[PATCH] D83508: [clangd][Hover] Don't use Decl if it is not related with tokens under cursor.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/Selection.cpp:227
 continue;
+  // Ignore tokens in disabled preprocessor sections.
+  if (Buf.expandedTokens(SM.getMacroArgExpandedLocation(T->location()))

ArcsinX wrote:
> sammccall wrote:
> > I think this is more work than we'd like to do in this loop (the whole file 
> > could be selected!) and it's also not obviously correct - it relies on the 
> > assumption that any token that doesn't expand to something by itself, isn't 
> > a macro argument or macro name, is part of an ignored region. (That may or 
> > may not be correct, but it's a nontrivial assumption to make here).
> > 
> > I think the API we need is something like `vector 
> > TokenBuffer::expansionsOverlapping(ArrayRef Spelled)`.
> > This requires a couple of binary searches on the TokenBuffer side to 
> > compute, and on this side we can just look at the spelled token ranges for 
> > empty expansions and mark them in a bitmap.
> > 
> > I'm happy to try to put together a TokenBuffer patch if this is too much of 
> > a yak-shave, though.
> >  it relies on the assumption that any token that doesn't expand to 
> > something by itself, isn't a macro argument or macro name, is part of an 
> > ignored region. (That may or may not be correct, but it's a nontrivial 
> > assumption to make here).
> 
> Example `#define FOO BAR`.
> Expanded tokens:
> Spelled tokens: `#`, `define`, `FOO`, `BAR`
> 
> I think we could ignore all except `FOO` in this case. Also I found similar 
> check in XRefs.cpp `bool tokenSpelledAt(SourceLocation SpellingLoc, const 
> syntax::TokenBuffer &TB)`
> 
> How to judge should we skip token or not if we do not have expanded tokens 
> for it? Do you have any advice here?
I'm not following, because I think we can ignore *all* those tokens. We care 
about macro names when the macros are *used* (tokens expanded from macro bodies 
are associated from the macro name at the expansion point). But not where 
they're defined.

> Also I found similar check in XRefs.cpp
Yes, there are a few restrictions there though:
 - it's only used for identifiers, so there are fewer cases to consider
 - performance doesn't matter at all, as it runs in response to an explicit 
action and runs on ~2 tokens

> How to judge should we skip token or not if we do not have expanded tokens 
> for it? Do you have any advice here?
I think we should just always skip in this case, let me try this out...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83508



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


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Michael Forster via Phabricator via cfe-commits
MForster created this revision.
MForster added reviewers: gribozavr2, milseman.
Herald added a reviewer: aaron.ballman.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is chery-picked from 
https://github.com/llvm/llvm-project-staging/commit/a14779f504b02ad0e4dbc39d6d10cadc7ed4cfd0
and adapted to updated Clang APIs.

ns_error_domain can be used by, e.g. NS_ERROR_ENUM, in order to
identify a global declaration representing the domain constant.

Introduces the attribute, Sema handling, diagnostics, and test case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84005

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

Index: clang/test/Analysis/ns_error_enum.m
===
--- /dev/null
+++ clang/test/Analysis/ns_error_enum.m
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -verify %s
+
+#define CF_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
+#define NS_ENUM(_type, _name) CF_ENUM(_type, _name)
+
+#define NS_ERROR_ENUM(_type, _name, _domain)  \
+  enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
+
+typedef NS_ENUM(unsigned, MyEnum) {
+  MyFirst,
+  MySecond,
+};
+
+typedef NS_ENUM(invalidType, MyInvalidEnum) {
+// expected-error@-1{{unknown type name 'invalidType'}}
+// expected-error@-2{{unknown type name 'invalidType'}}
+  MyFirstInvalid,
+  MySecondInvalid,
+};
+
+const char *MyErrorDomain;
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
+	MyErrFirst,
+	MyErrSecond,
+};
+struct __attribute__((ns_error_domain(MyErrorDomain))) MyStructErrorDomain {};
+
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnumInvalid, InvalidDomain) {
+	// expected-error@-1{{domain argument 'InvalidDomain' does not refer to global constant}}
+	MyErrFirstInvalid,
+	MyErrSecondInvalid,
+};
+
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnumInvalid, "domain-string");
+  // expected-error@-1{{domain argument must be an identifier}}
+
+int __attribute__((ns_error_domain(MyErrorDomain))) NotTagDecl;
+  // expected-error@-1{{ns_error_domain attribute only valid on enums, structs, and unions}}
+
+void foo() {}
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnumInvalidFunction, foo);
+  // expected-error@-1{{domain argument 'foo' does not refer to global constant}}
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -5327,6 +5327,39 @@
   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
 }
 
+static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
+  if (!isa(D)) {
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)
+<< S.getLangOpts().CPlusPlus;
+return;
+  }
+  IdentifierLoc *identLoc =
+  Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
+  if (!identLoc || !identLoc->Ident) {
+// Try to locate the argument directly
+SourceLocation loc = Attr.getLoc();
+if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
+  loc = Attr.getArgAsExpr(0)->getBeginLoc();
+
+S.Diag(loc, diag::err_nserrordomain_requires_identifier);
+return;
+  }
+
+  // Verify that the identifier is a valid decl in the C decl namespace
+  LookupResult lookupResult(S, DeclarationName(identLoc->Ident),
+SourceLocation(),
+Sema::LookupNameKind::LookupOrdinaryName);
+  if (!S.LookupName(lookupResult, S.TUScope) ||
+  !lookupResult.getAsSingle()) {
+S.Diag(identLoc->Loc, diag::err_nserrordomain_invalid_decl)
+<< identLoc->Ident;
+return;
+  }
+
+  D->addAttr(::new (S.Context)
+ NSErrorDomainAttr(S.Context, Attr, identLoc->Ident));
+}
+
 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
 
@@ -7098,6 +7131,9 @@
   case ParsedAttr::AT_ObjCBoxable:
 handleObjCBoxable(S, D, AL);
 break;
+  case ParsedAttr::AT_NSErrorDomain:
+handleNSErrorDomain(S, D, AL);
+break;
   case ParsedAttr::AT_CFAuditedTransfer:
 handleSimpleAttributeWithExclusions(S, D, AL);
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9446,6 +9446,14 @@
 def err_nsreturns_retained_attribute_mismatch : Error<
   "overriding method has mismatched ns_returns_%select{not_retained|retained}0"
   " attributes">;
+def err_nserrordomain_not_tagdecl : Error<
+  "ns_error_domain attribute only valid on "
+  "%select{enums, structs, and unions|enums, structs, unions, and classes}0">;
+def err_nserrordomain_i

[PATCH] D69318: [analyzer] Add SufficientSizeArrayIndexingChecker

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 marked 4 inline comments as done.
gamesh411 added a comment.

I am now experimenting with the suggestions. The other issues are on the 
worklist. Thanks for these so far.




Comment at: 
clang/lib/StaticAnalyzer/Checkers/SufficientSizeArrayIndexingChecker.cpp:50
+  if (isa(Index->IgnoreParenCasts()))
+return;
+

balazske wrote:
> gamesh411 wrote:
> > balazske wrote:
> > > `if (isa(Index))` should be used. `IntegerLiteral` is a 
> > > subclass of `Expr`, not a `QualType`.
> > The way I have structured the code is very misleading, sorry for that, I 
> > will move the type extraction if lower, where it is actually used.
> Probably function `SVB.getConstantVal` can be used to test if there is a 
> (compile-time) constant passed to the index. But it may be value of a (const) 
> variable.
Yes, that is a design question, should the checker warn if the index is not a 
literal but a const variable like:
```
constexpr char SpecialIndex = 12;
int Array[300] = make_array();
Array[SpecialIndex]; // should we warn in this case? because now we do,
 // as the indexing expression is not a literal.
```



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:48
+void ignore_literal_indexing_with_parens() {
+  char a = exactly_4byte_signed_range[(32)]; // nowarning
+}

balazske wrote:
> Does this work in `[32 + 1]` case?
It should, I will add a case for it.



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:106
+if (choice >= 1) {
+  c = f(choice)[four_byte_signed_index]; // nowarnining // the value is 
one or two, f returns an array that is correct in size
+}

balazske wrote:
> `choice` can be here only 1. If it could be 1 or 2 we should get no warning 
> because the array size may be good or bad. But to test that it is enough that 
> `choice` can have any value, like in `test_symbolic_index_handling4`.
Yes, this test is a bit redundant, should I remove it in your opinion?



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:37
+const short two_byte_signed_index = 1; // sizeof(short) == 2
+const int four_byte_signed_index = 1;  // sizeof(int) == 4
+

balazske wrote:
> gamesh411 wrote:
> > balazske wrote:
> > > I do not know if it is safe to make such assumptions about `sizeof`.
> > You are definitely right! However it is common as per:
> > https://en.cppreference.com/w/cpp/language/types#Data_models
> > ```
> > Data models
> > 
> > The choices made by each implementation about the sizes of the fundamental 
> > types are collectively known as data model. Four data models found wide 
> > acceptance:
> > 
> > 32 bit systems:
> > 
> > LP32 or 2/4/4 (int is 16-bit, long and pointer are 32-bit) 
> > 
> > Win16 API 
> > 
> > ILP32 or 4/4/4 (int, long, and pointer are 32-bit); 
> > 
> > Win32 API
> > Unix and Unix-like systems (Linux, macOS) 
> > 
> > 64 bit systems:
> > 
> > LLP64 or 4/4/8 (int and long are 32-bit, pointer is 64-bit) 
> > 
> > Win64 API 
> > 
> > LP64 or 4/8/8 (int is 32-bit, long and pointer are 64-bit) 
> > 
> > Unix and Unix-like systems (Linux, macOS) 
> > 
> > Other models are very rare. For example, ILP64 (8/8/8: int, long, and 
> > pointer are 64-bit) only appeared in some early 64-bit Unix systems (e.g. 
> > Unicos on Cray). 
> > ```
> > Only ILP32 has 16 bit ints.
> > Next idea would be to use fixed-width integer types from `cstdint`. But 
> > tests should not use system headers, and there are mentions in test files 
> > to `int32_t`, howevery they are just typedefs for int. And I think we 
> > maintaining a whole standard library headers is a bit too much a hassle.
> Still it would be good to check if the test passes on all the buildbots.
I'm afraid we can only test that by committing, as there is no other way to 
submit a build-job ( not that I am aware of, any information in that regard is 
welcome :) ).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69318



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


[PATCH] D83149: [gcov] Add __gcov_dump/__gcov_reset and delete __gcov_flush

2020-07-17 Thread serge via Phabricator via cfe-commits
serge-sans-paille accepted this revision.
serge-sans-paille added a comment.
This revision is now accepted and ready to land.

LGTM, I still would appreciate @calixte feedback here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83149



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


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1860
+def NSErrorDomain : Attr {
+  let Spellings = [GNU<"ns_error_domain">];
+  let Args = [IdentifierArgument<"ErrorDomain">];

Could we try to add a list of subjects here? It seems like it is a type-only 
attribute, and most likely enum-only.

let Subjects = SubjectList<[Enum]>;



Comment at: clang/include/clang/Basic/AttrDocs.td:3317
+def NSErrorDomainDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{

Shouldn't the category be DocCatType since it is a type attribute?



Comment at: clang/include/clang/Basic/AttrDocs.td:3319
+  let Content = [{
+The ``ns_error_domain`` attribute indicates a global constant representing the 
error domain.
+  }];

I think we should try to expand the docs. For example:

In Cocoa frameworks in Objective-C, one can group related error codes in enums, 
and categorize these enums with error domains.

The ``ns_error_domain`` attribute specifies the error domain that error codes 
belong to. This attribute is attached to enums that describe error codes.

This metadata is useful for documentation purposes, for static analysis, and 
for improving interoperability between Objective-C and Swift. It is not used 
for code generation in Objective-C.

For example:

(insert an example from tests)





Comment at: clang/test/Analysis/ns_error_enum.m:1
+// RUN: %clang_cc1 -verify %s
+

This file is a `.m` -- any specific reason? I'd call it `.c` and run the test 
in C, Objective-C, and C++ modes (enums might work slightly differently, the 
name lookup functionality might work differently).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D83826: [clangd] Don't send invalid messages from remote index

2020-07-17 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 278682.
kbobyrev marked 2 inline comments as done.
kbobyrev added a comment.

Refactor marshalling into a class, log errors only on the high level.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83826

Files:
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -13,6 +13,7 @@
 #include "index/Serialization.h"
 #include "index/Symbol.h"
 #include "index/SymbolID.h"
+#include "index/SymbolLocation.h"
 #include "index/remote/marshalling/Marshalling.h"
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/SmallString.h"
@@ -39,29 +40,35 @@
 TEST(RemoteMarshallingTest, URITranslation) {
   llvm::BumpPtrAllocator Arena;
   llvm::UniqueStringSaver Strings(Arena);
+  Marshaller ProtobufMarshaller(
+  testPath("remote/machine/projects/llvm-project/"),
+  testPath("home/my-projects/llvm-project/"));
   clangd::Ref Original;
   Original.Location.FileURI =
   testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
   "clangd/unittests/remote/MarshallingTests.cpp",
   Strings);
-  auto Serialized =
-  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
-  EXPECT_EQ(Serialized.location().file_path(),
+  auto Serialized = ProtobufMarshaller.toProtobuf(Original);
+  EXPECT_TRUE(Serialized);
+  EXPECT_EQ(Serialized->location().file_path(),
 "clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
-  const std::string LocalIndexPrefix = testPath("local/machine/project/");
-  auto Deserialized = fromProtobuf(Serialized, &Strings,
-   testPath("home/my-projects/llvm-project/"));
+  auto Deserialized = ProtobufMarshaller.fromProtobuf(*Serialized);
   EXPECT_TRUE(Deserialized);
-  EXPECT_EQ(Deserialized->Location.FileURI,
-testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
-"clangd/unittests/remote/MarshallingTests.cpp",
-Strings));
+  EXPECT_STREQ(Deserialized->Location.FileURI,
+   testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+   "clangd/unittests/remote/MarshallingTests.cpp",
+   Strings));
+
+  // Can't have empty paths.
+  *Serialized->mutable_location()->mutable_file_path() = std::string();
+  Deserialized = ProtobufMarshaller.fromProtobuf(*Serialized);
+  EXPECT_FALSE(Deserialized);
 
   clangd::Ref WithInvalidURI;
-  // Invalid URI results in empty path.
+  // Invalid URI results in serialization failure.
   WithInvalidURI.Location.FileURI = "This is not a URI";
-  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
-  EXPECT_EQ(Serialized.location().file_path(), "");
+  Serialized = ProtobufMarshaller.toProtobuf(WithInvalidURI);
+  EXPECT_FALSE(Serialized);
 
   // Can not use URIs with scheme different from "file".
   auto UnittestURI =
@@ -69,15 +76,15 @@
   EXPECT_TRUE(bool(UnittestURI));
   WithInvalidURI.Location.FileURI =
   Strings.save(UnittestURI->toString()).begin();
-  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
-  EXPECT_EQ(Serialized.location().file_path(), "");
+  Serialized = ProtobufMarshaller.toProtobuf(WithInvalidURI);
+  EXPECT_FALSE(Serialized);
 
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
   Ref WithAbsolutePath;
   *WithAbsolutePath.mutable_location()->mutable_file_path() =
   "/usr/local/user/home/HelloWorld.cpp";
-  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
-  // Paths transmitted over the wire can not be absolute, they have to be
-  // relative.
+  Deserialized = ProtobufMarshaller.fromProtobuf(WithAbsolutePath);
   EXPECT_FALSE(Deserialized);
 }
 
@@ -128,48 +135,63 @@
 
   Sym.Flags = clangd::Symbol::SymbolFlag::IndexedForCodeCompletion;
 
+  Marshaller ProtobufMarshaller(testPath("home/"), testPath("home/"));
+
   // Check that symbols are exactly the same if the path to indexed project is
   // the same on indexing machine and the client.
-  auto Serialized = toProtobuf(Sym, testPath("home/"));
-  auto Deserialized = fromProtobuf(Serialized, &Strings, testPath("home/"));
+  auto Serialized = ProtobufMarshaller.toProtobuf(Sym);
+  EXPECT_TRUE(Serialized);
+  auto Deserialized = ProtobufMarshaller.fromProtobuf(*Serialized);
   EXPECT_TRUE(Deseria

[PATCH] D83826: [clangd] Don't send invalid messages from remote index

2020-07-17 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 278683.
kbobyrev added a comment.

Remove (now empty) Marshalling.h file comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83826

Files:
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -13,6 +13,7 @@
 #include "index/Serialization.h"
 #include "index/Symbol.h"
 #include "index/SymbolID.h"
+#include "index/SymbolLocation.h"
 #include "index/remote/marshalling/Marshalling.h"
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/SmallString.h"
@@ -39,29 +40,35 @@
 TEST(RemoteMarshallingTest, URITranslation) {
   llvm::BumpPtrAllocator Arena;
   llvm::UniqueStringSaver Strings(Arena);
+  Marshaller ProtobufMarshaller(
+  testPath("remote/machine/projects/llvm-project/"),
+  testPath("home/my-projects/llvm-project/"));
   clangd::Ref Original;
   Original.Location.FileURI =
   testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
   "clangd/unittests/remote/MarshallingTests.cpp",
   Strings);
-  auto Serialized =
-  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
-  EXPECT_EQ(Serialized.location().file_path(),
+  auto Serialized = ProtobufMarshaller.toProtobuf(Original);
+  EXPECT_TRUE(Serialized);
+  EXPECT_EQ(Serialized->location().file_path(),
 "clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
-  const std::string LocalIndexPrefix = testPath("local/machine/project/");
-  auto Deserialized = fromProtobuf(Serialized, &Strings,
-   testPath("home/my-projects/llvm-project/"));
+  auto Deserialized = ProtobufMarshaller.fromProtobuf(*Serialized);
   EXPECT_TRUE(Deserialized);
-  EXPECT_EQ(Deserialized->Location.FileURI,
-testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
-"clangd/unittests/remote/MarshallingTests.cpp",
-Strings));
+  EXPECT_STREQ(Deserialized->Location.FileURI,
+   testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+   "clangd/unittests/remote/MarshallingTests.cpp",
+   Strings));
+
+  // Can't have empty paths.
+  *Serialized->mutable_location()->mutable_file_path() = std::string();
+  Deserialized = ProtobufMarshaller.fromProtobuf(*Serialized);
+  EXPECT_FALSE(Deserialized);
 
   clangd::Ref WithInvalidURI;
-  // Invalid URI results in empty path.
+  // Invalid URI results in serialization failure.
   WithInvalidURI.Location.FileURI = "This is not a URI";
-  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
-  EXPECT_EQ(Serialized.location().file_path(), "");
+  Serialized = ProtobufMarshaller.toProtobuf(WithInvalidURI);
+  EXPECT_FALSE(Serialized);
 
   // Can not use URIs with scheme different from "file".
   auto UnittestURI =
@@ -69,15 +76,15 @@
   EXPECT_TRUE(bool(UnittestURI));
   WithInvalidURI.Location.FileURI =
   Strings.save(UnittestURI->toString()).begin();
-  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
-  EXPECT_EQ(Serialized.location().file_path(), "");
+  Serialized = ProtobufMarshaller.toProtobuf(WithInvalidURI);
+  EXPECT_FALSE(Serialized);
 
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
   Ref WithAbsolutePath;
   *WithAbsolutePath.mutable_location()->mutable_file_path() =
   "/usr/local/user/home/HelloWorld.cpp";
-  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
-  // Paths transmitted over the wire can not be absolute, they have to be
-  // relative.
+  Deserialized = ProtobufMarshaller.fromProtobuf(WithAbsolutePath);
   EXPECT_FALSE(Deserialized);
 }
 
@@ -128,48 +135,63 @@
 
   Sym.Flags = clangd::Symbol::SymbolFlag::IndexedForCodeCompletion;
 
+  Marshaller ProtobufMarshaller(testPath("home/"), testPath("home/"));
+
   // Check that symbols are exactly the same if the path to indexed project is
   // the same on indexing machine and the client.
-  auto Serialized = toProtobuf(Sym, testPath("home/"));
-  auto Deserialized = fromProtobuf(Serialized, &Strings, testPath("home/"));
+  auto Serialized = ProtobufMarshaller.toProtobuf(Sym);
+  EXPECT_TRUE(Serialized);
+  auto Deserialized = ProtobufMarshaller.fromProtobuf(*Serialized);
   EXPECT_TRUE(Deserialized);
   EXPECT_EQ(toYAML(Sym), toYAML(*Deserialized));
   // Se

[PATCH] D72932: [ARM] Follow AACPS standard for volatile bit-fields access width

2020-07-17 Thread Oliver Stannard (Linaro) via Phabricator via cfe-commits
ostannard added a comment.

You haven't addressed my earlier inline comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72932



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


[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: cfe-commits, usaxena95, kadircet, ilya-biryukov.
Herald added a project: clang.

This allows efficiently accessing all expansions (without iterating over each
token and searching), and also identifying tokens within a range that are
affected by the preprocessor (which is how clangd will use it).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84009

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

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -53,6 +53,7 @@
 using namespace clang::syntax;
 
 using llvm::ValueIs;
+using ::testing::_;
 using ::testing::AllOf;
 using ::testing::Contains;
 using ::testing::ElementsAre;
@@ -755,7 +756,7 @@
   EXPECT_THAT(Buffer.expandedTokens(SourceRange()), testing::IsEmpty());
 }
 
-TEST_F(TokenBufferTest, ExpansionStartingAt) {
+TEST_F(TokenBufferTest, ExpansionsOverlapping) {
   // Object-like macro expansions.
   recordTokens(R"cpp(
 #define FOO 3+4
@@ -763,17 +764,25 @@
 int b = FOO 2;
   )cpp");
 
-  llvm::ArrayRef Foo1 = findSpelled("FOO 1").drop_back();
+  llvm::ArrayRef Foo1 = findSpelled("FOO 1");
   EXPECT_THAT(
   Buffer.expansionStartingAt(Foo1.data()),
-  ValueIs(IsExpansion(SameRange(Foo1),
+  ValueIs(IsExpansion(SameRange(Foo1.drop_back()),
   SameRange(findExpanded("3 + 4 1").drop_back();
+  EXPECT_THAT(
+  Buffer.expansionsAffecting(Foo1),
+  ElementsAre(IsExpansion(SameRange(Foo1.drop_back()),
+  SameRange(findExpanded("3 + 4 1").drop_back();
 
-  llvm::ArrayRef Foo2 = findSpelled("FOO 2").drop_back();
+  llvm::ArrayRef Foo2 = findSpelled("FOO 2");
   EXPECT_THAT(
   Buffer.expansionStartingAt(Foo2.data()),
-  ValueIs(IsExpansion(SameRange(Foo2),
+  ValueIs(IsExpansion(SameRange(Foo2.drop_back()),
   SameRange(findExpanded("3 + 4 2").drop_back();
+  EXPECT_THAT(
+  Buffer.expansionsAffecting(llvm::makeArrayRef(Foo1.begin(), Foo2.end())),
+  ElementsAre(IsExpansion(SameRange(Foo1.drop_back()), _),
+  IsExpansion(SameRange(Foo2.drop_back()), _)));
 
   // Function-like macro expansions.
   recordTokens(R"cpp(
@@ -798,6 +807,11 @@
   for (const auto &T : ID2.drop_front())
 EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
 
+  EXPECT_THAT(Buffer.expansionsAffecting(llvm::makeArrayRef(
+  findSpelled("1 + 2").data(), findSpelled("4").data())),
+  ElementsAre(IsExpansion(SameRange(ID1), _),
+  IsExpansion(SameRange(ID2), _)));
+
   // PP directives.
   recordTokens(R"cpp(
 #define FOO 1
@@ -823,6 +837,11 @@
   // Only the first spelled token should be found.
   for (const auto &T : PragmaOnce.drop_front())
 EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
+
+  EXPECT_THAT(
+  Buffer.expansionsAffecting(findSpelled("FOO ; # pragma")),
+  ElementsAre(IsExpansion(SameRange(findSpelled("FOO ;").drop_back()), _),
+  IsExpansion(SameRange(PragmaOnce), _)));
 }
 
 TEST_F(TokenBufferTest, TokensToFileRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -249,13 +249,7 @@
 TokenBuffer::expandedForSpelled(llvm::ArrayRef Spelled) const {
   if (Spelled.empty())
 return {};
-  assert(Spelled.front().location().isFileID());
-
-  auto FID = sourceManager().getFileID(Spelled.front().location());
-  auto It = Files.find(FID);
-  assert(It != Files.end());
-
-  const MarkedFile &File = It->second;
+  const MarkedFile &File = fileForSpelled(Spelled);
   // `Spelled` must be a subrange of `File.SpelledTokens`.
   assert(File.SpelledTokens.data() <= Spelled.data());
   assert(&Spelled.back() <=
@@ -395,16 +389,34 @@
   : LastSpelled + 1);
 }
 
+TokenBuffer::Expansion TokenBuffer::makeExpansion(const MarkedFile &F,
+  const Mapping &M) const {
+  Expansion E;
+  E.Spelled = llvm::makeArrayRef(F.SpelledTokens.data() + M.BeginSpelled,
+ F.SpelledTokens.data() + M.EndSpelled);
+  E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M.BeginExpanded,
+  ExpandedTokens.data() + M.EndExpanded);
+  return E;
+}
+
+const TokenBuffer::MarkedFile &
+TokenBuffer::fileForSpelled(llvm::ArrayRef Spelled) const {
+  assert(!Spelled.empty());
+  assert(Spelled.front().location().isFileID() && "not a spelled token");
+  auto FileIt = Files.find(SourceMgr->getFileID(Spelled.front().location()));
+  assert(FileIt != Files.end() && "file not t

[clang] bb160e7 - [Sema][AArch64] Add parsing support for arm_sve_vector_bits attribute

2020-07-17 Thread Cullen Rhodes via cfe-commits

Author: Cullen Rhodes
Date: 2020-07-17T10:06:54Z
New Revision: bb160e769dbef25fe0aa130c71458a8f686ccf80

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

LOG: [Sema][AArch64] Add parsing support for arm_sve_vector_bits attribute

Summary:

This patch implements parsing support for the 'arm_sve_vector_bits' type
attribute, defined by the Arm C Language Extensions (ACLE, version 00bet5,
section 3.7.3) for SVE [1].

The purpose of this attribute is to define fixed-length (VLST) versions
of existing sizeless types (VLAT). For example:

#if __ARM_FEATURE_SVE_BITS==512
typedef svint32_t fixed_svint32_t __attribute__((arm_sve_vector_bits(512)));
#endif

Creates a type 'fixed_svint32_t' that is a fixed-length version of
'svint32_t' that is normal-sized (rather than sizeless) and contains
exactly 512 bits. Unlike 'svint32_t', this type can be used in places
such as structs and arrays where sizeless types can't.

Implemented in this patch is the following:

  * Defined and tested attribute taking single argument.
  * Checks the argument is an integer constant expression.
  * Attribute can only be attached to a single SVE vector or predicate
type, excluding tuple types such as svint32x4_t.
  * Added the `-msve-vector-bits=` flag. When specified the
`__ARM_FEATURE_SVE_BITS__EXPERIMENTAL` macro is defined.
  * Added a language option to store the vector size specified by the
`-msve-vector-bits=` flag. This is used to validate `N ==
__ARM_FEATURE_SVE_BITS`, where N is the number of bits passed to the
attribute and `__ARM_FEATURE_SVE_BITS` is the feature macro defined under
the same flag.

The `__ARM_FEATURE_SVE_BITS` macro will be made non-experimental in the final
patch of the series.

[1] https://developer.arm.com/documentation/100987/latest

This is patch 1/4 of a patch series.

Reviewers: sdesmalen, rsandifo-arm, efriedma, ctetreau, cameron.mcinally, 
rengolin, aaron.ballman

Reviewed By: sdesmalen, aaron.ballman

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

Added: 
clang/test/Driver/aarch64-sve-vector-bits.c
clang/test/Sema/attr-arm-sve-vector-bits.c

Modified: 
clang/include/clang/AST/Type.h
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/AST/Type.cpp
clang/lib/AST/TypePrinter.cpp
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Sema/SemaType.cpp
clang/test/Preprocessor/aarch64-target-features.c

Removed: 




diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 0fc50e0e799f..131658fbc8c4 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1925,6 +1925,11 @@ class alignas(8) Type : public ExtQualsTypeCommonBase {
   bool isSizelessType() const;
   bool isSizelessBuiltinType() const;
 
+  /// Determines if this is a sizeless type supported by the
+  /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
+  /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
+  bool isVLSTBuiltinType() const;
+
   /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
   /// object types, function types, and incomplete types.
 

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index bc4a380545af..8e0c57bd2efd 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1532,6 +1532,12 @@ def NeonVectorType : TypeAttr {
   let ASTNode = 0;
 }
 
+def ArmSveVectorBits : TypeAttr {
+  let Spellings = [GNU<"arm_sve_vector_bits">];
+  let Args = [IntArgument<"NumBits">];
+  let Documentation = [ArmSveVectorBitsDocs];
+}
+
 def ArmMveStrictPolymorphism : TypeAttr, TargetSpecificAttr {
   let Spellings = [Clang<"__clang_arm_mve_strict_polymorphism">];
   let Documentation = [ArmMveStrictPolymorphismDocs];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 3cba3a3d96f9..c835e6da04d5 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4855,6 +4855,43 @@ close the handle. It is also assumed to require an open 
handle to work with.
   }];
 }
 
+def ArmSveVectorBitsDocs : Documentation {
+  let Category = DocCatType;
+  let Content = [{
+The ``arm_sve_vector_bits(N)`` attribute is defined by the Arm C Language
+Extensions (ACLE) for SVE. It is used to define fixed-length (VLST) variants of
+sizeless types (VLAT)

[PATCH] D83550: [PATCH 1/4][Sema][AArch64] Add parsing support for arm_sve_vector_bits attribute

2020-07-17 Thread Cullen Rhodes via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
c-rhodes marked an inline comment as done.
Closed by commit rGbb160e769dbe: [Sema][AArch64] Add parsing support for 
arm_sve_vector_bits attribute (authored by c-rhodes).

Changed prior to commit:
  https://reviews.llvm.org/D83550?vs=278507&id=278702#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83550

Files:
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/Driver/aarch64-sve-vector-bits.c
  clang/test/Preprocessor/aarch64-target-features.c
  clang/test/Sema/attr-arm-sve-vector-bits.c

Index: clang/test/Sema/attr-arm-sve-vector-bits.c
===
--- /dev/null
+++ clang/test/Sema/attr-arm-sve-vector-bits.c
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -fsyntax-only -verify -msve-vector-bits=128 -fallow-half-arguments-and-returns %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -fsyntax-only -verify -msve-vector-bits=256 -fallow-half-arguments-and-returns %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -fsyntax-only -verify -msve-vector-bits=512 -fallow-half-arguments-and-returns %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -fsyntax-only -verify -msve-vector-bits=1024 -fallow-half-arguments-and-returns %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -fsyntax-only -verify -msve-vector-bits=2048 -fallow-half-arguments-and-returns %s
+
+#define N __ARM_FEATURE_SVE_BITS_EXPERIMENTAL
+
+typedef __SVInt8_t svint8_t;
+typedef __SVInt16_t svint16_t;
+typedef __SVInt32_t svint32_t;
+typedef __SVInt64_t svint64_t;
+typedef __SVUint8_t svuint8_t;
+typedef __SVUint16_t svuint16_t;
+typedef __SVUint32_t svuint32_t;
+typedef __SVUint64_t svuint64_t;
+typedef __SVFloat16_t svfloat16_t;
+typedef __SVFloat32_t svfloat32_t;
+typedef __SVFloat64_t svfloat64_t;
+
+#if defined(__ARM_FEATURE_SVE_BF16)
+typedef __SVBFloat16_t svbfloat16_t;
+#endif
+
+typedef __SVBool_t svbool_t;
+
+// Define valid fixed-width SVE types
+typedef svint8_t fixed_int8_t __attribute__((arm_sve_vector_bits(N)));
+typedef svint16_t fixed_int16_t __attribute__((arm_sve_vector_bits(N)));
+typedef svint32_t fixed_int32_t __attribute__((arm_sve_vector_bits(N)));
+typedef svint64_t fixed_int64_t __attribute__((arm_sve_vector_bits(N)));
+
+typedef svuint8_t fixed_uint8_t __attribute__((arm_sve_vector_bits(N)));
+typedef svuint16_t fixed_uint16_t __attribute__((arm_sve_vector_bits(N)));
+typedef svuint32_t fixed_uint32_t __attribute__((arm_sve_vector_bits(N)));
+typedef svuint64_t fixed_uint64_t __attribute__((arm_sve_vector_bits(N)));
+
+typedef svfloat16_t fixed_float16_t __attribute__((arm_sve_vector_bits(N)));
+typedef svfloat32_t fixed_float32_t __attribute__((arm_sve_vector_bits(N)));
+typedef svfloat64_t fixed_float64_t __attribute__((arm_sve_vector_bits(N)));
+
+typedef svbfloat16_t fixed_bfloat16_t __attribute__((arm_sve_vector_bits(N)));
+
+typedef svbool_t fixed_bool_t __attribute__((arm_sve_vector_bits(N)));
+
+// Attribute must have a single argument
+typedef svint8_t no_argument __attribute__((arm_sve_vector_bits)); // expected-error {{'arm_sve_vector_bits' attribute takes one argument}}
+typedef svint8_t two_arguments __attribute__((arm_sve_vector_bits(2, 4))); // expected-error {{'arm_sve_vector_bits' attribute takes one argument}}
+
+// The number of SVE vector bits must be an integer constant expression
+typedef svint8_t non_int_size1 __attribute__((arm_sve_vector_bits(2.0)));   // expected-error {{'arm_sve_vector_bits' attribute requires an integer constant}}
+typedef svint8_t non_int_size2 __attribute__((arm_sve_vector_bits("256"))); // expected-error {{'arm_sve_vector_bits' attribute requires an integer constant}}
+
+typedef __clang_svint8x2_t svint8x2_t;
+typedef __clang_svfloat32x3_t svfloat32x3_t;
+
+// Attribute must be attached to a single SVE vector or predicate type.
+typedef void *badtype1 __attribute__((arm_sve_vector_bits(N))); // expected-error {{'arm_sve_vector_bits' attribute applied to non-SVE type 'void *'}}
+typedef int badtype2 __attribute__((arm_sve_vector_bits(N)));   // expected-error {{'arm_sve_vector_bits' attribu

[PATCH] D69318: [analyzer] Add SufficientSizeArrayIndexingChecker

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 278703.
gamesh411 added a comment.

move tests to one file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69318

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/SufficientSizeArrayIndexingChecker.cpp
  clang/test/Analysis/sufficient-size-array-indexing.c

Index: clang/test/Analysis/sufficient-size-array-indexing.c
===
--- /dev/null
+++ clang/test/Analysis/sufficient-size-array-indexing.c
@@ -0,0 +1,142 @@
+// RUN: %clang_analyze_cc1 -triple i386 -analyzer-checker=core,alpha.core.SufficientSizeArrayIndexing %s -verify
+// RUN: %clang_analyze_cc1 -triple x86_64 -analyzer-checker=core,alpha.core.SufficientSizeArrayIndexing %s -verify
+
+#include "Inputs/system-header-simulator.h"
+
+const unsigned long long one_byte_signed_max = (1ULL << 7) - 1;
+const unsigned long long two_byte_signed_max = (1ULL << 15) - 1;
+const unsigned long long four_byte_signed_max = (1ULL << 31) - 1;
+
+const unsigned long long one_byte_unsigned_max = (1ULL << 8) - 1;
+const unsigned long long two_byte_unsigned_max = (1ULL << 16) - 1;
+const unsigned long long four_byte_unsigned_max = (1ULL << 32) - 1;
+
+char smaller_than_1byte_signed_range[one_byte_signed_max];
+char exactly_1byte_signed_range[one_byte_signed_max + 1];
+char greater_than_1byte_signed_range[one_byte_signed_max + 2];
+
+char smaller_than_2byte_signed_range[two_byte_signed_max];
+char exactly_2byte_signed_range[two_byte_signed_max + 1];
+char greater_than_2byte_signed_range[two_byte_signed_max + 2];
+
+char smaller_than_4byte_signed_range[four_byte_signed_max];
+char exactly_4byte_signed_range[four_byte_signed_max + 1];
+char greater_than_4byte_signed_range[four_byte_signed_max + 2];
+
+char smaller_than_1byte_unsigned_range[one_byte_unsigned_max];
+char exactly_1byte_unsigned_range[one_byte_unsigned_max + 1];
+char greater_than_1byte_unsigned_range[one_byte_unsigned_max + 2];
+
+char smaller_than_2byte_unsigned_range[two_byte_unsigned_max];
+char exactly_2byte_unsigned_range[two_byte_unsigned_max + 1];
+char greater_than_2byte_unsigned_range[two_byte_unsigned_max + 2];
+
+char smaller_than_4byte_unsigned_range[four_byte_unsigned_max];
+
+const char one_byte_signed_index = 1;  // sizeof(char) == 1
+const short two_byte_signed_index = 1; // sizeof(short) == 2
+const int four_byte_signed_index = 1;  // sizeof(int) == 4
+
+const unsigned char one_byte_unsigned_index = 1;
+const unsigned short two_byte_unsigned_index = 1;
+const unsigned int four_byte_unsigned_index = 1;
+
+void ignore_literal_indexing() {
+  char a = exactly_4byte_signed_range[32]; // nowarning
+}
+
+void ignore_literal_indexing_with_parens() {
+  char a = exactly_4byte_signed_range[(32)]; // nowarning
+}
+
+void range_check_one_byte_index() {
+  char r;
+  char *pr = &r;
+  *pr = smaller_than_1byte_signed_range[one_byte_signed_index]; // nowarning
+  *pr = exactly_1byte_signed_range[one_byte_signed_index];  // nowarning
+  *pr = greater_than_1byte_signed_range[one_byte_signed_index]; // expected-warning{{Index type cannot cover the whole range of the array's index set, which may result in memory waste in form of unindexable elements. Consider using a type with greater maximum value}}
+  *pr = smaller_than_1byte_unsigned_range[one_byte_unsigned_index]; // nowarning
+  *pr = exactly_1byte_unsigned_range[one_byte_unsigned_index];  // nowarning
+  *pr = greater_than_1byte_unsigned_range[one_byte_unsigned_index]; // expected-warning{{Index type cannot cover the whole range of the array's index set, which may result in memory waste in form of unindexable elements. Consider using a type with greater maximum value}}
+}
+
+void range_check_two_byte_index() {
+  char r;
+  char *pr = &r;
+  *pr = smaller_than_2byte_signed_range[two_byte_signed_index]; // nowarning
+  *pr = exactly_2byte_signed_range[two_byte_signed_index];  // nowarning
+  *pr = greater_than_2byte_signed_range[two_byte_signed_index]; // expected-warning{{Index type cannot cover the whole range of the array's index set, which may result in memory waste in form of unindexable elements. Consider using a type with greater maximum value}}
+  *pr = smaller_than_2byte_unsigned_range[two_byte_unsigned_index]; // nowarning
+  *pr = exactly_2byte_unsigned_range[two_byte_unsigned_index];  // nowarning
+  *pr = greater_than_2byte_unsigned_range[two_byte_unsigned_index]; // expected-warning{{Index type cannot cover the whole range of the array's index set, which may result in memory waste in form of unindexable elements. Consider using a type with greater maximum value}}
+}
+
+void range_check_four_byte_index() {
+  char r;
+  char *pr = &r;
+  *pr = smaller_than_4byte_signed_range[four_byte_signed_index]; // nowarning
+  *pr =

[PATCH] D84012: [clangd] Exclude preprocessed-to-nothing tokens from selectionThis prevents selection of empty preprocessor entities (like #define directives,or text in disabled sections) creating a s

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: ArcsinX, kadircet.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

Based on D83508  by Aleksandr Platonov.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84012

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -182,6 +182,14 @@
   )cpp",
   nullptr,
   },
+  {
+  R"cpp(
+void foo();
+#define CALL_FUNCTION(X) X()
+void bar() { CALL_FUNCTION(foo^)^; }
+  )cpp",
+  nullptr,
+  },
   {
   R"cpp(
 struct S { S(const char*); };
@@ -388,7 +396,8 @@
 void test(S2 s2) {
   s2[[-^>]]f();
 }
-  )cpp", "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
+  )cpp",
+   "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
   };
   for (const Case &C : Cases) {
 trace::TestTracer Tracer;
@@ -538,7 +547,33 @@
   auto AST = TU.build();
   auto T = makeSelectionTree(Case, AST);
 
-  EXPECT_EQ("WhileStmt", T.commonAncestor()->kind());
+  EXPECT_EQ(nullptr, T.commonAncestor());
+}
+
+TEST(SelectionTest, DisabledPreprocessor) {
+  const char *Case = R"cpp(
+namespace ns {
+#define FOO B^AR
+}
+  )cpp";
+  Annotations Test(Case);
+  auto TU = TestTU::withCode(Test.code());
+  auto AST = TU.build();
+  auto T = makeSelectionTree(Case, AST);
+  EXPECT_EQ(T.commonAncestor(), nullptr);
+
+  Case = R"cpp(
+namespace ns {
+#if 0
+void fu^nc();
+#endif
+}
+  )cpp";
+  Test = Annotations(Case);
+  TU = TestTU::withCode(Test.code());
+  AST = TU.build();
+  T = makeSelectionTree(Case, AST);
+  EXPECT_EQ(T.commonAncestor(), nullptr);
 }
 
 TEST(SelectionTest, MacroArgExpansion) {
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -220,14 +220,26 @@
 SelFirst, AllSpelledTokens.end(), [&](const syntax::Token &Tok) {
   return SM.getFileOffset(Tok.location()) < SelEnd;
 });
+auto Sel = llvm::makeArrayRef(SelFirst, SelLimit);
+// Find which of these are preprocessed to nothing and should be ignored.
+std::vector PPIgnored(Sel.size(), false);
+for (const syntax::TokenBuffer::Expansion &X :
+ Buf.expansionsAffecting(Sel)) {
+  if (X.Expanded.empty()) {
+for (const syntax::Token &Tok : X.Spelled) {
+  if (&Tok >= SelFirst && &Tok < SelLimit)
+PPIgnored[&Tok - SelFirst] = true;
+}
+  }
+}
 // Precompute selectedness and offset for selected spelled tokens.
-for (const syntax::Token *T = SelFirst; T < SelLimit; ++T) {
-  if (shouldIgnore(*T))
+for (unsigned I = 0; I < Sel.size(); ++I) {
+  if (shouldIgnore(Sel[I]) || PPIgnored[I])
 continue;
   SpelledTokens.emplace_back();
   Tok &S = SpelledTokens.back();
-  S.Offset = SM.getFileOffset(T->location());
-  if (S.Offset >= SelBegin && S.Offset + T->length() <= SelEnd)
+  S.Offset = SM.getFileOffset(Sel[I].location());
+  if (S.Offset >= SelBegin && S.Offset + Sel[I].length() <= SelEnd)
 S.Selected = SelectionTree::Complete;
   else
 S.Selected = SelectionTree::Partial;


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -182,6 +182,14 @@
   )cpp",
   nullptr,
   },
+  {
+  R"cpp(
+void foo();
+#define CALL_FUNCTION(X) X()
+void bar() { CALL_FUNCTION(foo^)^; }
+  )cpp",
+  nullptr,
+  },
   {
   R"cpp(
 struct S { S(const char*); };
@@ -388,7 +396,8 @@
 void test(S2 s2) {
   s2[[-^>]]f();
 }
-  )cpp", "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
+  )cpp",
+   "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
   };
   for (const Case &C : Cases) {
 trace::TestTracer Tracer;
@@ -538,7 +547,33 @@
   auto AST = TU.build();
   auto T = makeSelectionTree(Case, AST);
 
-  EXPECT_EQ("WhileStmt", T.commonAncestor()->kind());
+  EXPECT_EQ(nullptr, T.commonAncestor());
+}
+
+TEST(SelectionTest, DisabledPreprocessor) {
+  const char *Case = R"cpp(
+namespace ns {
+#define FOO B^AR
+}
+  )cpp";
+  Annotations Test(Case);
+  auto TU = TestTU::with

[PATCH] D83508: [clangd][Hover] Don't use Decl if it is not related with tokens under cursor.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Tried this out in D84012 /D84009 
. Works pretty well, and I think the API is a 
useful and natural addition to TokenBuffer.
Maybe this is too much complexity though?

(Mostly here i'm worrying about the case when the user hits "select all" in 
their editor and we get a code action request or so - it seems wasteful to 
query the token buffer for every token in the file separately. But maybe this 
is in the noise in any case).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83508



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


[PATCH] D84012: [clangd] Exclude preprocessed-to-nothing tokens from selection

2020-07-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!




Comment at: clang-tools-extra/clangd/Selection.cpp:228
+ Buf.expansionsAffecting(Sel)) {
+  if (X.Expanded.empty()) {
+for (const syntax::Token &Tok : X.Spelled) {

nit: reduce nesting via

```
if(!X.Expanded.empty())
  continue
```



Comment at: clang-tools-extra/clangd/unittests/SelectionTests.cpp:554
+TEST(SelectionTest, DisabledPreprocessor) {
+  const char *Case = R"cpp(
+namespace ns {

this case isn't disabled PP, moreover seems to be already tested in  
CommonAncestor, see:

```
  {
  R"cpp(
void foo();
#define CALL_FUNCTION(X) X^()^
void bar() { CALL_FUNCTION(foo); }
  )cpp",
  nullptr,
  },
```

maybe also put a couple of tests for the macroname and the directive itself? 
(or just extend the test above to whole directive line?)



Comment at: clang-tools-extra/clangd/unittests/SelectionTests.cpp:568
+#if 0
+void fu^nc();
+#endif

nit: i am not sure if this is worth it's own test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84012



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


[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added inline comments.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:252
 return {};
-  assert(Spelled.front().location().isFileID());
-
-  auto FID = sourceManager().getFileID(Spelled.front().location());
-  auto It = Files.find(FID);
-  assert(It != Files.end());
-
-  const MarkedFile &File = It->second;
+  const MarkedFile &File = fileForSpelled(Spelled);
   // `Spelled` must be a subrange of `File.SpelledTokens`.

Could we use `const auto &` here as in lines 419, 434 for consistency?



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:431
+std::vector
+TokenBuffer::expansionsAffecting(llvm::ArrayRef Spelled) const {
+  if (Spelled.empty())

Will it be useful to have similar API with FileID/MarkedFile parameter?
For example, we already have FileID in `SelectionTester::SelectionTester`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009



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


[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:431
+std::vector
+TokenBuffer::expansionsAffecting(llvm::ArrayRef Spelled) const {
+  if (Spelled.empty())

ArcsinX wrote:
> Will it be useful to have similar API with FileID/MarkedFile parameter?
> For example, we already have FileID in `SelectionTester::SelectionTester`.
FileID is a bit awkward: then you have to have some way to specify which 
expansions you're interested in (or get those for the whole file and filter 
them yourself).

We could add an overload for this, but I think 
Buf.expansionsAffecting(Buf.spelledTokens(FID)) is pretty acceptable for this 
case.

(MarkedFile can't be used in an API because it's private)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009



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


[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 278716.
sammccall marked 2 inline comments as done.
sammccall added a comment.

auto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009

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

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -53,6 +53,7 @@
 using namespace clang::syntax;
 
 using llvm::ValueIs;
+using ::testing::_;
 using ::testing::AllOf;
 using ::testing::Contains;
 using ::testing::ElementsAre;
@@ -755,7 +756,7 @@
   EXPECT_THAT(Buffer.expandedTokens(SourceRange()), testing::IsEmpty());
 }
 
-TEST_F(TokenBufferTest, ExpansionStartingAt) {
+TEST_F(TokenBufferTest, ExpansionsOverlapping) {
   // Object-like macro expansions.
   recordTokens(R"cpp(
 #define FOO 3+4
@@ -763,17 +764,25 @@
 int b = FOO 2;
   )cpp");
 
-  llvm::ArrayRef Foo1 = findSpelled("FOO 1").drop_back();
+  llvm::ArrayRef Foo1 = findSpelled("FOO 1");
   EXPECT_THAT(
   Buffer.expansionStartingAt(Foo1.data()),
-  ValueIs(IsExpansion(SameRange(Foo1),
+  ValueIs(IsExpansion(SameRange(Foo1.drop_back()),
   SameRange(findExpanded("3 + 4 1").drop_back();
+  EXPECT_THAT(
+  Buffer.expansionsAffecting(Foo1),
+  ElementsAre(IsExpansion(SameRange(Foo1.drop_back()),
+  SameRange(findExpanded("3 + 4 1").drop_back();
 
-  llvm::ArrayRef Foo2 = findSpelled("FOO 2").drop_back();
+  llvm::ArrayRef Foo2 = findSpelled("FOO 2");
   EXPECT_THAT(
   Buffer.expansionStartingAt(Foo2.data()),
-  ValueIs(IsExpansion(SameRange(Foo2),
+  ValueIs(IsExpansion(SameRange(Foo2.drop_back()),
   SameRange(findExpanded("3 + 4 2").drop_back();
+  EXPECT_THAT(
+  Buffer.expansionsAffecting(llvm::makeArrayRef(Foo1.begin(), Foo2.end())),
+  ElementsAre(IsExpansion(SameRange(Foo1.drop_back()), _),
+  IsExpansion(SameRange(Foo2.drop_back()), _)));
 
   // Function-like macro expansions.
   recordTokens(R"cpp(
@@ -798,6 +807,11 @@
   for (const auto &T : ID2.drop_front())
 EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
 
+  EXPECT_THAT(Buffer.expansionsAffecting(llvm::makeArrayRef(
+  findSpelled("1 + 2").data(), findSpelled("4").data())),
+  ElementsAre(IsExpansion(SameRange(ID1), _),
+  IsExpansion(SameRange(ID2), _)));
+
   // PP directives.
   recordTokens(R"cpp(
 #define FOO 1
@@ -823,6 +837,11 @@
   // Only the first spelled token should be found.
   for (const auto &T : PragmaOnce.drop_front())
 EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
+
+  EXPECT_THAT(
+  Buffer.expansionsAffecting(findSpelled("FOO ; # pragma")),
+  ElementsAre(IsExpansion(SameRange(findSpelled("FOO ;").drop_back()), _),
+  IsExpansion(SameRange(PragmaOnce), _)));
 }
 
 TEST_F(TokenBufferTest, TokensToFileRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -249,13 +249,7 @@
 TokenBuffer::expandedForSpelled(llvm::ArrayRef Spelled) const {
   if (Spelled.empty())
 return {};
-  assert(Spelled.front().location().isFileID());
-
-  auto FID = sourceManager().getFileID(Spelled.front().location());
-  auto It = Files.find(FID);
-  assert(It != Files.end());
-
-  const MarkedFile &File = It->second;
+  const auto &File = fileForSpelled(Spelled);
   // `Spelled` must be a subrange of `File.SpelledTokens`.
   assert(File.SpelledTokens.data() <= Spelled.data());
   assert(&Spelled.back() <=
@@ -395,16 +389,34 @@
   : LastSpelled + 1);
 }
 
+TokenBuffer::Expansion TokenBuffer::makeExpansion(const MarkedFile &F,
+  const Mapping &M) const {
+  Expansion E;
+  E.Spelled = llvm::makeArrayRef(F.SpelledTokens.data() + M.BeginSpelled,
+ F.SpelledTokens.data() + M.EndSpelled);
+  E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M.BeginExpanded,
+  ExpandedTokens.data() + M.EndExpanded);
+  return E;
+}
+
+const TokenBuffer::MarkedFile &
+TokenBuffer::fileForSpelled(llvm::ArrayRef Spelled) const {
+  assert(!Spelled.empty());
+  assert(Spelled.front().location().isFileID() && "not a spelled token");
+  auto FileIt = Files.find(SourceMgr->getFileID(Spelled.front().location()));
+  assert(FileIt != Files.end() && "file not tracked by token buffer");
+  const auto &File = FileIt->second;
+  assert(File.SpelledTokens.data() <= Spelled.data() &&
+ Spelled.end() <=
+ (File.Spe

[PATCH] D84012: [clangd] Exclude preprocessed-to-nothing tokens from selection

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 278717.
sammccall marked 3 inline comments as done.
sammccall edited the summary of this revision.
sammccall added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84012

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -177,11 +177,29 @@
   {
   R"cpp(
 void foo();
-#define CALL_FUNCTION(X) X^()^
+#^define CALL_FUNCTION(X) X(^)
 void bar() { CALL_FUNCTION(foo); }
   )cpp",
   nullptr,
   },
+  {
+  R"cpp(
+void foo();
+#define CALL_FUNCTION(X) X()
+void bar() { CALL_FUNCTION(foo^)^; }
+  )cpp",
+  nullptr,
+  },
+  {
+  R"cpp(
+namespace ns {
+#if 0
+void fo^o() {}
+#endif
+}
+  )cpp",
+  nullptr,
+  },
   {
   R"cpp(
 struct S { S(const char*); };
@@ -388,7 +406,8 @@
 void test(S2 s2) {
   s2[[-^>]]f();
 }
-  )cpp", "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
+  )cpp",
+   "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
   };
   for (const Case &C : Cases) {
 trace::TestTracer Tracer;
@@ -538,7 +557,7 @@
   auto AST = TU.build();
   auto T = makeSelectionTree(Case, AST);
 
-  EXPECT_EQ("WhileStmt", T.commonAncestor()->kind());
+  EXPECT_EQ(nullptr, T.commonAncestor());
 }
 
 TEST(SelectionTest, MacroArgExpansion) {
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -220,14 +220,26 @@
 SelFirst, AllSpelledTokens.end(), [&](const syntax::Token &Tok) {
   return SM.getFileOffset(Tok.location()) < SelEnd;
 });
+auto Sel = llvm::makeArrayRef(SelFirst, SelLimit);
+// Find which of these are preprocessed to nothing and should be ignored.
+std::vector PPIgnored(Sel.size(), false);
+for (const syntax::TokenBuffer::Expansion &X :
+ Buf.expansionsAffecting(Sel)) {
+  if (X.Expanded.empty()) {
+for (const syntax::Token &Tok : X.Spelled) {
+  if (&Tok >= SelFirst && &Tok < SelLimit)
+PPIgnored[&Tok - SelFirst] = true;
+}
+  }
+}
 // Precompute selectedness and offset for selected spelled tokens.
-for (const syntax::Token *T = SelFirst; T < SelLimit; ++T) {
-  if (shouldIgnore(*T))
+for (unsigned I = 0; I < Sel.size(); ++I) {
+  if (shouldIgnore(Sel[I]) || PPIgnored[I])
 continue;
   SpelledTokens.emplace_back();
   Tok &S = SpelledTokens.back();
-  S.Offset = SM.getFileOffset(T->location());
-  if (S.Offset >= SelBegin && S.Offset + T->length() <= SelEnd)
+  S.Offset = SM.getFileOffset(Sel[I].location());
+  if (S.Offset >= SelBegin && S.Offset + Sel[I].length() <= SelEnd)
 S.Selected = SelectionTree::Complete;
   else
 S.Selected = SelectionTree::Partial;


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -177,11 +177,29 @@
   {
   R"cpp(
 void foo();
-#define CALL_FUNCTION(X) X^()^
+#^define CALL_FUNCTION(X) X(^)
 void bar() { CALL_FUNCTION(foo); }
   )cpp",
   nullptr,
   },
+  {
+  R"cpp(
+void foo();
+#define CALL_FUNCTION(X) X()
+void bar() { CALL_FUNCTION(foo^)^; }
+  )cpp",
+  nullptr,
+  },
+  {
+  R"cpp(
+namespace ns {
+#if 0
+void fo^o() {}
+#endif
+}
+  )cpp",
+  nullptr,
+  },
   {
   R"cpp(
 struct S { S(const char*); };
@@ -388,7 +406,8 @@
 void test(S2 s2) {
   s2[[-^>]]f();
 }
-  )cpp", "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
+  )cpp",
+   "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
   };
   for (const Case &C : Cases) {
 trace::TestTracer Tracer;
@@ -538,7 +557,7 @@
   auto AST = TU.build();
   auto T = makeSelectionTree(Case, AST);
 
-  EXPECT_EQ("WhileStmt", T.commonAncestor()->kind());
+  EXPECT_EQ(nullptr, T.commonAncestor());
 }
 
 TEST(SelectionTest, MacroArgExpansion) {
Index: clang

[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added a comment.

Thanks. This LGTM, but I think I don't have enough experience to accept 
revisions and could miss something important. So, may be @kadircet could accept 
it if its OK for him.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009



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


[PATCH] D83508: [clangd][Hover] Don't use Decl if it is not related with tokens under cursor.

2020-07-17 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added a comment.

In D83508#2157859 , @sammccall wrote:

> Tried this out in D84012 /D84009 
> . Works pretty well, and I think the API is 
> a useful and natural addition to TokenBuffer.


For my test cases it works well, so I think this problem is fixed.
Should I abandon this revision?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83508



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


[PATCH] D83501: [clangd][ObjC] Improve xrefs for protocols and classes

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D83501#2154300 , @dgoldman wrote:

> In D83501#2153605 , @sammccall wrote:
>
> > In D83501#2148671 , @dgoldman 
> > wrote:
> >
> > > I implemented goto-definition from Foo() --> Foo impl in Xrefs, on the 
> > > symbolcollector side I don't think there's anything to do?
> >
> >
> > This can't be done purely in xrefs as the AST may not be available.
> >
> > A.m: `@class Foo; ^Foo x;` <-- go-to-definition at ^
> >  B.m: `@interface Foo...@end @implementation Foo...@end`
> >
> > The index needs to know that for the USR associated with the @class (found 
> > by targetDecl), the canonical decl is the @interface in B and the 
> > definition is the @implementation in B.
> >  So SymbolCollector needs to see it as a definition. **The tests seem to 
> > show it does already**, but it's not obvious why from the code. Do you 
> > know? Maybe it's the fact that they share a USR and thus a symbol ID. This 
> > is worth making explicit somewhere.
>
>
> Think we're talking about different things. See `ObjCClassExtensions` in 
> SymbolCollectorTests which I added, the idea is that the `Cat ()` can link to 
> the implementation like I added to XRefs, but I'm not sure how this should be 
> represented. As for @class -> @interface/@implementation those should have 
> the same USR, yes.


Oh, sorry I indeed missed the parens.
Yes, this is a go-to-def special case, SymbolCollector shouldn't need anything. 
(I'm assuming that a reference to the class is reported already - could add a 
test that the ref exists if you like).




Comment at: clang-tools-extra/clangd/XRefs.cpp:276
getDeclAtPosition(AST, CurLoc, Relations, NodeKind)) {
 // Special case: void foo() ^override: jump to the overridden method.
 if (const auto *CMD = llvm::dyn_cast(D)) {

dgoldman wrote:
> sammccall wrote:
> > dgoldman wrote:
> > > sammccall wrote:
> > > > dgoldman wrote:
> > > > > sammccall wrote:
> > > > > > dgoldman wrote:
> > > > > > > sammccall wrote:
> > > > > > > > dgoldman wrote:
> > > > > > > > > Think it would make sense to special case ObjCInterfaceDecl 
> > > > > > > > > here to get at both the interface definition + implementation 
> > > > > > > > > if available?
> > > > > > > > Rather than returning both results, I think it's more 
> > > > > > > > consistent to return them as a declaration/definition pair.
> > > > > > > > 
> > > > > > > > (This means special-casing ObjCImplDecl in namedDecl or at 
> > > > > > > > least getDeclAsPosition, so you always end up with the 
> > > > > > > > ObjCInterfaceDecl instead)
> > > > > > > Whoops, meant to comment here but it was lost. I'm not sure what 
> > > > > > > you meant here. Should this be done here inside the for loop or 
> > > > > > > in getDeclAtPosition?
> > > > > > > 
> > > > > > > Are you saying that given:
> > > > > > > 
> > > > > > > ```
> > > > > > > @interface Foo // A
> > > > > > > @end
> > > > > > > @implementation Foo // B
> > > > > > > @end
> > > > > > > ```
> > > > > > > B --> A here
> > > > > > > 
> > > > > > > and similarly
> > > > > > > 
> > > > > > > ```
> > > > > > > @interface Foo // A
> > > > > > > @end
> > > > > > > @interface Foo (Ext) // B
> > > > > > > @end
> > > > > > > @implementation Foo (Ext) // C
> > > > > > > @end
> > > > > > > ```
> > > > > > > B --> A
> > > > > > > C --> B (and A? it's unclear how this should map over, e.g. maybe 
> > > > > > > Foo loc --> A, Ext --> B)
> > > > > > In the first example, selecting either A or B should yield one 
> > > > > > LocatedSymbol with {Decl=A, Def=B}. This shouldn't require any 
> > > > > > special-casing.
> > > > > > 
> > > > > > The second example is very similar to template specialization, with 
> > > > > > exceptions:
> > > > > >  - there's always a Decl/Def pair you may want to navigate between, 
> > > > > > whereas in templates there rarely is, so we have ambiguity
> > > > > >  - there's no AST like there is for template names and args, just a 
> > > > > > bag of tokens
> > > > > > 
> > > > > > I'd suggest, given `@interface Foo (Ext)`:
> > > > > >  - we produce a LocatedSymbol with {Decl=@interface Foo(Ext), 
> > > > > > Def=@implementation  Foo(Ext)} - this is the default behavior
> > > > > >  - if the cursor is exactly on the token `Foo`, we also produce a 
> > > > > > LocatedSymbol with {Decl=@interface Foo, Def=@implementation Foo} - 
> > > > > > this is similar to the template special case
> > > > > >  - if the cursor is exactly on the token Ext... are categories 
> > > > > > explicitly/separately declared anywhere? I guess not. If they are, 
> > > > > > we could special case this too.
> > > > > > And `@implementation Foo(Ext)` should behave in exactly the same 
> > > > > > way.
> > > > > Trying this out now, two problems:
> > > > > 
> > > > > - getDeclAtPosition will call findTarget. Due to the changes above we 
> >

[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

thanks, mostly LG with a comment about some edge case. just wanna know what you 
think.




Comment at: clang/include/clang/Tooling/Syntax/Tokens.h:281
+  std::vector
+  expansionsAffecting(llvm::ArrayRef Spelled) const;
 

this sounds more like `expansionsAffected` rather than affecting ? maybe my 
mental model requires correction, but it feels like spelled tokens are not 
affected by expansions, it is the other way around.

maybe even `expansionsSpawned` or `triggered`?

this is definitely non-blocking though, i am just bikesheding, comment is 
explanatory enough in any case.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:431
+std::vector
+TokenBuffer::expansionsAffecting(llvm::ArrayRef Spelled) const {
+  if (Spelled.empty())

this might be inconistent with spelledForExpanded from time to time, e.g:

```
#define FOO(X) 123
#define BAR

void foo() {
  FOO(BA^R);
}
```

normally BAR has no expansions, but I think it will get merged into outer macro 
expansion e.g. `123` coming from `FOO(BAR)`. (whereas spelledForExpanded will 
treat `BAR` in isolation)

not sure an important limitation but something to keep in mind.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:254
   // `Spelled` must be a subrange of `File.SpelledTokens`.
   assert(File.SpelledTokens.data() <= Spelled.data());
   assert(&Spelled.back() <=

these two are also asserted in `fileForSpelled`



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:257
  File.SpelledTokens.data() + File.SpelledTokens.size());
 #ifndef NDEBUG
   auto T1 = Spelled.back().location();

maybe move that into fileForSpelled too ? (to ensure `Spelled` is contained 
within the returned file)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009



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


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Michael Forster via Phabricator via cfe-commits
MForster updated this revision to Diff 278724.
MForster marked 4 inline comments as done.
MForster added a comment.

- Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005

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


Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -5327,9 +5327,9 @@
   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
 }
 
-static void handleNSErrorDomain(Sema &S, Decl *D, const AttributeList &Attr) {
+static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
   if (!isa(D)) {
-S.Diag(D->getLocStart(), diag::err_nserrordomain_not_tagdecl)
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)
 << S.getLangOpts().CPlusPlus;
 return;
   }
@@ -5339,7 +5339,7 @@
 // Try to locate the argument directly
 SourceLocation loc = Attr.getLoc();
 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
-  loc = Attr.getArgAsExpr(0)->getLocStart();
+  loc = Attr.getArgAsExpr(0)->getBeginLoc();
 
 S.Diag(loc, diag::err_nserrordomain_requires_identifier);
 return;
@@ -5357,8 +5357,7 @@
   }
 
   D->addAttr(::new (S.Context)
- NSErrorDomainAttr(Attr.getRange(), S.Context, identLoc->Ident,
-   Attr.getAttributeSpellingListIndex()));
+ NSErrorDomainAttr(S.Context, Attr, identLoc->Ident));
 }
 
 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
@@ -7132,8 +7131,8 @@
   case ParsedAttr::AT_ObjCBoxable:
 handleObjCBoxable(S, D, AL);
 break;
-  case AttributeList::AT_NSErrorDomain:
-handleNSErrorDomain(S, D, Attr);
+  case ParsedAttr::AT_NSErrorDomain:
+handleNSErrorDomain(S, D, AL);
 break;
   case ParsedAttr::AT_CFAuditedTransfer:
 handleSimpleAttributeWithExclusions];
+  let Subjects = SubjectList<[Enum]>;
   let Args = [IdentifierArgument<"ErrorDomain">];
   let Documentation = [NSErrorDomainDocs];
 }


Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -5327,9 +5327,9 @@
   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
 }
 
-static void handleNSErrorDomain(Sema &S, Decl *D, const AttributeList &Attr) {
+static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
   if (!isa(D)) {
-S.Diag(D->getLocStart(), diag::err_nserrordomain_not_tagdecl)
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)
 << S.getLangOpts().CPlusPlus;
 return;
   }
@@ -5339,7 +5339,7 @@
 // Try to locate the argument directly
 SourceLocation loc = Attr.getLoc();
 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
-  loc = Attr.getArgAsExpr(0)->getLocStart();
+  loc = Attr.getArgAsExpr(0)->getBeginLoc();
 
 S.Diag(loc, diag::err_nserrordomain_requires_identifier);
 return;
@@ -5357,8 +5357,7 @@
   }
 
   D->addAttr(::new (S.Context)
- NSErrorDomainAttr(Attr.getRange(), S.Context, identLoc->Ident,
-   Attr.getAttributeSpellingListIndex()));
+ NSErrorDomainAttr(S.Context, Attr, identLoc->Ident));
 }
 
 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
@@ -7132,8 +7131,8 @@
   case ParsedAttr::AT_ObjCBoxable:
 handleObjCBoxable(S, D, AL);
 break;
-  case AttributeList::AT_NSErrorDomain:
-handleNSErrorDomain(S, D, Attr);
+  case ParsedAttr::AT_NSErrorDomain:
+handleNSErrorDomain(S, D, AL);
 break;
   case ParsedAttr::AT_CFAuditedTransfer:
 handleSimpleAttributeWithExclusions];
+  let Subjects = SubjectList<[Enum]>;
   let Args = [IdentifierArgument<"ErrorDomain">];
   let Documentation = [NSErrorDomainDocs];
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Michael Forster via Phabricator via cfe-commits
MForster marked an inline comment as done and an inline comment as not done.
MForster added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1860
+def NSErrorDomain : Attr {
+  let Spellings = [GNU<"ns_error_domain">];
+  let Args = [IdentifierArgument<"ErrorDomain">];

gribozavr2 wrote:
> Could we try to add a list of subjects here? It seems like it is a type-only 
> attribute, and most likely enum-only.
> 
> let Subjects = SubjectList<[Enum]>;
@milseman, could you comment on this? 

In the meantime I've added the restriction. Obviously this makes the tests 
fail. I will also test this change against the Swift unit tests.



Comment at: clang/test/Analysis/ns_error_enum.m:1
+// RUN: %clang_cc1 -verify %s
+

gribozavr2 wrote:
> This file is a `.m` -- any specific reason? I'd call it `.c` and run the test 
> in C, Objective-C, and C++ modes (enums might work slightly differently, the 
> name lookup functionality might work differently).
The test doesn't compile in C or C++ (`non-defining declaration of enumeration 
with a fixed underlying type is only permitted as a standalone declaration; 
missing list of enumerators?`). Not sure if it's worth adapting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D81728: [InstCombine] Add target-specific inst combining

2020-07-17 Thread Jay Foad via Phabricator via cfe-commits
foad added inline comments.



Comment at: llvm/include/llvm/Analysis/TargetTransformInfo.h:552-555
+  /// \returns false to not do anything target specific or true to return the
+  /// value in \p ResultI from the InstCombiner. It is possible to return null
+  /// and stop further processing of the intrinsic by writing nullptr into
+  /// \p ResultI and returning true.

Did you consider returning `std::pair`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81728



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


[clang] 4fc752b - [CUDA][HIP] Always defer diagnostics for wrong-sided reference

2020-07-17 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2020-07-17T07:51:55-04:00
New Revision: 4fc752b30b9acac73a282cb844a6240e6cb70cca

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

LOG: [CUDA][HIP] Always defer diagnostics for wrong-sided reference

When a device function calls a host function or vice versa, this is wrong-sided
reference. Currently clang immediately diagnose it. This is different from nvcc
behavior, where it is diagnosed only if the function is really emitted.

Current clang behavior causes false alarms for valid use cases.

This patch let clang always defer diagnostics for wrong-sided
reference.

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

Added: 


Modified: 
clang/lib/Sema/SemaCUDA.cpp
clang/test/SemaCUDA/builtins.cu
clang/test/SemaCUDA/call-kernel-from-kernel.cu
clang/test/SemaCUDA/function-overload.cu
clang/test/SemaCUDA/function-target.cu
clang/test/SemaCUDA/implicit-device-lambda.cu
clang/test/SemaCUDA/method-target.cu
clang/test/SemaCUDA/reference-to-kernel-fn.cu

Removed: 




diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index 283a04683a32..e2190fc42de4 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -715,9 +715,8 @@ bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl 
*Callee) {
   CallerKnownEmitted] {
 switch (IdentifyCUDAPreference(Caller, Callee)) {
 case CFP_Never:
-  return DeviceDiagBuilder::K_Immediate;
 case CFP_WrongSide:
-  assert(Caller && "WrongSide calls require a non-null caller");
+  assert(Caller && "Never/wrongSide calls require a non-null caller");
   // If we know the caller will be emitted, we know this wrong-side call
   // will be emitted, so it's an immediate error.  Otherwise, defer the
   // error until we know the caller is emitted.

diff  --git a/clang/test/SemaCUDA/builtins.cu b/clang/test/SemaCUDA/builtins.cu
index 814fda2ac7d3..c01a687e12c0 100644
--- a/clang/test/SemaCUDA/builtins.cu
+++ b/clang/test/SemaCUDA/builtins.cu
@@ -7,10 +7,10 @@
 // REQUIRES: nvptx-registered-target
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown \
 // RUN: -aux-triple nvptx64-unknown-cuda \
-// RUN: -fsyntax-only -verify %s
+// RUN: -fsyntax-only -verify=host %s
 // RUN: %clang_cc1 -triple nvptx64-unknown-cuda -fcuda-is-device \
 // RUN: -aux-triple x86_64-unknown-unknown \
-// RUN: -fsyntax-only -verify %s
+// RUN: -fsyntax-only -verify=dev %s
 
 #if !(defined(__amd64__) && defined(__PTX__))
 #error "Expected to see preprocessor macros from both sides of compilation."
@@ -18,14 +18,14 @@
 
 void hf() {
   int x = __builtin_ia32_rdtsc();
-  int y = __nvvm_read_ptx_sreg_tid_x(); // expected-note  
{{'__nvvm_read_ptx_sreg_tid_x' declared here}}
-  // expected-error@-1 {{reference to __device__ function 
'__nvvm_read_ptx_sreg_tid_x' in __host__ function}}
+  int y = __nvvm_read_ptx_sreg_tid_x(); // host-note  
{{'__nvvm_read_ptx_sreg_tid_x' declared here}}
+  // host-error@-1 {{reference to __device__ function 
'__nvvm_read_ptx_sreg_tid_x' in __host__ function}}
   x = __builtin_abs(1);
 }
 
 __attribute__((device)) void df() {
   int x = __nvvm_read_ptx_sreg_tid_x();
-  int y = __builtin_ia32_rdtsc(); // expected-error {{reference to __host__ 
function '__builtin_ia32_rdtsc' in __device__ function}}
-  // expected-note@20 {{'__builtin_ia32_rdtsc' 
declared here}}
+  int y = __builtin_ia32_rdtsc(); // dev-error {{reference to __host__ 
function '__builtin_ia32_rdtsc' in __device__ function}}
+  // dev-note@20 {{'__builtin_ia32_rdtsc' 
declared here}}
   x = __builtin_abs(1);
 }

diff  --git a/clang/test/SemaCUDA/call-kernel-from-kernel.cu 
b/clang/test/SemaCUDA/call-kernel-from-kernel.cu
index c89037c52bff..900efcef43b8 100644
--- a/clang/test/SemaCUDA/call-kernel-from-kernel.cu
+++ b/clang/test/SemaCUDA/call-kernel-from-kernel.cu
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 %s --std=c++11 -triple x86_64-unknown-linux -emit-llvm -o - 
\
-// RUN:   -verify -fsyntax-only -verify-ignore-unexpected=note
+// RUN: %clang_cc1 %s --std=c++11 -triple nvptx -emit-llvm -o - \
+// RUN:   -verify -fcuda-is-device -fsyntax-only -verify-ignore-unexpected=note
 
 #include "Inputs/cuda.h"
 

diff  --git a/clang/test/SemaCUDA/function-overload.cu 
b/clang/test/SemaCUDA/function-overload.cu
index b9efd1c09e69..191268c9a5f1 100644
--- a/clang/test/SemaCUDA/function-overload.cu
+++ b/clang/test/SemaCUDA/function-overload.cu
@@ -1,8 +1,8 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: nvptx-registered-target
 
-// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple nvptx64-nvidia-

[PATCH] D83893: [CUDA][HIP] Always defer diagnostics for wrong-sided reference

2020-07-17 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4fc752b30b9a: [CUDA][HIP] Always defer diagnostics for 
wrong-sided reference (authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83893

Files:
  clang/lib/Sema/SemaCUDA.cpp
  clang/test/SemaCUDA/builtins.cu
  clang/test/SemaCUDA/call-kernel-from-kernel.cu
  clang/test/SemaCUDA/function-overload.cu
  clang/test/SemaCUDA/function-target.cu
  clang/test/SemaCUDA/implicit-device-lambda.cu
  clang/test/SemaCUDA/method-target.cu
  clang/test/SemaCUDA/reference-to-kernel-fn.cu

Index: clang/test/SemaCUDA/reference-to-kernel-fn.cu
===
--- clang/test/SemaCUDA/reference-to-kernel-fn.cu
+++ clang/test/SemaCUDA/reference-to-kernel-fn.cu
@@ -1,12 +1,14 @@
-// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify \
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify=host \
+// RUN:   -verify-ignore-unexpected=note %s
+// RUN: %clang_cc1 -std=c++11 -fcuda-is-device -fsyntax-only -verify=dev \
 // RUN:   -verify-ignore-unexpected=note %s
-// RUN: %clang_cc1 -std=c++11 -fcuda-is-device -fsyntax-only -verify \
-// RUN:   -verify-ignore-unexpected=note -DDEVICE %s
 
 // Check that we can reference (get a function pointer to) a __global__
 // function from the host side, but not the device side.  (We don't yet support
 // device-side kernel launches.)
 
+// host-no-diagnostics
+
 #include "Inputs/cuda.h"
 
 struct Dummy {};
@@ -17,13 +19,11 @@
 
 __host__ __device__ fn_ptr_t get_ptr_hd() {
   return kernel;
-#ifdef DEVICE
-  // expected-error@-2 {{reference to __global__ function}}
-#endif
+  // dev-error@-1 {{reference to __global__ function}}
 }
 __host__ fn_ptr_t get_ptr_h() {
   return kernel;
 }
 __device__ fn_ptr_t get_ptr_d() {
-  return kernel;  // expected-error {{reference to __global__ function}}
+  return kernel;  // dev-error {{reference to __global__ function}}
 }
Index: clang/test/SemaCUDA/method-target.cu
===
--- clang/test/SemaCUDA/method-target.cu
+++ clang/test/SemaCUDA/method-target.cu
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify=host,expected %s
+// RUN: %clang_cc1 -fcuda-is-device -fsyntax-only -verify=dev,expected %s
 
 #include "Inputs/cuda.h"
 
@@ -6,11 +7,11 @@
 // Test 1: host method called from device function
 
 struct S1 {
-  void method() {} // expected-note {{'method' declared here}}
+  void method() {} // dev-note {{'method' declared here}}
 };
 
 __device__ void foo1(S1& s) {
-  s.method(); // expected-error {{reference to __host__ function 'method' in __device__ function}}
+  s.method(); // dev-error {{reference to __host__ function 'method' in __device__ function}}
 }
 
 //--
@@ -29,22 +30,22 @@
 // Test 3: device method called from host function
 
 struct S3 {
-  __device__ void method() {} // expected-note {{'method' declared here}}
+  __device__ void method() {} // host-note {{'method' declared here}}
 };
 
 void foo3(S3& s) {
-  s.method(); // expected-error {{reference to __device__ function 'method' in __host__ function}}
+  s.method(); // host-error {{reference to __device__ function 'method' in __host__ function}}
 }
 
 //--
 // Test 4: device method called from host&device function
 
 struct S4 {
-  __device__ void method() {}  // expected-note {{'method' declared here}}
+  __device__ void method() {}  // host-note {{'method' declared here}}
 };
 
 __host__ __device__ void foo4(S4& s) {
-  s.method(); // expected-error {{reference to __device__ function 'method' in __host__ __device__ function}}
+  s.method(); // host-error {{reference to __device__ function 'method' in __host__ __device__ function}}
 }
 
 //--
@@ -63,9 +64,9 @@
 // Test 6: call method through pointer
 
 struct S6 {
-  void method() {} // expected-note {{'method' declared here}};
+  void method() {} // dev-note {{'method' declared here}};
 };
 
 __device__ void foo6(S6* s) {
-  s->method(); // expected-error {{reference to __host__ function 'method' in __device__ function}}
+  s->method(); // dev-error {{reference to __host__ function 'method' in __device__ function}}
 }
Index: clang/test/SemaCUDA/implicit-device-lambda.cu
===
--- clang/test/SemaCUDA/implicit-device-lambda.cu
+++ clang/test/SemaCUDA/implicit-device-lambda.cu
@@ -1,5 +1,7 @@
-// RUN: %clang_cc1 -std=c++11 -fcuda-is-device -verify -fsyntax-only -verify-ignore-unexpected=warning -verify-ignore-unexpected=note %s
-// RUN: %clang_cc1 -std=c++11 -verify -fsyntax-only

[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added a comment.

Did your latest update unintentionally drop the test file 
`clang/test/Analysis/ns_error_enum.m`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D69318: [analyzer] Add SufficientSizeArrayIndexingChecker

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 278727.
gamesh411 marked 3 inline comments as done.
gamesh411 added a comment.

extend test cases
add comments to non-obvious cases


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69318

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/SufficientSizeArrayIndexingChecker.cpp
  clang/test/Analysis/sufficient-size-array-indexing.c

Index: clang/test/Analysis/sufficient-size-array-indexing.c
===
--- /dev/null
+++ clang/test/Analysis/sufficient-size-array-indexing.c
@@ -0,0 +1,198 @@
+// RUN: %clang_analyze_cc1 -triple i386 -analyzer-checker=core,alpha.core.SufficientSizeArrayIndexing %s -verify
+// RUN: %clang_analyze_cc1 -triple x86_64 -analyzer-checker=core,alpha.core.SufficientSizeArrayIndexing %s -verify
+
+#include "Inputs/system-header-simulator.h"
+
+const unsigned long long one_byte_signed_max = (1ULL << 7) - 1;
+const unsigned long long two_byte_signed_max = (1ULL << 15) - 1;
+const unsigned long long four_byte_signed_max = (1ULL << 31) - 1;
+
+const unsigned long long one_byte_unsigned_max = (1ULL << 8) - 1;
+const unsigned long long two_byte_unsigned_max = (1ULL << 16) - 1;
+const unsigned long long four_byte_unsigned_max = (1ULL << 32) - 1;
+
+char smaller_than_1byte_signed_range[one_byte_signed_max];
+char exactly_1byte_signed_range[one_byte_signed_max + 1];
+char greater_than_1byte_signed_range[one_byte_signed_max + 2];
+
+char smaller_than_2byte_signed_range[two_byte_signed_max];
+char exactly_2byte_signed_range[two_byte_signed_max + 1];
+char greater_than_2byte_signed_range[two_byte_signed_max + 2];
+
+char smaller_than_4byte_signed_range[four_byte_signed_max];
+char exactly_4byte_signed_range[four_byte_signed_max + 1];
+char greater_than_4byte_signed_range[four_byte_signed_max + 2];
+
+char smaller_than_1byte_unsigned_range[one_byte_unsigned_max];
+char exactly_1byte_unsigned_range[one_byte_unsigned_max + 1];
+char greater_than_1byte_unsigned_range[one_byte_unsigned_max + 2];
+
+char smaller_than_2byte_unsigned_range[two_byte_unsigned_max];
+char exactly_2byte_unsigned_range[two_byte_unsigned_max + 1];
+char greater_than_2byte_unsigned_range[two_byte_unsigned_max + 2];
+
+char smaller_than_4byte_unsigned_range[four_byte_unsigned_max];
+
+const char one_byte_signed_index = 1;  // sizeof(char) == 1
+const short two_byte_signed_index = 1; // sizeof(short) == 2
+const int four_byte_signed_index = 1;  // sizeof(int) == 4
+
+const unsigned char one_byte_unsigned_index = 1;
+const unsigned short two_byte_unsigned_index = 1;
+const unsigned int four_byte_unsigned_index = 1;
+
+void ignore_literal_indexing() {
+  char a;
+  a = smaller_than_1byte_signed_range[1]; // nowarning
+  a = exactly_1byte_signed_range[1];  // nowarning
+  a = greater_than_1byte_signed_range[1]; // nowarning
+  a = smaller_than_2byte_signed_range[1]; // nowarning
+  a = exactly_2byte_signed_range[1];  // nowarning
+  a = greater_than_2byte_signed_range[1]; // nowarning
+  a = smaller_than_4byte_signed_range[1]; // nowarning
+  a = exactly_4byte_signed_range[1];  // nowarning
+  a = greater_than_4byte_signed_range[1]; // nowarning
+
+  a = smaller_than_1byte_unsigned_range[1]; // nowarning
+  a = exactly_1byte_unsigned_range[1];  // nowarning
+  a = greater_than_1byte_unsigned_range[1]; // nowarning
+  a = smaller_than_2byte_unsigned_range[1]; // nowarning
+  a = exactly_2byte_unsigned_range[1];  // nowarning
+  a = greater_than_2byte_unsigned_range[1]; // nowarning
+  a = smaller_than_4byte_unsigned_range[1]; // nowarning
+}
+
+void ignore_literal_indexing_with_parens() {
+  char a;
+  a = smaller_than_1byte_signed_range[(1)]; // nowarning
+  a = exactly_1byte_signed_range[(1)];  // nowarning
+  a = greater_than_1byte_signed_range[(1)]; // nowarning
+  a = smaller_than_2byte_signed_range[(1)]; // nowarning
+  a = exactly_2byte_signed_range[(1)];  // nowarning
+  a = greater_than_2byte_signed_range[(1)]; // nowarning
+  a = smaller_than_4byte_signed_range[(1)]; // nowarning
+  a = exactly_4byte_signed_range[(1)];  // nowarning
+  a = greater_than_4byte_signed_range[(1)]; // nowarning
+
+  a = smaller_than_1byte_unsigned_range[(1)]; // nowarning
+  a = exactly_1byte_unsigned_range[(1)];  // nowarning
+  a = greater_than_1byte_unsigned_range[(1)]; // nowarning
+  a = smaller_than_2byte_unsigned_range[(1)]; // nowarning
+  a = exactly_2byte_unsigned_range[(1)];  // nowarning
+  a = greater_than_2byte_unsigned_range[(1)]; // nowarning
+  a = smaller_than_4byte_unsigned_range[(1)]; // nowarning
+}
+
+void non_literal_but_compile_time_const_indexing() {
+  char a;
+  a = smaller_than_1byte_signed_range[(unsigned char)(1 + 1)]; // nowarning
+  a = exactly_1byte_signed_range[(unsigned char)(1 + 1)];  // nowa

[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

FWIW, this is *really* hard to review because it's not a diff against the trunk 
and so it's not immediately clear what the actual changes are.

The change is missing all of its test coverage.




Comment at: clang/include/clang/Basic/Attr.td:1860
+def NSErrorDomain : Attr {
+  let Spellings = [GNU<"ns_error_domain">];
+  let Args = [IdentifierArgument<"ErrorDomain">];

MForster wrote:
> gribozavr2 wrote:
> > Could we try to add a list of subjects here? It seems like it is a 
> > type-only attribute, and most likely enum-only.
> > 
> > let Subjects = SubjectList<[Enum]>;
> @milseman, could you comment on this? 
> 
> In the meantime I've added the restriction. Obviously this makes the tests 
> fail. I will also test this change against the Swift unit tests.
FWIW, this is not a attribute; it's a declaration attribute.

Is there a reason it's not inheritable?

I assume it's not getting a Clang spelling because Objective-C isn't tracking 
C2x yet? (Though that spelling still seems useful to Objective-C++ users in 
general for these NS attributes.)



Comment at: clang/include/clang/Basic/AttrDocs.td:3317
+def NSErrorDomainDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{

gribozavr2 wrote:
> Shouldn't the category be DocCatType since it is a type attribute?
This is not a type attribute. It should be set to `DocCatDecl`.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5330
 
-static void handleNSErrorDomain(Sema &S, Decl *D, const AttributeList &Attr) {
+static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
   if (!isa(D)) {

Please do not name the parameter with the same name as a type.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5331
+static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
   if (!isa(D)) {
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)

This shouldn't be necessary as the common attribute handler checks subjects. 
Also, it's the wrong subject (this would allow things like putting the 
attribute onto a struct).



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5332
   if (!isa(D)) {
-S.Diag(D->getLocStart(), diag::err_nserrordomain_not_tagdecl)
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)
 << S.getLangOpts().CPlusPlus;

Where is this error defined?



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5336
   }
   IdentifierLoc *identLoc =
   Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;

Doesn't match the usual naming conventions. Same issue elsewhere in the patch.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5341
 SourceLocation loc = Attr.getLoc();
 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
+  loc = Attr.getArgAsExpr(0)->getBeginLoc();

```
if (const Expr *E = Attr.getArgAsExpr(0))
  loc = E->getBeginLoc();
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Michael Forster via Phabricator via cfe-commits
MForster updated this revision to Diff 278728.
MForster marked an inline comment as not done.
MForster added a comment.

Fix diff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005

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

Index: clang/test/Analysis/ns_error_enum.m
===
--- /dev/null
+++ clang/test/Analysis/ns_error_enum.m
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -verify %s
+
+#define CF_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
+#define NS_ENUM(_type, _name) CF_ENUM(_type, _name)
+
+#define NS_ERROR_ENUM(_type, _name, _domain)  \
+  enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
+
+typedef NS_ENUM(unsigned, MyEnum) {
+  MyFirst,
+  MySecond,
+};
+
+typedef NS_ENUM(invalidType, MyInvalidEnum) {
+// expected-error@-1{{unknown type name 'invalidType'}}
+// expected-error@-2{{unknown type name 'invalidType'}}
+  MyFirstInvalid,
+  MySecondInvalid,
+};
+
+const char *MyErrorDomain;
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
+	MyErrFirst,
+	MyErrSecond,
+};
+struct __attribute__((ns_error_domain(MyErrorDomain))) MyStructErrorDomain {};
+
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnumInvalid, InvalidDomain) {
+	// expected-error@-1{{domain argument 'InvalidDomain' does not refer to global constant}}
+	MyErrFirstInvalid,
+	MyErrSecondInvalid,
+};
+
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnumInvalid, "domain-string");
+  // expected-error@-1{{domain argument must be an identifier}}
+
+int __attribute__((ns_error_domain(MyErrorDomain))) NotTagDecl;
+  // expected-error@-1{{ns_error_domain attribute only valid on enums, structs, and unions}}
+
+void foo() {}
+typedef NS_ERROR_ENUM(unsigned char, MyErrorEnumInvalidFunction, foo);
+  // expected-error@-1{{domain argument 'foo' does not refer to global constant}}
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -5327,6 +5327,39 @@
   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
 }
 
+static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
+  if (!isa(D)) {
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)
+<< S.getLangOpts().CPlusPlus;
+return;
+  }
+  IdentifierLoc *identLoc =
+  Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
+  if (!identLoc || !identLoc->Ident) {
+// Try to locate the argument directly
+SourceLocation loc = Attr.getLoc();
+if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
+  loc = Attr.getArgAsExpr(0)->getBeginLoc();
+
+S.Diag(loc, diag::err_nserrordomain_requires_identifier);
+return;
+  }
+
+  // Verify that the identifier is a valid decl in the C decl namespace
+  LookupResult lookupResult(S, DeclarationName(identLoc->Ident),
+SourceLocation(),
+Sema::LookupNameKind::LookupOrdinaryName);
+  if (!S.LookupName(lookupResult, S.TUScope) ||
+  !lookupResult.getAsSingle()) {
+S.Diag(identLoc->Loc, diag::err_nserrordomain_invalid_decl)
+<< identLoc->Ident;
+return;
+  }
+
+  D->addAttr(::new (S.Context)
+ NSErrorDomainAttr(S.Context, Attr, identLoc->Ident));
+}
+
 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
 
@@ -7098,6 +7131,9 @@
   case ParsedAttr::AT_ObjCBoxable:
 handleObjCBoxable(S, D, AL);
 break;
+  case ParsedAttr::AT_NSErrorDomain:
+handleNSErrorDomain(S, D, AL);
+break;
   case ParsedAttr::AT_CFAuditedTransfer:
 handleSimpleAttributeWithExclusions(S, D, AL);
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9446,6 +9446,14 @@
 def err_nsreturns_retained_attribute_mismatch : Error<
   "overriding method has mismatched ns_returns_%select{not_retained|retained}0"
   " attributes">;
+def err_nserrordomain_not_tagdecl : Error<
+  "ns_error_domain attribute only valid on "
+  "%select{enums, structs, and unions|enums, structs, unions, and classes}0">;
+def err_nserrordomain_invalid_decl : Error<
+  "domain argument %0 does not refer to global constant">;
+def err_nserrordomain_requires_identifier : Error<
+  "domain argument must be an identifier">;
+
 def warn_nsconsumed_attribute_mismatch : Warning<
   err_nsconsumed_attribute_mismatch.Text>, InGroup;
 def warn_nsreturns_retained_attribute_mismatch : Warning<
Index: 

[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Michael Forster via Phabricator via cfe-commits
MForster added a comment.

In D84005#2158019 , @gribozavr2 wrote:

> Did your latest update unintentionally drop the test file 
> `clang/test/Analysis/ns_error_enum.m`?


I'm struggling with arcanist :-). Fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Michael Forster via Phabricator via cfe-commits
MForster added a comment.

In D84005#2158029 , @aaron.ballman 
wrote:

> FWIW, this is *really* hard to review because it's not a diff against the 
> trunk and so it's not immediately clear what the actual changes are.
>
> The change is missing all of its test coverage.


I'm sorry. This was me struggling with arcanist. It should be a diff against 
trunk now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D69318: [analyzer] Add SufficientSizeArrayIndexingChecker

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added inline comments.



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:120
+
+void test_symbolic_index_handling4(int choice) {
+  char c;

balazske wrote:
> Here "is a chance that indexing is correct". So no warning should occur?
I think as there is a  branch where it is provably wrong, this is correct. It 
is just not obvious from the diag message which branch is taken, and 
consequently which array is being indexed. I think there is no way to address 
this from inside the checker.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69318



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


[PATCH] D83979: Port LangOpts option flags to new option parsing system

2020-07-17 Thread Daniel Grumberg via Phabricator via cfe-commits
dang updated this revision to Diff 278729.
dang added a comment.

Fix formatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83979

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -269,7 +269,7 @@
 
 template 
 static T mergeForwardValue(T KeyPath, U Value) {
-  return Value;
+  return static_cast(Value);
 }
 
 template  static T mergeMaskValue(T KeyPath, U Value) {
@@ -285,7 +285,8 @@
   return KeyPath & Value;
 }
 
-static void FixupInvocation(CompilerInvocation &Invocation) {
+static void FixupInvocation(CompilerInvocation &Invocation,
+DiagnosticsEngine &Diags) {
   LangOptions &LangOpts = *Invocation.getLangOpts();
   DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
@@ -296,7 +297,15 @@
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
 
+  LangOpts.Optimize = CodeGenOpts.OptimizationLevel != 0;
+  LangOpts.OptimizeSize = CodeGenOpts.OptimizeSize != 0;
+  LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
+  LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
+
   llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes);
+
+  if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
+Diags.Report(diag::warn_c_kext);
 }
 
 //===--===//
@@ -2292,9 +2301,6 @@
 }
   }
 
-  if (Args.hasArg(OPT_fno_dllexport_inlines))
-Opts.DllExportInlines = false;
-
   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
 StringRef Name = A->getValue();
 if (Name == "full" || Name == "branch") {
@@ -2321,7 +2327,6 @@
   LangStd = OpenCLLangStd;
   }
 
-  Opts.SYCL = Args.hasArg(options::OPT_fsycl);
   Opts.SYCLIsDevice = Opts.SYCL && Args.hasArg(options::OPT_fsycl_is_device);
   if (Opts.SYCL) {
 // -sycl-std applies to any SYCL source, not only those containing kernels,
@@ -2339,9 +2344,6 @@
 }
   }
 
-  Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
-  Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
-
   llvm::Triple T(TargetOpts.Triple);
   CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
 
@@ -2367,20 +2369,9 @@
 
   if (Args.hasArg(OPT_fno_operator_names))
 Opts.CXXOperatorNames = 0;
-
-  if (Args.hasArg(OPT_fcuda_is_device))
-Opts.CUDAIsDevice = 1;
-
-  if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
-Opts.CUDAAllowVariadicFunctions = 1;
-
-  if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
-Opts.CUDAHostDeviceConstexpr = 0;
-
   if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
 Opts.CUDADeviceApproxTranscendentals = 1;
 
-  Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
   if (Args.hasArg(OPT_fgpu_allow_device_init)) {
 if (Opts.HIP)
   Opts.GPUAllowDeviceInit = 1;
@@ -2388,7 +2379,6 @@
   Diags.Report(diag::warn_ignored_hip_only_option)
   << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
   }
-  Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api);
   if (Opts.HIP)
 Opts.GPUMaxThreadsPerBlock = getLastArgIntValue(
 Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock);
@@ -2408,7 +2398,6 @@
 else if (Args.hasArg(OPT_fobjc_gc))
   Opts.setGC(LangOptions::HybridGC);
 else if (Args.hasArg(OPT_fobjc_arc)) {
-  Opts.ObjCAutoRefCount = 1;
   if (!Opts.ObjCRuntime.allowsARC())
 Diags.Report(diag::err_arc_unsupported_on_runtime);
 }
@@ -2438,9 +2427,6 @@
   Opts.ObjCWeak = Opts.ObjCWeakRuntime;
 }
 
-if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
-  Opts.ObjCInferRelatedResultType = 0;
-
 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
   Opts.ObjCSubscriptingLegacyRuntime =
 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
@@ -2469,18 +2455,6 @@
   Opts.GNUInline = 1;
   }
 
-  if (Args.hasArg(OPT_fapple_kext)) {
-if (!Opts.CPlusPlus)
-  Diags.Report(diag::warn_c_kext);
-else
-  Opts.AppleKext = 1;
-  }
-
-  if (Args.hasArg(OPT_print_ivar_layout))
-Opts.ObjCGCBitmapPrint = 1;
-
-  if (Args.hasArg(OPT_fno_constant_cfstrings))
-Opts.NoConstantCFStrings = 1;
   if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
 Opts.CFRuntime =
 llvm::StringSwitch(A->getValue())
@@ -2492,12 +2466,6 @@
 .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
 .Default(LangOpt

[clang] a46ef7d - Revert "[CUDA][HIP] Always defer diagnostics for wrong-sided reference"

2020-07-17 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2020-07-17T08:10:56-04:00
New Revision: a46ef7d42dc8aa5083319bef678262bddf299f82

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

LOG: Revert "[CUDA][HIP] Always defer diagnostics for wrong-sided reference"

This reverts commit 4fc752b30b9acac73a282cb844a6240e6cb70cca.

Added: 


Modified: 
clang/lib/Sema/SemaCUDA.cpp
clang/test/SemaCUDA/builtins.cu
clang/test/SemaCUDA/call-kernel-from-kernel.cu
clang/test/SemaCUDA/function-overload.cu
clang/test/SemaCUDA/function-target.cu
clang/test/SemaCUDA/implicit-device-lambda.cu
clang/test/SemaCUDA/method-target.cu
clang/test/SemaCUDA/reference-to-kernel-fn.cu

Removed: 




diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index e2190fc42de4..283a04683a32 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -715,8 +715,9 @@ bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl 
*Callee) {
   CallerKnownEmitted] {
 switch (IdentifyCUDAPreference(Caller, Callee)) {
 case CFP_Never:
+  return DeviceDiagBuilder::K_Immediate;
 case CFP_WrongSide:
-  assert(Caller && "Never/wrongSide calls require a non-null caller");
+  assert(Caller && "WrongSide calls require a non-null caller");
   // If we know the caller will be emitted, we know this wrong-side call
   // will be emitted, so it's an immediate error.  Otherwise, defer the
   // error until we know the caller is emitted.

diff  --git a/clang/test/SemaCUDA/builtins.cu b/clang/test/SemaCUDA/builtins.cu
index c01a687e12c0..814fda2ac7d3 100644
--- a/clang/test/SemaCUDA/builtins.cu
+++ b/clang/test/SemaCUDA/builtins.cu
@@ -7,10 +7,10 @@
 // REQUIRES: nvptx-registered-target
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown \
 // RUN: -aux-triple nvptx64-unknown-cuda \
-// RUN: -fsyntax-only -verify=host %s
+// RUN: -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple nvptx64-unknown-cuda -fcuda-is-device \
 // RUN: -aux-triple x86_64-unknown-unknown \
-// RUN: -fsyntax-only -verify=dev %s
+// RUN: -fsyntax-only -verify %s
 
 #if !(defined(__amd64__) && defined(__PTX__))
 #error "Expected to see preprocessor macros from both sides of compilation."
@@ -18,14 +18,14 @@
 
 void hf() {
   int x = __builtin_ia32_rdtsc();
-  int y = __nvvm_read_ptx_sreg_tid_x(); // host-note  
{{'__nvvm_read_ptx_sreg_tid_x' declared here}}
-  // host-error@-1 {{reference to __device__ function 
'__nvvm_read_ptx_sreg_tid_x' in __host__ function}}
+  int y = __nvvm_read_ptx_sreg_tid_x(); // expected-note  
{{'__nvvm_read_ptx_sreg_tid_x' declared here}}
+  // expected-error@-1 {{reference to __device__ function 
'__nvvm_read_ptx_sreg_tid_x' in __host__ function}}
   x = __builtin_abs(1);
 }
 
 __attribute__((device)) void df() {
   int x = __nvvm_read_ptx_sreg_tid_x();
-  int y = __builtin_ia32_rdtsc(); // dev-error {{reference to __host__ 
function '__builtin_ia32_rdtsc' in __device__ function}}
-  // dev-note@20 {{'__builtin_ia32_rdtsc' 
declared here}}
+  int y = __builtin_ia32_rdtsc(); // expected-error {{reference to __host__ 
function '__builtin_ia32_rdtsc' in __device__ function}}
+  // expected-note@20 {{'__builtin_ia32_rdtsc' 
declared here}}
   x = __builtin_abs(1);
 }

diff  --git a/clang/test/SemaCUDA/call-kernel-from-kernel.cu 
b/clang/test/SemaCUDA/call-kernel-from-kernel.cu
index 900efcef43b8..c89037c52bff 100644
--- a/clang/test/SemaCUDA/call-kernel-from-kernel.cu
+++ b/clang/test/SemaCUDA/call-kernel-from-kernel.cu
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 %s --std=c++11 -triple nvptx -emit-llvm -o - \
-// RUN:   -verify -fcuda-is-device -fsyntax-only -verify-ignore-unexpected=note
+// RUN: %clang_cc1 %s --std=c++11 -triple x86_64-unknown-linux -emit-llvm -o - 
\
+// RUN:   -verify -fsyntax-only -verify-ignore-unexpected=note
 
 #include "Inputs/cuda.h"
 

diff  --git a/clang/test/SemaCUDA/function-overload.cu 
b/clang/test/SemaCUDA/function-overload.cu
index 191268c9a5f1..b9efd1c09e69 100644
--- a/clang/test/SemaCUDA/function-overload.cu
+++ b/clang/test/SemaCUDA/function-overload.cu
@@ -1,8 +1,8 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: nvptx-registered-target
 
-// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsyntax-only 
-verify=host,expected %s
-// RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -fsyntax-only -fcuda-is-device 
-verify=dev,expected %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -fsyntax-only -fcuda-is-device 
-verify %s
 
 #include "Inputs/cuda.h"
 
@@ -75,37 +75,37 @@ extern "C" __host__ __device__ int chhd2() { return 0; }
 
 /

[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:9450
+def err_nserrordomain_not_tagdecl : Error<
+  "ns_error_domain attribute only valid on "
+  "%select{enums, structs, and unions|enums, structs, unions, and classes}0">;

ns_error_domain -> 'ns_error_domain' (with the single quotes around it, because 
it's syntax).



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:9454
+  "domain argument %0 does not refer to global constant">;
+def err_nserrordomain_requires_identifier : Error<
+  "domain argument must be an identifier">;

I don't think this requires a custom diagnostic -- we can use 
`err_attribute_argument_n_type` instead.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5332
   if (!isa(D)) {
-S.Diag(D->getLocStart(), diag::err_nserrordomain_not_tagdecl)
+S.Diag(D->getBeginLoc(), diag::err_nserrordomain_not_tagdecl)
 << S.getLangOpts().CPlusPlus;

aaron.ballman wrote:
> Where is this error defined?
> Where is this error defined?

Now I found it, it was dropped in the version of the review I was looking at. 
:-)



Comment at: clang/test/Analysis/ns_error_enum.m:1
+// RUN: %clang_cc1 -verify %s
+

I think this test belongs in Sema, not in Analysis (nothing about the feature 
is specific to static analysis).

Also, missing Sema tests that the attribute appertains to the correct subject, 
accepts the correct number and types of arguments, etc.

I'd also appreciate seeing tests of the edge cases, like a locally-defined 
enumeration, a forward declaration of an enumeration, etc.



Comment at: clang/test/Analysis/ns_error_enum.m:1
+// RUN: %clang_cc1 -verify %s
+

MForster wrote:
> gribozavr2 wrote:
> > This file is a `.m` -- any specific reason? I'd call it `.c` and run the 
> > test in C, Objective-C, and C++ modes (enums might work slightly 
> > differently, the name lookup functionality might work differently).
> The test doesn't compile in C or C++ (`non-defining declaration of 
> enumeration with a fixed underlying type is only permitted as a standalone 
> declaration; missing list of enumerators?`). Not sure if it's worth adapting.
Enums with fixed underlying types exist in C++ and C, so I was expecting the 
attribute to work there. If the attribute isn't supported in these languages, 
should the attribute be tied to a language mode?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D84018: Port Preprocessor and PreprocessorOutput option flags to new option parsing system

2020-07-17 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Depends on D83979 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84018

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3054,15 +3054,9 @@
   Opts.ImplicitPCHInclude = std::string(Args.getLastArgValue(OPT_include_pch));
   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
 Args.hasArg(OPT_pch_through_hdrstop_use);
-  Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create);
   Opts.PCHThroughHeader =
   std::string(Args.getLastArgValue(OPT_pch_through_header_EQ));
-  Opts.UsePredefines = !Args.hasArg(OPT_undef);
-  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
-  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
-  Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
 
-  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
 
@@ -3145,9 +3139,6 @@
   // "editor placeholder in source file" error in PP only mode.
   if (isStrictlyPreprocessorAction(Action))
 Opts.LexEditorPlaceholders = false;
-
-  Opts.SetUpStaticAnalyzer = Args.hasArg(OPT_setup_static_analyzer);
-  Opts.DisablePragmaDebugCrash = Args.hasArg(OPT_disable_pragma_debug_crash);
 }
 
 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
@@ -3158,14 +3149,7 @@
   else
 Opts.ShowCPP = 0;
 
-  Opts.ShowComments = Args.hasArg(OPT_C);
-  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
-  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
-  Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
-  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
-  Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
-  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
 }
 
 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1429,6 +1429,57 @@
 
 } // Flags = [CC1Option, NoDriverOption]
 
+// Preprocessor Options
+
+def undef : Flag<["-"], "undef">, Group, Flags<[CC1Option]>,
+  HelpText<"undef all system defines">,
+  MarshallingInfoFlag<"PreprocessorOpts->UsePredefines", "true">, IsNegative;
+
+let Flags = [CC1Option, NoDriverOption] in {
+
+def pch_through_hdrstop_create : Flag<["-"], "pch-through-hdrstop-create">,
+  HelpText<"When creating a PCH, stop PCH generation after #pragma hdrstop.">,
+  MarshallingInfoFlag<"PreprocessorOpts->PCHWithHdrStopCreate", "false">;
+def fno_validate_pch : Flag<["-"], "fno-validate-pch">,
+  HelpText<"Disable validation of precompiled headers">,
+  MarshallingInfoFlag<"PreprocessorOpts->DisablePCHValidation", "false">;
+def fallow_pch_with_errors : Flag<["-"], "fallow-pch-with-compiler-errors">,
+  HelpText<"Accept a PCH file that was created with compiler errors">,
+  MarshallingInfoFlag<"PreprocessorOpts->AllowPCHWithCompilerErrors", "false">;
+def dump_deserialized_pch_decls : Flag<["-"], "dump-deserialized-decls">,
+  HelpText<"Dump declarations that are deserialized from PCH, for testing">,
+  MarshallingInfoFlag<"PreprocessorOpts->DumpDeserializedPCHDecls", "false">;
+def detailed_preprocessing_record : Flag<["-"], "detailed-preprocessing-record">,
+  HelpText<"include a detailed record of preprocessing actions">,
+  MarshallingInfoFlag<"PreprocessorOpts->DetailedRecord", "false">;
+def setup_static_analyzer : Flag<["-"], "setup-static-analyzer">,
+  HelpText<"Set up preprocessor for static analyzer (done automatically when static analyzer is run).">,
+  MarshallingInfoFlag<"PreprocessorOpts->SetUpStaticAnalyzer", "false">;
+def disable_pragma_debug_crash : Flag<["-"], "disable-pragma-debug-crash">,
+  HelpText<"Disable any #pragma clang __debug that can lead to crashing behavior. This is meant for testing.">,
+  MarshallingInfoFlag<"PreprocessorOpts->DisablePragmaDebugCrash", "false">;
+
+} // Flags = [CC1Option, NoDriverOption]
+
+// Preprocessor Output Options
+
+def CC : Flag<["-"], "CC">, Flags<[CC1Option]>, Group,
+HelpText<"Include comments from within macros in preprocessed output">,
+MarshallingInfoFlag<"PreprocessorOutputOpts.ShowMacroComments", "false">; 
+def C : Flag<["-"], "C">, Flags<[CC1Option]>, Group,
+HelpText<"Include comments in preprocessed output">,

[clang] de0c6bd - Add -o /dev/null to make it explicit that we don't care about the

2020-07-17 Thread Adrian Kuegel via cfe-commits

Author: Adrian Kuegel
Date: 2020-07-17T14:21:13+02:00
New Revision: de0c6bd56b41081f1b89a1c7a0bf2597fd6d0104

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

LOG: Add -o /dev/null to make it explicit that we don't care about the
compiler output.

Added: 


Modified: 
clang/test/Driver/aarch64-sve-vector-bits.c

Removed: 




diff  --git a/clang/test/Driver/aarch64-sve-vector-bits.c 
b/clang/test/Driver/aarch64-sve-vector-bits.c
index b7138d4a0772..c3d0d05bb9b6 100644
--- a/clang/test/Driver/aarch64-sve-vector-bits.c
+++ b/clang/test/Driver/aarch64-sve-vector-bits.c
@@ -45,8 +45,8 @@
 
 // Error if using attribute without -msve-vector-bits
 // 
-
-// RUN: not %clang -c %s -target aarch64-none-linux-gnu -march=armv8-a+sve \
-// RUN:  2>&1 | FileCheck --check-prefix=CHECK-NO-FLAG-ERROR %s
+// RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
+// RUN:  -march=armv8-a+sve 2>&1 | FileCheck 
--check-prefix=CHECK-NO-FLAG-ERROR %s
 
 typedef __SVInt32_t svint32_t;
 typedef svint32_t noflag __attribute__((arm_sve_vector_bits(256)));
@@ -55,8 +55,8 @@ typedef svint32_t noflag 
__attribute__((arm_sve_vector_bits(256)));
 
 // Error if attribute vector size != -msve-vector-bits
 // 
-
-// RUN: not %clang -c %s -target aarch64-none-linux-gnu -march=armv8-a+sve \
-// RUN:  -msve-vector-bits=128 2>&1 | FileCheck 
--check-prefix=CHECK-BAD-VECTOR-SIZE-ERROR %s
+// RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
+// RUN:  -march=armv8-a+sve -msve-vector-bits=128 2>&1 | FileCheck 
--check-prefix=CHECK-BAD-VECTOR-SIZE-ERROR %s
 
 typedef svint32_t bad_vector_size __attribute__((arm_sve_vector_bits(256)));
 



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


[PATCH] D83822: [clangd] Support config over LSP.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:1220
   CDB->setCompileCommand(File, std::move(New));
   ModifiedFiles.insert(File);
 }

kadircet wrote:
> nit: maybe just set `ReparseAllFiles` in here too, and change the condition 
> below to only `return ReparseAllFiles`
Is the idea here that triggering spurious reparses is cheap enough?
Or that if it's cheap enough for our "future-facing" extension, we should be 
able to stop optimizing it for the existing one?



Comment at: clang-tools-extra/clangd/Protocol.h:494
+  // Each value is an Object or null, and replaces any fragment with that key.
+  // Fragments are used in key order ("!foo" is low-priority, "~foo" is high).
+  std::map fragments;

kadircet wrote:
> it feels like clients will only be using two types of keys, a "global" one 
> for sending over (likely project-specific) user preferences and another for 
> directory/file specific configs. The latter is likely to have the path as a 
> key, whereas the former will likely be a special identifier. I am glad that 
> `!` comes before both `/` and any capital letters(letter drives).
> 
> I think it is only important to have a distinction between these two types (a 
> subset of what you describe here). Current design makes it really easy on our 
> side, I am just afraid of confusing clients. Maybe we should just have an 
> enum/boolean tag saying if the fragment is global or not instead of relying 
> on the key orderings ?
If we go down this path, where do we draw the line?
(this isn't a slipper-slope argument - I think it's a reasonable idea and we 
should work out how far we want to take it)

If we're encoding this file/directory use case in the protocol somehow, why 
wouldn't we *require* the key to be a path, and no longer require a condition 
to be set for that? This is like how `.clangd` files are handled.

Then we'd have a more natural way of dealing with priority between 
file/dir-specific entries (actually, maybe it coincides with sort order, ha!).

But this model starts to look something much closer to the 
`workspace/configuration` server->client request, which has a scope URI 
attached. The recommendation from LSP folks is that actual configuration flow 
over that endpoint, and didChangeConfiguration just be used to notify of 
changes.

That hasn't seemed feasible for us as we imagine all the requests issues by 
background index, and the bother of making everything consuming config 
asynchronous. But:
 - if we restricted per-URI config to per-directory, not per-file, the number 
of requests aren't overwhelming (assuming caching). It's still possible to 
achieve per-file config with conditions...
 - async seems fundamentally solvable, given that we only create config on 
TUScheduler threads and background-index threads now, never the main thread 
(unless in sync mode...). Technical details to work out of course (if the 
server doesn't get a response it'll want to time out, but what thread does the 
timeout handler run on?)

It would help there were some clearer practical goal we were driving towards. 
Propagating, say, vscode extension settings live into clangd can be done this 
way, but it's a sledgehammer for a peanut. Maybe live-configuring *workspace* 
properties is an interesting thing, but I'm not sure how much value there is 
when `.clangd` exists.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83822



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


[clang] fd02a86 - [analyzer] Add system header simulator a symmetric random access iterator operator+

2020-07-17 Thread Endre Fülöp via cfe-commits

Author: Endre Fülöp
Date: 2020-07-17T14:36:43+02:00
New Revision: fd02a86260b3fb01361175af9600d53354631fb2

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

LOG: [analyzer] Add system header simulator a symmetric random access iterator 
operator+

Summary:
Random access iterators must handle operator+, where the iterator is on the
RHS. The system header simulator library is extended with these operators.

Reviewers: Szelethus

Subscribers: whisperity, xazax.hun, baloghadamsoftware, szepet, a.sidorin, 
mikhail.ramalho, Szelethus, donat.nagy, dkrupp, Charusso, steakhal, martong, 
ASDenysPetrov, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/test/Analysis/Inputs/system-header-simulator-cxx.h
clang/test/Analysis/diagnostics/explicit-suppression.cpp

Removed: 




diff  --git a/clang/test/Analysis/Inputs/system-header-simulator-cxx.h 
b/clang/test/Analysis/Inputs/system-header-simulator-cxx.h
index fe4b9d081e9c..1dee3294d732 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -60,6 +60,11 @@ template  struct 
__vector_iterator {
   __vector_iterator operator+(
diff erence_type n) {
 return ptr + n;
   }
+  friend __vector_iterator operator+(
+  
diff erence_type n,
+  const __vector_iterator &iter) {
+return n + iter.ptr;
+  }
   __vector_iterator operator-(
diff erence_type n) {
 return ptr - n;
   }
@@ -118,6 +123,11 @@ template  struct 
__deque_iterator {
   __deque_iterator operator+(
diff erence_type n) {
 return ptr + n;
   }
+  friend __deque_iterator operator+(
+  
diff erence_type n,
+  const __deque_iterator &iter) {
+return n + iter.ptr;
+  }
   __deque_iterator operator-(
diff erence_type n) {
 return ptr - n;
   }

diff  --git a/clang/test/Analysis/diagnostics/explicit-suppression.cpp 
b/clang/test/Analysis/diagnostics/explicit-suppression.cpp
index 2b586add19ee..0ef01771e58b 100644
--- a/clang/test/Analysis/diagnostics/explicit-suppression.cpp
+++ b/clang/test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@ class C {
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:699 {{Called C++ 
object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:709 {{Called C++ 
object pointer is null}}
 #endif
 }



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


[PATCH] D83226: [analyzer] Add system header simulator a symmetric random access iterator operator+

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfd02a86260b3: [analyzer] Add system header simulator a 
symmetric random access iterator… (authored by gamesh411).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83226

Files:
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/diagnostics/explicit-suppression.cpp


Index: clang/test/Analysis/diagnostics/explicit-suppression.cpp
===
--- clang/test/Analysis/diagnostics/explicit-suppression.cpp
+++ clang/test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:699 {{Called C++ 
object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:709 {{Called C++ 
object pointer is null}}
 #endif
 }
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -60,6 +60,11 @@
   __vector_iterator operator+(difference_type n) {
 return ptr + n;
   }
+  friend __vector_iterator operator+(
+  difference_type n,
+  const __vector_iterator &iter) {
+return n + iter.ptr;
+  }
   __vector_iterator operator-(difference_type n) {
 return ptr - n;
   }
@@ -118,6 +123,11 @@
   __deque_iterator operator+(difference_type n) {
 return ptr + n;
   }
+  friend __deque_iterator operator+(
+  difference_type n,
+  const __deque_iterator &iter) {
+return n + iter.ptr;
+  }
   __deque_iterator operator-(difference_type n) {
 return ptr - n;
   }


Index: clang/test/Analysis/diagnostics/explicit-suppression.cpp
===
--- clang/test/Analysis/diagnostics/explicit-suppression.cpp
+++ clang/test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:699 {{Called C++ object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:709 {{Called C++ object pointer is null}}
 #endif
 }
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -60,6 +60,11 @@
   __vector_iterator operator+(difference_type n) {
 return ptr + n;
   }
+  friend __vector_iterator operator+(
+  difference_type n,
+  const __vector_iterator &iter) {
+return n + iter.ptr;
+  }
   __vector_iterator operator-(difference_type n) {
 return ptr - n;
   }
@@ -118,6 +123,11 @@
   __deque_iterator operator+(difference_type n) {
 return ptr + n;
   }
+  friend __deque_iterator operator+(
+  difference_type n,
+  const __deque_iterator &iter) {
+return n + iter.ptr;
+  }
   __deque_iterator operator-(difference_type n) {
 return ptr - n;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1860
+def NSErrorDomain : Attr {
+  let Spellings = [GNU<"ns_error_domain">];
+  let Args = [IdentifierArgument<"ErrorDomain">];

aaron.ballman wrote:
> MForster wrote:
> > gribozavr2 wrote:
> > > Could we try to add a list of subjects here? It seems like it is a 
> > > type-only attribute, and most likely enum-only.
> > > 
> > > let Subjects = SubjectList<[Enum]>;
> > @milseman, could you comment on this? 
> > 
> > In the meantime I've added the restriction. Obviously this makes the tests 
> > fail. I will also test this change against the Swift unit tests.
> FWIW, this is not a attribute; it's a declaration attribute.
> 
> Is there a reason it's not inheritable?
> 
> I assume it's not getting a Clang spelling because Objective-C isn't tracking 
> C2x yet? (Though that spelling still seems useful to Objective-C++ users in 
> general for these NS attributes.)
> FWIW, this is not a attribute; it's a declaration attribute.

Sorry, yes, of course I meant to say "declaration attribute".

> Is there a reason it's not inheritable?

Good observation, I think it should be.

> I assume it's not getting a Clang spelling because Objective-C isn't tracking 
> C2x yet?

Cocoa users are expected to use the `NS_*` macros instead of using the 
attribute directly, so even if a C2x spelling was an option (IDK if it is), 
there would be very limited use for it.



Comment at: clang/test/Analysis/ns_error_enum.m:1
+// RUN: %clang_cc1 -verify %s
+

aaron.ballman wrote:
> MForster wrote:
> > gribozavr2 wrote:
> > > This file is a `.m` -- any specific reason? I'd call it `.c` and run the 
> > > test in C, Objective-C, and C++ modes (enums might work slightly 
> > > differently, the name lookup functionality might work differently).
> > The test doesn't compile in C or C++ (`non-defining declaration of 
> > enumeration with a fixed underlying type is only permitted as a standalone 
> > declaration; missing list of enumerators?`). Not sure if it's worth 
> > adapting.
> Enums with fixed underlying types exist in C++ and C, so I was expecting the 
> attribute to work there. If the attribute isn't supported in these languages, 
> should the attribute be tied to a language mode?
There are Apple SDK headers that parse in all language modes (C, Objective-C, 
C++, Objective-C++), so I think it is quite important to test this feature in 
all modes. I suspect the reason for the error is that different language modes 
require a slightly different macro definition.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D83914: [clangd] Plan features for FoldingRanges

2020-07-17 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev planned changes to this revision.
kbobyrev added a comment.

Will resolve the comments and add some missing examples.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83914



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


[clang] 16a4350 - [MSP430] Actualize the toolchain description

2020-07-17 Thread Anatoly Trosinenko via cfe-commits

Author: Anatoly Trosinenko
Date: 2020-07-17T15:42:12+03:00
New Revision: 16a4350f76d2bead7af32617dd557d2ec096d2c5

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

LOG: [MSP430] Actualize the toolchain description

Reviewed By: krisb

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

Added: 

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin_no_eh.o
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin_no_eh.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend_no_eh.o
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/include/stdio.h

clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/exceptions/crt0.o
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/crt0.o
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/exceptions/crt0.o
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/crt0.o

clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/exceptions/crt0.o

clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/crt0.o

clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/exceptions/crt0.o

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Basic/Targets/MSP430.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/MSP430.cpp
clang/lib/Driver/ToolChains/MSP430.h
clang/test/Driver/msp430-toolchain.c

Removed: 

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtbegin.o

clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtend.o
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/crtn.o



diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td

[PATCH] D81676: [MSP430] Align the toolchain definition with the TI's msp430-gcc v9.2.0

2020-07-17 Thread Anatoly Trosinenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG16a4350f76d2: [MSP430] Actualize the toolchain description 
(authored by atrosinenko).

Changed prior to commit:
  https://reviews.llvm.org/D81676?vs=276693&id=278741#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81676

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/MSP430.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/MSP430.cpp
  clang/lib/Driver/ToolChains/MSP430.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/include/stdio.h
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/crtn.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/exceptions/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/exceptions/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/exceptions/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/exceptions/crt0.o
  clang/test/Driver/msp430-toolchain.c

Index: clang/test/Driver/msp430-toolchain.c
===
--- clang/test/Driver/msp430-toolchain.c
+++ clang/test/Driver/msp430-toolchain.c
@@ -1,78 +1,264 @@
-// A basic clang -cc1 command-line, and simple environment check.
+// Splitting some tests into POS and NEG part

[PATCH] D81676: [MSP430] Align the toolchain definition with the TI's msp430-gcc v9.2.0

2020-07-17 Thread Anatoly Trosinenko via Phabricator via cfe-commits
atrosinenko added a comment.

After a final retesting, this patch was updated a bit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81676



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


[PATCH] D83961: [Analyzer] Fix bug report source locations in minimal output.

2020-07-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 278742.
balazske marked an inline comment as done.
balazske added a comment.

Fixed some source location changes in tests.
Re-added check for empty path.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83961

Files:
  clang/lib/Analysis/PathDiagnostic.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/test/Analysis/CGColorSpace.c
  clang/test/Analysis/NSString.m
  clang/test/Analysis/malloc-plist.c

Index: clang/test/Analysis/malloc-plist.c
===
--- clang/test/Analysis/malloc-plist.c
+++ clang/test/Analysis/malloc-plist.c
@@ -135,8 +135,8 @@
 static void function_with_leak3(int y) {
 char *x = (char*)malloc(12);
 if (y)
-y++;
-}//expected-warning{{Potential leak}}
+  y++; //expected-warning{{Potential leak}}
+}
 void use_function_with_leak3(int y) {
 function_with_leak3(y);
 }
Index: clang/test/Analysis/NSString.m
===
--- clang/test/Analysis/NSString.m
+++ clang/test/Analysis/NSString.m
@@ -125,13 +125,13 @@
 
 NSString* f7(NSString* s1, NSString* s2, NSString* s3) {
 
-  NSString* s4 = (NSString*)
-CFStringCreateWithFormat(kCFAllocatorDefault, 0,  // expected-warning{{leak}}
- (CFStringRef) __builtin___CFStringMakeConstantString("%@ %@ (%@)"), 
- s1, s2, s3);
+  NSString *s4 = (NSString *)
+  CFStringCreateWithFormat(kCFAllocatorDefault, 0,
+   (CFStringRef)__builtin___CFStringMakeConstantString("%@ %@ (%@)"),
+   s1, s2, s3);
 
   CFRetain(s4);
-  return s4;
+  return s4; // expected-warning{{leak}}
 }
 
 NSMutableArray* f8() {
@@ -202,15 +202,15 @@
 }
 - (void)m1
 {
- NSString *s = [[NSString alloc] init]; // expected-warning{{leak}}
- [s retain];
- [s autorelease];
-}
+  NSString *s = [[NSString alloc] init];
+  [s retain];
+  [s autorelease];
+} // expected-warning{{leak}}
 - (void)m2
 {
- NSString *s = [[[NSString alloc] init] autorelease]; // expected-warning{{leak}}
- [s retain];
-}
+  NSString *s = [[[NSString alloc] init] autorelease];
+  [s retain];
+} // expected-warning{{leak}}
 - (void)m3
 {
  NSString *s = [[[NSString alloc] init] autorelease];
@@ -219,9 +219,9 @@
 }
 - (void)m4
 {
- NSString *s = [[NSString alloc] init]; // expected-warning{{leak}}
- [s retain];
-}
+  NSString *s = [[NSString alloc] init];
+  [s retain];
+} // expected-warning{{leak}}
 - (void)m5
 {
  NSString *s = [[NSString alloc] init];
@@ -360,9 +360,9 @@
 }
 
 void test_objc_atomicCompareAndSwap_parameter_no_direct_release(NSString **old) {
-  NSString *s = [[NSString alloc] init]; // expected-warning{{leak}}
+  NSString *s = [[NSString alloc] init];
   if (!objc_atomicCompareAndSwapPtr(0, s, old))
-return;
+return; // expected-warning{{leak}}
   else
 [*old release];
 }
@@ -382,8 +382,8 @@
 @end
 
 void test_isTrackedObjectType(void) {
-  NSString *str = [TestIsTracked newString]; // expected-warning{{Potential leak}}
-}
+  NSString *str = [TestIsTracked newString];
+} // expected-warning{{Potential leak}}
 
 // Test isTrackedCFObjectType().
 @interface TestIsCFTracked
@@ -402,9 +402,9 @@
 // Test @synchronized
 void test_synchronized(id x) {
   @synchronized(x) {
-NSString *string = [[NSString stringWithFormat:@"%ld", (long) 100] retain]; // expected-warning {{leak}}
+NSString *string = [[NSString stringWithFormat:@"%ld", (long)100] retain];
   }
-}
+} // expected-warning {{leak}}
 @end
 
 void testOSCompareAndSwapXXBarrier_parameter(NSString **old) {
Index: clang/test/Analysis/CGColorSpace.c
===
--- clang/test/Analysis/CGColorSpace.c
+++ clang/test/Analysis/CGColorSpace.c
@@ -6,9 +6,9 @@
 extern void CGColorSpaceRelease(CGColorSpaceRef space);
 
 void f() {
-  CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB(); // expected-warning{{leak}}
+  CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB();
   CGColorSpaceRetain(X);
-}
+} // expected-warning{{leak}}
 
 void fb() {
   CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB();
Index: clang/lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -1997,9 +1997,6 @@
   return nullptr;
   }
 
-  if (!PDC->shouldGenerateDiagnostics())
-return generateEmptyDiagnosticForReport(R, getSourceManager());
-
   // Construct the final (warning) event for the bug report.
   auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
   PathDiagnosticPieceRef LastPiece;
@@ -2012,6 +2009,9 @@
   }
   Construct.PD->setEndOfPath(LastPiece);
 
+  if (!PDC->shouldGenerateDiagnostics())
+return std::move(Construct.PD);
+
   PathDiagnosticLocation PrevLoc = 

[PATCH] D83961: [Analyzer] Fix bug report source locations in minimal output.

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

Big part of the test failures is with the `osx.cocoa.RetainCount` checker. Only 
a small part of the errors is fixed now.




Comment at: clang/lib/Analysis/PathDiagnostic.cpp:369
+}
+  }
   if (X.getBugType() != Y.getBugType())

This change is needed to eliminate crash in tests at `assert(b.hasValue());`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83961



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


[PATCH] D84021: [Driver] Add suppoort for -msve-vector-bits=scalable.

2020-07-17 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm created this revision.
Herald added subscribers: cfe-commits, tschuett.
Herald added a project: clang.

No real action is taken for a value of scalable but it provides a
route to disable an earlier specification and is effectively its
default value when omitted.

Patch also removes an "unused variable" warning.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84021

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/aarch64-sve-vector-bits.c


Index: clang/test/Driver/aarch64-sve-vector-bits.c
===
--- clang/test/Driver/aarch64-sve-vector-bits.c
+++ clang/test/Driver/aarch64-sve-vector-bits.c
@@ -12,12 +12,15 @@
 // RUN:  -msve-vector-bits=1024 2>&1 | FileCheck --check-prefix=CHECK-1024 %s
 // RUN: %clang -c %s -### -target aarch64-none-linux-gnu -march=armv8-a+sve \
 // RUN:  -msve-vector-bits=2048 2>&1 | FileCheck --check-prefix=CHECK-2048 %s
+// RUN: %clang -c %s -### -target aarch64-none-linux-gnu -march=armv8-a+sve \
+// RUN:  -msve-vector-bits=scalable 2>&1 | FileCheck 
--check-prefix=CHECK-SCALABLE %s
 
 // CHECK-128: "-msve-vector-bits=128"
 // CHECK-256: "-msve-vector-bits=256"
 // CHECK-512: "-msve-vector-bits=512"
 // CHECK-1024: "-msve-vector-bits=1024"
 // CHECK-2048: "-msve-vector-bits=2048"
+// CHECK-SCALABLE-NOT: "-msve-vector-bits=
 
 // Bail out if -msve-vector-bits is specified without SVE enabled
 // 
-
@@ -47,11 +50,13 @@
 // 
-
 // RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
 // RUN:  -march=armv8-a+sve 2>&1 | FileCheck 
--check-prefix=CHECK-NO-FLAG-ERROR %s
+// RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
+// RUN:  -march=armv8-a+sve -msve-vector-bits=scalable 2>&1 | FileCheck 
--check-prefix=CHECK-NO-FLAG-ERROR %s
 
 typedef __SVInt32_t svint32_t;
 typedef svint32_t noflag __attribute__((arm_sve_vector_bits(256)));
 
-// CHECK-NO-FLAG-ERROR: error: 'arm_sve_vector_bits' is not supported when 
'-msve-vector-bits=' is not specified
+// CHECK-NO-FLAG-ERROR: error: 'arm_sve_vector_bits' is only supported when 
'-msve-vector-bits=' is specified with a value of 128, 256, 512, 1024 or 
2048
 
 // Error if attribute vector size != -msve-vector-bits
 // 
-
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1720,15 +1720,15 @@
   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
 StringRef Val = A->getValue();
 const Driver &D = getToolChain().getDriver();
-if (!Val.equals("128") && !Val.equals("256") && !Val.equals("512") &&
-!Val.equals("1024") && !Val.equals("2048")) {
+if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
+Val.equals("1024") || Val.equals("2048"))
+  CmdArgs.push_back(
+  Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
+// Silently drop requests for vector-length agnostic code as it's implied.
+else if (!Val.equals("scalable"))
   // Handle the unsupported values passed to msve-vector-bits.
   D.Diag(diag::err_drv_unsupported_option_argument)
   << A->getOption().getName() << Val;
-} else if (A->getOption().matches(options::OPT_msve_vector_bits_EQ)) {
-  CmdArgs.push_back(
-  Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
-}
   }
 }
 
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -370,8 +370,8 @@
 V8_6Pos = Features.insert(std::next(V8_6Pos), {"+i8mm", "+bf16"});
 
   bool HasSve = llvm::is_contained(Features, "+sve");
-  // -msve_vector_bits= flag is valid only if SVE is enabled.
-  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
+  // -msve-vector-bits= flag is valid only if SVE is enabled.
+  if (Args.hasArg(options::OPT_msve_vector_bits_EQ))
 if (!HasSve)
   D.Diag(diag::err_drv_invalid_sve_vector_bits);
 
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2816,7 +2816,8 @@
   "invalid SVE vector size '%0', must match value set by "
   "'-msve-vector-bits' ('%1')">;
 def err_attribute_arm_feature_sve_bits_unsupported : Error<
-  "%0 is not supported when '-msve-vector-bits=' is not specified">;
+  "%0 is only supported when

[PATCH] D84021: [Driver] Add suppoort for -msve-vector-bits=scalable.

2020-07-17 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm updated this revision to Diff 278744.
paulwalker-arm added a comment.

Fixed typo to match existing wrapping style.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84021

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/aarch64-sve-vector-bits.c


Index: clang/test/Driver/aarch64-sve-vector-bits.c
===
--- clang/test/Driver/aarch64-sve-vector-bits.c
+++ clang/test/Driver/aarch64-sve-vector-bits.c
@@ -12,12 +12,15 @@
 // RUN:  -msve-vector-bits=1024 2>&1 | FileCheck --check-prefix=CHECK-1024 %s
 // RUN: %clang -c %s -### -target aarch64-none-linux-gnu -march=armv8-a+sve \
 // RUN:  -msve-vector-bits=2048 2>&1 | FileCheck --check-prefix=CHECK-2048 %s
+// RUN: %clang -c %s -### -target aarch64-none-linux-gnu -march=armv8-a+sve \
+// RUN:  -msve-vector-bits=scalable 2>&1 | FileCheck 
--check-prefix=CHECK-SCALABLE %s
 
 // CHECK-128: "-msve-vector-bits=128"
 // CHECK-256: "-msve-vector-bits=256"
 // CHECK-512: "-msve-vector-bits=512"
 // CHECK-1024: "-msve-vector-bits=1024"
 // CHECK-2048: "-msve-vector-bits=2048"
+// CHECK-SCALABLE-NOT: "-msve-vector-bits=
 
 // Bail out if -msve-vector-bits is specified without SVE enabled
 // 
-
@@ -47,11 +50,13 @@
 // 
-
 // RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
 // RUN:  -march=armv8-a+sve 2>&1 | FileCheck 
--check-prefix=CHECK-NO-FLAG-ERROR %s
+// RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
+// RUN:  -march=armv8-a+sve -msve-vector-bits=scalable 2>&1 | FileCheck 
--check-prefix=CHECK-NO-FLAG-ERROR %s
 
 typedef __SVInt32_t svint32_t;
 typedef svint32_t noflag __attribute__((arm_sve_vector_bits(256)));
 
-// CHECK-NO-FLAG-ERROR: error: 'arm_sve_vector_bits' is not supported when 
'-msve-vector-bits=' is not specified
+// CHECK-NO-FLAG-ERROR: error: 'arm_sve_vector_bits' is only supported when 
'-msve-vector-bits=' is specified with a value of 128, 256, 512, 1024 or 
2048
 
 // Error if attribute vector size != -msve-vector-bits
 // 
-
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1720,15 +1720,15 @@
   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
 StringRef Val = A->getValue();
 const Driver &D = getToolChain().getDriver();
-if (!Val.equals("128") && !Val.equals("256") && !Val.equals("512") &&
-!Val.equals("1024") && !Val.equals("2048")) {
+if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
+Val.equals("1024") || Val.equals("2048"))
+  CmdArgs.push_back(
+  Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
+// Silently drop requests for vector-length agnostic code as it's implied.
+else if (!Val.equals("scalable"))
   // Handle the unsupported values passed to msve-vector-bits.
   D.Diag(diag::err_drv_unsupported_option_argument)
   << A->getOption().getName() << Val;
-} else if (A->getOption().matches(options::OPT_msve_vector_bits_EQ)) {
-  CmdArgs.push_back(
-  Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
-}
   }
 }
 
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -370,8 +370,8 @@
 V8_6Pos = Features.insert(std::next(V8_6Pos), {"+i8mm", "+bf16"});
 
   bool HasSve = llvm::is_contained(Features, "+sve");
-  // -msve_vector_bits= flag is valid only if SVE is enabled.
-  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
+  // -msve-vector-bits= flag is valid only if SVE is enabled.
+  if (Args.hasArg(options::OPT_msve_vector_bits_EQ))
 if (!HasSve)
   D.Diag(diag::err_drv_invalid_sve_vector_bits);
 
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2816,7 +2816,8 @@
   "invalid SVE vector size '%0', must match value set by "
   "'-msve-vector-bits' ('%1')">;
 def err_attribute_arm_feature_sve_bits_unsupported : Error<
-  "%0 is not supported when '-msve-vector-bits=' is not specified">;
+  "%0 is only supported when '-msve-vector-bits=' is specified with a "
+  "value of 128, 256, 512, 1024 or 2048.">;
 def err_attribute_requires_positive_integ

[PATCH] D83190: [analyzer] Model iterator random incrementation symmetrically

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 278747.
gamesh411 added a comment.

rebase upon hotfix patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83190

Files:
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/test/Analysis/iterator-modeling.cpp

Index: clang/test/Analysis/iterator-modeling.cpp
===
--- clang/test/Analysis/iterator-modeling.cpp
+++ clang/test/Analysis/iterator-modeling.cpp
@@ -149,7 +149,7 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning-re {{$v.end(){{$
 }
 
-void plus(const std::vector &v) {
+void lhs_plus(const std::vector &v) {
   auto i1 = v.begin();
 
   clang_analyzer_denote(clang_analyzer_container_begin(v), "$v.begin()");
@@ -161,7 +161,19 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning-re{{$v.begin() + 2{{$
 }
 
-void plus_negative(const std::vector &v) {
+void rhs_plus(const std::vector &v) {
+  auto i1 = v.begin();
+
+  clang_analyzer_denote(clang_analyzer_container_begin(v), "$v.begin()");
+
+  auto i2 = 2 + i1;
+
+  clang_analyzer_eval(clang_analyzer_iterator_container(i2) == &v); // expected-warning{{TRUE}}
+  clang_analyzer_express(clang_analyzer_iterator_position(i1)); // expected-warning-re{{$v.begin(){{$
+  clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning-re{{$v.begin() + 2{{$
+}
+
+void lhs_plus_negative(const std::vector &v) {
   auto i1 = v.end();
 
   clang_analyzer_denote(clang_analyzer_container_end(v), "$v.end()");
@@ -173,6 +185,18 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning-re {{$v.end() - 2{{$
 }
 
+void rhs_plus_negative(const std::vector &v) {
+  auto i1 = v.end();
+
+  clang_analyzer_denote(clang_analyzer_container_end(v), "$v.end()");
+
+  auto i2 = (-2) + i1;
+
+  clang_analyzer_eval(clang_analyzer_iterator_container(i2) == &v); // expected-warning{{TRUE}}
+  clang_analyzer_express(clang_analyzer_iterator_position(i1)); // expected-warning-re {{$v.end(){{$
+  clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning-re {{$v.end() - 2{{$
+}
+
 void minus(const std::vector &v) {
   auto i1 = v.end();
 
@@ -1955,7 +1979,7 @@
   i -= n; // no-crash
 }
 
-void plus_ptr_iterator(const cont_with_ptr_iterator &c) {
+void lhs_plus_ptr_iterator(const cont_with_ptr_iterator &c) {
   auto i1 = c.begin();
 
   clang_analyzer_denote(clang_analyzer_container_begin(c), "$c.begin()");
@@ -1967,6 +1991,18 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning{{$c.begin() + 2}}
 }
 
+void rhs_plus_ptr_iterator(const cont_with_ptr_iterator &c) {
+  auto i1 = c.begin();
+
+  clang_analyzer_denote(clang_analyzer_container_begin(c), "$c.begin()");
+
+  auto i2 = 2 + i1;
+
+  clang_analyzer_eval(clang_analyzer_iterator_container(i2) == &c); // expected-warning{{TRUE}}
+  clang_analyzer_express(clang_analyzer_iterator_position(i1)); // expected-warning{{$c.begin()}}
+  clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning{{$c.begin() + 2}}
+}
+
 void minus_ptr_iterator(const cont_with_ptr_iterator &c) {
   auto i1 = c.end();
 
Index: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
@@ -109,7 +109,7 @@
bool Postfix) const;
   void handleRandomIncrOrDecr(CheckerContext &C, const Expr *CE,
   OverloadedOperatorKind Op, const SVal &RetVal,
-  const SVal &LHS, const SVal &RHS) const;
+  const SVal &Iterator, const SVal &Offset) const;
   void handlePtrIncrOrDecr(CheckerContext &C, const Expr *Iterator,
OverloadedOperatorKind OK, SVal Offset) const;
   void handleAdvance(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
@@ -262,20 +262,30 @@
 
 void IteratorModeling::checkPostStmt(const BinaryOperator *BO,
  CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
-  BinaryOperatorKind OK = BO->getOpcode();
-  SVal RVal = State->getSVal(BO->getRHS(), C.getLocationContext());
+  const ProgramStateRef State = C.getState();
+  const BinaryOperatorKind OK = BO->getOpcode();
+  const Expr *const LHS = BO->getLHS();
+  const Expr *const RHS = BO->getRHS();
+  const SVal LVal = State->getSVal(LHS, C.getLocationContext());
+  const SVal RVal = State->getSVal(RHS, C.getLocationContext());
 
   if (isSimpleComparisonOperator(BO->getOpcode())) {
-SVal LVal = State->getSVal(BO->getLHS(), C.getLocationContext());
 SVal Result = State->getSVal(BO, C.getL

[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 4 inline comments as done.
sammccall added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Tokens.h:281
+  std::vector
+  expansionsAffecting(llvm::ArrayRef Spelled) const;
 

kadircet wrote:
> this sounds more like `expansionsAffected` rather than affecting ? maybe my 
> mental model requires correction, but it feels like spelled tokens are not 
> affected by expansions, it is the other way around.
> 
> maybe even `expansionsSpawned` or `triggered`?
> 
> this is definitely non-blocking though, i am just bikesheding, comment is 
> explanatory enough in any case.
Either mental model works I think. Mine is that expansions are rewrite rules - 
you start with a stream of tokens, and then each expansion mutates it, and you 
end up with different ones.

Renamed to `expansionsOverlapping` which seems more neutral and consistent with 
expansionStartingAt



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:431
+std::vector
+TokenBuffer::expansionsAffecting(llvm::ArrayRef Spelled) const {
+  if (Spelled.empty())

kadircet wrote:
> this might be inconistent with spelledForExpanded from time to time, e.g:
> 
> ```
> #define FOO(X) 123
> #define BAR
> 
> void foo() {
>   FOO(BA^R);
> }
> ```
> 
> normally BAR has no expansions, but I think it will get merged into outer 
> macro expansion e.g. `123` coming from `FOO(BAR)`. (whereas 
> spelledForExpanded will treat `BAR` in isolation)
> 
> not sure an important limitation but something to keep in mind.
I don't understand the consistency you're looking for - AFAICS these are 
different functions that do different things - spelledForExpanded is much 
higher level.

Is there something in the name or comment I can add/remove to clarify?

> normally BAR has no expansions

Tokens don't really "have expansions" - they're *part of* expansions. Generally 
expansionsOverlapping() will return the expansions themselves that are 
overlapping, while spelledForExpanded will include the expanded tokens if the 
whole expansion is in-range.

The former is a building-block (returning Expansions seems like a clear 
indicator of that) that will usually require some postfiltering, while the 
latter is fairly directly usable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009



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


[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 278748.
sammccall added a comment.

expansionsAffecting->expansionsOverlapping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009

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

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -53,6 +53,7 @@
 using namespace clang::syntax;
 
 using llvm::ValueIs;
+using ::testing::_;
 using ::testing::AllOf;
 using ::testing::Contains;
 using ::testing::ElementsAre;
@@ -755,7 +756,7 @@
   EXPECT_THAT(Buffer.expandedTokens(SourceRange()), testing::IsEmpty());
 }
 
-TEST_F(TokenBufferTest, ExpansionStartingAt) {
+TEST_F(TokenBufferTest, ExpansionsOverlapping) {
   // Object-like macro expansions.
   recordTokens(R"cpp(
 #define FOO 3+4
@@ -763,17 +764,25 @@
 int b = FOO 2;
   )cpp");
 
-  llvm::ArrayRef Foo1 = findSpelled("FOO 1").drop_back();
+  llvm::ArrayRef Foo1 = findSpelled("FOO 1");
   EXPECT_THAT(
   Buffer.expansionStartingAt(Foo1.data()),
-  ValueIs(IsExpansion(SameRange(Foo1),
+  ValueIs(IsExpansion(SameRange(Foo1.drop_back()),
   SameRange(findExpanded("3 + 4 1").drop_back();
+  EXPECT_THAT(
+  Buffer.expansionsOverlapping(Foo1),
+  ElementsAre(IsExpansion(SameRange(Foo1.drop_back()),
+  SameRange(findExpanded("3 + 4 1").drop_back();
 
-  llvm::ArrayRef Foo2 = findSpelled("FOO 2").drop_back();
+  llvm::ArrayRef Foo2 = findSpelled("FOO 2");
   EXPECT_THAT(
   Buffer.expansionStartingAt(Foo2.data()),
-  ValueIs(IsExpansion(SameRange(Foo2),
+  ValueIs(IsExpansion(SameRange(Foo2.drop_back()),
   SameRange(findExpanded("3 + 4 2").drop_back();
+  EXPECT_THAT(Buffer.expansionsOverlapping(
+  llvm::makeArrayRef(Foo1.begin(), Foo2.end())),
+  ElementsAre(IsExpansion(SameRange(Foo1.drop_back()), _),
+  IsExpansion(SameRange(Foo2.drop_back()), _)));
 
   // Function-like macro expansions.
   recordTokens(R"cpp(
@@ -798,6 +807,11 @@
   for (const auto &T : ID2.drop_front())
 EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
 
+  EXPECT_THAT(Buffer.expansionsOverlapping(llvm::makeArrayRef(
+  findSpelled("1 + 2").data(), findSpelled("4").data())),
+  ElementsAre(IsExpansion(SameRange(ID1), _),
+  IsExpansion(SameRange(ID2), _)));
+
   // PP directives.
   recordTokens(R"cpp(
 #define FOO 1
@@ -823,6 +837,11 @@
   // Only the first spelled token should be found.
   for (const auto &T : PragmaOnce.drop_front())
 EXPECT_EQ(Buffer.expansionStartingAt(&T), llvm::None);
+
+  EXPECT_THAT(
+  Buffer.expansionsOverlapping(findSpelled("FOO ; # pragma")),
+  ElementsAre(IsExpansion(SameRange(findSpelled("FOO ;").drop_back()), _),
+  IsExpansion(SameRange(PragmaOnce), _)));
 }
 
 TEST_F(TokenBufferTest, TokensToFileRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -249,22 +249,7 @@
 TokenBuffer::expandedForSpelled(llvm::ArrayRef Spelled) const {
   if (Spelled.empty())
 return {};
-  assert(Spelled.front().location().isFileID());
-
-  auto FID = sourceManager().getFileID(Spelled.front().location());
-  auto It = Files.find(FID);
-  assert(It != Files.end());
-
-  const MarkedFile &File = It->second;
-  // `Spelled` must be a subrange of `File.SpelledTokens`.
-  assert(File.SpelledTokens.data() <= Spelled.data());
-  assert(&Spelled.back() <=
- File.SpelledTokens.data() + File.SpelledTokens.size());
-#ifndef NDEBUG
-  auto T1 = Spelled.back().location();
-  auto T2 = File.SpelledTokens.back().location();
-  assert(T1 == T2 || sourceManager().isBeforeInTranslationUnit(T1, T2));
-#endif
+  const auto &File = fileForSpelled(Spelled);
 
   auto *FrontMapping = mappingStartingBeforeSpelled(File, &Spelled.front());
   unsigned SpelledFrontI = &Spelled.front() - File.SpelledTokens.data();
@@ -395,16 +380,39 @@
   : LastSpelled + 1);
 }
 
+TokenBuffer::Expansion TokenBuffer::makeExpansion(const MarkedFile &F,
+  const Mapping &M) const {
+  Expansion E;
+  E.Spelled = llvm::makeArrayRef(F.SpelledTokens.data() + M.BeginSpelled,
+ F.SpelledTokens.data() + M.EndSpelled);
+  E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M.BeginExpanded,
+  ExpandedTokens.data() + M.EndExpanded);
+  return E;
+}
+
+const TokenBuffer::MarkedFile &
+TokenBuffer::fileForS

[clang] 9275e14 - recommit 4fc752b30b9a [CUDA][HIP] Always defer diagnostics for wrong-sided reference

2020-07-17 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2020-07-17T09:14:39-04:00
New Revision: 9275e14379961a4304de559f16fdbac275fb6301

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

LOG: recommit 4fc752b30b9a [CUDA][HIP] Always defer diagnostics for wrong-sided 
reference

Fixed regression in test builtin-amdgcn-atomic-inc-dec-failure.cpp.

Added: 


Modified: 
clang/lib/Sema/SemaCUDA.cpp
clang/test/Sema/builtin-amdgcn-atomic-inc-dec-failure.cpp
clang/test/SemaCUDA/builtins.cu
clang/test/SemaCUDA/call-kernel-from-kernel.cu
clang/test/SemaCUDA/function-overload.cu
clang/test/SemaCUDA/function-target.cu
clang/test/SemaCUDA/implicit-device-lambda.cu
clang/test/SemaCUDA/method-target.cu
clang/test/SemaCUDA/reference-to-kernel-fn.cu

Removed: 




diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index 283a04683a32..6203edea7112 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -715,9 +715,8 @@ bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl 
*Callee) {
   CallerKnownEmitted] {
 switch (IdentifyCUDAPreference(Caller, Callee)) {
 case CFP_Never:
-  return DeviceDiagBuilder::K_Immediate;
 case CFP_WrongSide:
-  assert(Caller && "WrongSide calls require a non-null caller");
+  assert(Caller && "Never/wrongSide calls require a non-null caller");
   // If we know the caller will be emitted, we know this wrong-side call
   // will be emitted, so it's an immediate error.  Otherwise, defer the
   // error until we know the caller is emitted.
@@ -740,9 +739,10 @@ bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl 
*Callee) {
 
   DeviceDiagBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
   << IdentifyCUDATarget(Callee) << Callee << IdentifyCUDATarget(Caller);
-  DeviceDiagBuilder(DiagKind, Callee->getLocation(), diag::note_previous_decl,
-Caller, *this)
-  << Callee;
+  if (!Callee->getBuiltinID())
+DeviceDiagBuilder(DiagKind, Callee->getLocation(), 
diag::note_previous_decl,
+  Caller, *this)
+<< Callee;
   return DiagKind != DeviceDiagBuilder::K_Immediate &&
  DiagKind != DeviceDiagBuilder::K_ImmediateWithCallStack;
 }

diff  --git a/clang/test/Sema/builtin-amdgcn-atomic-inc-dec-failure.cpp 
b/clang/test/Sema/builtin-amdgcn-atomic-inc-dec-failure.cpp
index 9351b4ecb032..88fcbd716ef4 100644
--- a/clang/test/Sema/builtin-amdgcn-atomic-inc-dec-failure.cpp
+++ b/clang/test/Sema/builtin-amdgcn-atomic-inc-dec-failure.cpp
@@ -1,19 +1,26 @@
 // REQUIRES: amdgpu-registered-target
-// RUN: not %clang_cc1 %s -x hip -fcuda-is-device -o - -emit-llvm 
-triple=amdgcn-amd-amdhsa 2>&1 | FileCheck %s
+// RUN: %clang_cc1 %s -x hip -fcuda-is-device -o - \
+// RUN:   -triple=amdgcn-amd-amdhsa -fsyntax-only \
+// RUN:   -verify=dev
+// RUN: %clang_cc1 %s -x hip -triple x86_64 -o - \
+// RUN:   -aux-triple amdgcn-amd-amdhsa -fsyntax-only \
+// RUN:   -verify=host
+
+// dev-no-diagnostics
 
 void test_host() {
   __UINT32_TYPE__ val32;
   __UINT64_TYPE__ val64;
 
-  // CHECK: error: reference to __device__ function 
'__builtin_amdgcn_atomic_inc32' in __host__ function
+  // host-error@+1 {{reference to __device__ function 
'__builtin_amdgcn_atomic_inc32' in __host__ function}}
   val32 = __builtin_amdgcn_atomic_inc32(&val32, val32, __ATOMIC_SEQ_CST, "");
 
-  // CHECK: error: reference to __device__ function 
'__builtin_amdgcn_atomic_inc64' in __host__ function
+  // host-error@+1 {{reference to __device__ function 
'__builtin_amdgcn_atomic_inc64' in __host__ function}}
   val64 = __builtin_amdgcn_atomic_inc64(&val64, val64, __ATOMIC_SEQ_CST, "");
 
-  // CHECK: error: reference to __device__ function 
'__builtin_amdgcn_atomic_dec32' in __host__ function
+  // host-error@+1 {{reference to __device__ function 
'__builtin_amdgcn_atomic_dec32' in __host__ function}}
   val32 = __builtin_amdgcn_atomic_dec32(&val32, val32, __ATOMIC_SEQ_CST, "");
 
-  // CHECK: error: reference to __device__ function 
'__builtin_amdgcn_atomic_dec64' in __host__ function
+  // host-error@+1 {{reference to __device__ function 
'__builtin_amdgcn_atomic_dec64' in __host__ function}}
   val64 = __builtin_amdgcn_atomic_dec64(&val64, val64, __ATOMIC_SEQ_CST, "");
 }

diff  --git a/clang/test/SemaCUDA/builtins.cu b/clang/test/SemaCUDA/builtins.cu
index 814fda2ac7d3..78a333e511a5 100644
--- a/clang/test/SemaCUDA/builtins.cu
+++ b/clang/test/SemaCUDA/builtins.cu
@@ -7,10 +7,10 @@
 // REQUIRES: nvptx-registered-target
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown \
 // RUN: -aux-triple nvptx64-unknown-cuda \
-// RUN: -fsyntax-only -verify %s
+// RUN: -fsyntax-only -verify=host %s
 // RUN: %clang_cc1 

[PATCH] D83501: [clangd][ObjC] Improve xrefs for protocols and classes

2020-07-17 Thread David Goldman via Phabricator via cfe-commits
dgoldman marked 7 inline comments as done.
dgoldman added a comment.

In D83501#2157957 , @sammccall wrote:

> In D83501#2154300 , @dgoldman wrote:
>
> > In D83501#2153605 , @sammccall 
> > wrote:
> >
> > > In D83501#2148671 , @dgoldman 
> > > wrote:
> > >
> > > > I implemented goto-definition from Foo() --> Foo impl in Xrefs, on the 
> > > > symbolcollector side I don't think there's anything to do?
> > >
> > >
> > > This can't be done purely in xrefs as the AST may not be available.
> > >
> > > A.m: `@class Foo; ^Foo x;` <-- go-to-definition at ^
> > >  B.m: `@interface Foo...@end @implementation Foo...@end`
> > >
> > > The index needs to know that for the USR associated with the @class 
> > > (found by targetDecl), the canonical decl is the @interface in B and the 
> > > definition is the @implementation in B.
> > >  So SymbolCollector needs to see it as a definition. **The tests seem to 
> > > show it does already**, but it's not obvious why from the code. Do you 
> > > know? Maybe it's the fact that they share a USR and thus a symbol ID. 
> > > This is worth making explicit somewhere.
> >
> >
> > Think we're talking about different things. See `ObjCClassExtensions` in 
> > SymbolCollectorTests which I added, the idea is that the `Cat ()` can link 
> > to the implementation like I added to XRefs, but I'm not sure how this 
> > should be represented. As for @class -> @interface/@implementation those 
> > should have the same USR, yes.
>
>
> Oh, sorry I indeed missed the parens.
>  Yes, this is a go-to-def special case, SymbolCollector shouldn't need 
> anything. (I'm assuming that a reference to the class is reported already - 
> could add a test that the ref exists if you like).


if I understand this correctly I think `MultipleDeclsWithSameDefinition` 
already tests that, although it relies upon `locateASTReferent` 's 
`TouchedIdentifier` being the interface. Should it always be added instead?




Comment at: clang-tools-extra/clangd/XRefs.cpp:276
getDeclAtPosition(AST, CurLoc, Relations, NodeKind)) {
 // Special case: void foo() ^override: jump to the overridden method.
 if (const auto *CMD = llvm::dyn_cast(D)) {

sammccall wrote:
> dgoldman wrote:
> > sammccall wrote:
> > > dgoldman wrote:
> > > > sammccall wrote:
> > > > > dgoldman wrote:
> > > > > > sammccall wrote:
> > > > > > > dgoldman wrote:
> > > > > > > > sammccall wrote:
> > > > > > > > > dgoldman wrote:
> > > > > > > > > > Think it would make sense to special case ObjCInterfaceDecl 
> > > > > > > > > > here to get at both the interface definition + 
> > > > > > > > > > implementation if available?
> > > > > > > > > Rather than returning both results, I think it's more 
> > > > > > > > > consistent to return them as a declaration/definition pair.
> > > > > > > > > 
> > > > > > > > > (This means special-casing ObjCImplDecl in namedDecl or at 
> > > > > > > > > least getDeclAsPosition, so you always end up with the 
> > > > > > > > > ObjCInterfaceDecl instead)
> > > > > > > > Whoops, meant to comment here but it was lost. I'm not sure 
> > > > > > > > what you meant here. Should this be done here inside the for 
> > > > > > > > loop or in getDeclAtPosition?
> > > > > > > > 
> > > > > > > > Are you saying that given:
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > @interface Foo // A
> > > > > > > > @end
> > > > > > > > @implementation Foo // B
> > > > > > > > @end
> > > > > > > > ```
> > > > > > > > B --> A here
> > > > > > > > 
> > > > > > > > and similarly
> > > > > > > > 
> > > > > > > > ```
> > > > > > > > @interface Foo // A
> > > > > > > > @end
> > > > > > > > @interface Foo (Ext) // B
> > > > > > > > @end
> > > > > > > > @implementation Foo (Ext) // C
> > > > > > > > @end
> > > > > > > > ```
> > > > > > > > B --> A
> > > > > > > > C --> B (and A? it's unclear how this should map over, e.g. 
> > > > > > > > maybe Foo loc --> A, Ext --> B)
> > > > > > > In the first example, selecting either A or B should yield one 
> > > > > > > LocatedSymbol with {Decl=A, Def=B}. This shouldn't require any 
> > > > > > > special-casing.
> > > > > > > 
> > > > > > > The second example is very similar to template specialization, 
> > > > > > > with exceptions:
> > > > > > >  - there's always a Decl/Def pair you may want to navigate 
> > > > > > > between, whereas in templates there rarely is, so we have 
> > > > > > > ambiguity
> > > > > > >  - there's no AST like there is for template names and args, just 
> > > > > > > a bag of tokens
> > > > > > > 
> > > > > > > I'd suggest, given `@interface Foo (Ext)`:
> > > > > > >  - we produce a LocatedSymbol with {Decl=@interface Foo(Ext), 
> > > > > > > Def=@implementation  Foo(Ext)} - this is the default behavior
> > > > > > >  - if the cursor is exactly on the token `Foo`, we also produce a 
> > 

[PATCH] D83501: [clangd][ObjC] Improve xrefs for protocols and classes

2020-07-17 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 278752.
dgoldman marked an inline comment as done.
dgoldman added a comment.

- Minor test and formatting fixes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83501

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -674,7 +674,57 @@
   enum class E { [[A]], B };
   E e = E::A^;
 };
-  )cpp"};
+  )cpp",
+
+  R"objc(
+@protocol Dog;
+@protocol $decl[[Dog]]
+- (void)bark;
+@end
+id getDoggo() {
+  return 0;
+}
+  )objc",
+
+  R"objc(
+@interface Cat
+@end
+@implementation Cat
+@end
+@interface $decl[[Cat]] (Exte^nsion)
+- (void)meow;
+@end
+@implementation $def[[Cat]] (Extension)
+- (void)meow {}
+@end
+  )objc",
+
+  R"objc(
+@class $decl[[Foo]];
+Fo^o * getFoo() {
+  return 0;
+}
+  )objc",
+
+  R"objc(
+@class Foo;
+@interface $decl[[Foo]]
+@end
+Fo^o * getFoo() {
+  return 0;
+}
+  )objc",
+
+  R"objc(
+@class Foo;
+@interface $decl[[Foo]]
+@end
+@implementation $def[[Foo]]
+@end
+Fo^o * getFoo() {
+  return 0;
+}
+  )objc"};
   for (const char *Test : Tests) {
 Annotations T(Test);
 llvm::Optional WantDecl;
@@ -692,6 +742,7 @@
 // FIXME: Auto-completion in a template requires disabling delayed template
 // parsing.
 TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
+TU.ExtraArgs.push_back("-xobjective-c++");
 
 auto AST = TU.build();
 auto Results = locateSymbolAt(AST, T.point());
@@ -709,6 +760,131 @@
   }
 }
 
+TEST(LocateSymbol, AllMulti) {
+  // Ranges in tests:
+  //   $declN is the declaration location
+  //   $defN is the definition location (if absent, symbol has no definition)
+  //
+  // NOTE:
+  //   N starts at 0.
+  //   Due to limitations in clang's Annotations, you can't annotate the same
+  //   text with multiple ranges, e.g. `$def0$def1[[Foo]]` is invalid.
+  struct ExpectedRanges {
+Range WantDecl;
+llvm::Optional WantDef;
+  };
+  const char *Tests[] = {
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @implementation $def0[[Cat]]
+  @end
+  @interface $decl1[[Ca^t]] (Extension)
+  - (void)meow;
+  @end
+  @implementation $def1[[Cat]] (Extension)
+  - (void)meow {}
+  @end
+)objc",
+
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @implementation $def0[[Cat]]
+  @end
+  @interface $decl1[[Cat]] (Extension)
+  - (void)meow;
+  @end
+  @implementation $def1[[Ca^t]] (Extension)
+  - (void)meow {}
+  @end
+)objc",
+  };
+  for (const char *Test : Tests) {
+Annotations T(Test);
+std::vector Ranges;
+for (int Idx = 0; true; Idx++) {
+  bool HasDecl = !T.ranges("decl" + std::to_string(Idx)).empty();
+  bool HasDef = !T.ranges("def" + std::to_string(Idx)).empty();
+  if (!HasDecl && !HasDef)
+break;
+  ExpectedRanges Range;
+  if (HasDecl)
+Range.WantDecl = T.range("decl" + std::to_string(Idx));
+  if (HasDef)
+Range.WantDef = T.range("def" + std::to_string(Idx));
+  Ranges.push_back(Range);
+}
+
+TestTU TU;
+TU.Code = std::string(T.code());
+TU.ExtraArgs.push_back("-xobjective-c++");
+
+auto AST = TU.build();
+auto Results = locateSymbolAt(AST, T.point());
+
+ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
+for (size_t Idx = 0; Idx < Ranges.size(); Idx++) {
+  EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
+  << "($decl" << Idx << ")" << Test;
+  llvm::Optional GotDef;
+  if (Results[Idx].Definition)
+GotDef = Results[Idx].Definition->range;
+  EXPECT_EQ(GotDef, Ranges[Idx].WantDef) << "($def" << Idx << ")" << Test;
+}
+  }
+}
+
+TEST(LocateSymbol, MultipleDeclsWithSameDefinition) {
+  // Ranges in tests:
+  //   $def is the shared definition location
+  //   $declN is one of the declaration locations
+  //
+  // NOTE:
+  //   N starts at 0.
+  const char *Tests[] = {
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @interface $decl1[[Ca^t]] ()
+  - (void)meow;
+  @end
+  @implementation $def[

[PATCH] D83190: [analyzer] Model iterator random incrementation symmetrically

2020-07-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

It would be nice to see the measurements on llvm as this patch introduced some 
(IMO reasonable) asserts. Also in the unlikely case, there is an expression 
like `1 + iter`, there could be more results.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83190



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


[PATCH] D82845: [Analyzer][StreamChecker] Report every leak, clean up state.

2020-07-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 278755.
balazske added a comment.

Checking notes in test `f_leak_2`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82845

Files:
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-note.c

Index: clang/test/Analysis/stream-note.c
===
--- clang/test/Analysis/stream-note.c
+++ clang/test/Analysis/stream-note.c
@@ -46,3 +46,34 @@
 }
 // expected-warning@-1 {{Opened stream never closed. Potential resource leak}}
 // expected-note@-2 {{Opened stream never closed. Potential resource leak}}
+
+void check_note_leak_2(int c) {
+  FILE *F1 = fopen("foo1.c", "r"); // expected-note {{Stream opened here}}
+  if (!F1)
+// expected-note@-1 {{'F1' is non-null}}
+// expected-note@-2 {{Taking false branch}}
+// expected-note@-3 {{'F1' is non-null}}
+// expected-note@-4 {{Taking false branch}}
+return;
+  FILE *F2 = fopen("foo2.c", "r"); // expected-note {{Stream opened here}}
+  if (!F2) {
+// expected-note@-1 {{'F2' is non-null}}
+// expected-note@-2 {{Taking false branch}}
+// expected-note@-3 {{'F2' is non-null}}
+// expected-note@-4 {{Taking false branch}}
+fclose(F1);
+return;
+  }
+  if(c)
+// expected-note@-1 {{Assuming 'c' is not equal to 0}}
+// expected-note@-2 {{Taking true branch}}
+// expected-note@-3 {{Assuming 'c' is not equal to 0}}
+// expected-note@-4 {{Taking true branch}}
+return;
+// expected-warning@-1 {{Opened stream never closed. Potential resource leak}}
+// expected-note@-2 {{Opened stream never closed. Potential resource leak}}
+// expected-warning@-3 {{Opened stream never closed. Potential resource leak}}
+// expected-note@-4 {{Opened stream never closed. Potential resource leak}}
+  fclose(F1);
+  fclose(F2);
+}
Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -337,6 +337,12 @@
   /// to ensure uniform handling.
   void reportFEofWarning(CheckerContext &C, ProgramStateRef State) const;
 
+  /// Emit resource leak warnings for the given symbols.
+  /// Createn a non-fatal error node for these, and returns it (if any warnings
+  /// were generated). Return value is non-null.
+  ExplodedNode *reportLeaks(const SmallVector &LeakedSyms,
+CheckerContext &C, ExplodedNode *Pred) const;
+
   /// Find the description data of the function called by a call event.
   /// Returns nullptr if no function is recognized.
   const FnDescription *lookupFn(const CallEvent &Call) const {
@@ -956,28 +962,19 @@
   C.addTransition(State);
 }
 
-void StreamChecker::checkDeadSymbols(SymbolReaper &SymReaper,
- CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
-
-  // TODO: Clean up the state.
-  const StreamMapTy &Map = State->get();
-  for (const auto &I : Map) {
-SymbolRef Sym = I.first;
-const StreamState &SS = I.second;
-if (!SymReaper.isDead(Sym) || !SS.isOpened())
-  continue;
-
-ExplodedNode *N = C.generateErrorNode();
-if (!N)
-  continue;
+ExplodedNode *
+StreamChecker::reportLeaks(const SmallVector &LeakedSyms,
+   CheckerContext &C, ExplodedNode *Pred) const {
+  // Do not warn for non-closed stream at program exit.
+  // FIXME: Use BugType::SuppressOnSink instead.
+  if (Pred && Pred->getCFGBlock() && Pred->getCFGBlock()->hasNoReturnElement())
+return Pred;
 
-// Do not warn for non-closed stream at program exit.
-ExplodedNode *Pred = C.getPredecessor();
-if (Pred && Pred->getCFGBlock() &&
-Pred->getCFGBlock()->hasNoReturnElement())
-  continue;
+  ExplodedNode *Err = C.generateNonFatalErrorNode(C.getState(), Pred);
+  if (!Err)
+return Pred;
 
+  for (SymbolRef LeakSym : LeakedSyms) {
 // Resource leaks can result in multiple warning that describe the same kind
 // of programming error:
 //  void f() {
@@ -989,8 +986,7 @@
 // from a different kinds of errors), the reduction in redundant reports
 // makes this a worthwhile heuristic.
 // FIXME: Add a checker option to turn this uniqueing feature off.
-
-const ExplodedNode *StreamOpenNode = getAcquisitionSite(N, Sym, C);
+const ExplodedNode *StreamOpenNode = getAcquisitionSite(Err, LeakSym, C);
 assert(StreamOpenNode && "Could not find place of stream opening.");
 PathDiagnosticLocation LocUsedForUniqueing =
 PathDiagnosticLocation::createBegin(
@@ -1000,12 +996,38 @@
 std::unique_ptr R =
 std::make_unique(
 BT_ResourceLeak,
-"Opened stream never closed. Potential resource leak.", N,
+"Opened stream never closed. Potent

[PATCH] D83970: [ASTImporter] Refactor ASTImporter to support custom downstream tests

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

Future improvement: Split `ASTImporterTest.cpp` into smaller parts. It is still 
too large.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83970



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


[PATCH] D84005: Introduce ns_error_domain attribute.

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1860
+def NSErrorDomain : Attr {
+  let Spellings = [GNU<"ns_error_domain">];
+  let Args = [IdentifierArgument<"ErrorDomain">];

gribozavr2 wrote:
> aaron.ballman wrote:
> > MForster wrote:
> > > gribozavr2 wrote:
> > > > Could we try to add a list of subjects here? It seems like it is a 
> > > > type-only attribute, and most likely enum-only.
> > > > 
> > > > let Subjects = SubjectList<[Enum]>;
> > > @milseman, could you comment on this? 
> > > 
> > > In the meantime I've added the restriction. Obviously this makes the 
> > > tests fail. I will also test this change against the Swift unit tests.
> > FWIW, this is not a attribute; it's a declaration attribute.
> > 
> > Is there a reason it's not inheritable?
> > 
> > I assume it's not getting a Clang spelling because Objective-C isn't 
> > tracking C2x yet? (Though that spelling still seems useful to Objective-C++ 
> > users in general for these NS attributes.)
> > FWIW, this is not a attribute; it's a declaration attribute.
> 
> Sorry, yes, of course I meant to say "declaration attribute".
> 
> > Is there a reason it's not inheritable?
> 
> Good observation, I think it should be.
> 
> > I assume it's not getting a Clang spelling because Objective-C isn't 
> > tracking C2x yet?
> 
> Cocoa users are expected to use the `NS_*` macros instead of using the 
> attribute directly, so even if a C2x spelling was an option (IDK if it is), 
> there would be very limited use for it.
> Cocoa users are expected to use the NS_* macros instead of using the 
> attribute directly, so even if a C2x spelling was an option (IDK if it is), 
> there would be very limited use for it.

Okay, that's reasonable, thanks!



Comment at: clang/test/Analysis/ns_error_enum.m:1
+// RUN: %clang_cc1 -verify %s
+

gribozavr2 wrote:
> aaron.ballman wrote:
> > MForster wrote:
> > > gribozavr2 wrote:
> > > > This file is a `.m` -- any specific reason? I'd call it `.c` and run 
> > > > the test in C, Objective-C, and C++ modes (enums might work slightly 
> > > > differently, the name lookup functionality might work differently).
> > > The test doesn't compile in C or C++ (`non-defining declaration of 
> > > enumeration with a fixed underlying type is only permitted as a 
> > > standalone declaration; missing list of enumerators?`). Not sure if it's 
> > > worth adapting.
> > Enums with fixed underlying types exist in C++ and C, so I was expecting 
> > the attribute to work there. If the attribute isn't supported in these 
> > languages, should the attribute be tied to a language mode?
> There are Apple SDK headers that parse in all language modes (C, Objective-C, 
> C++, Objective-C++), so I think it is quite important to test this feature in 
> all modes. I suspect the reason for the error is that different language 
> modes require a slightly different macro definition.
> There are Apple SDK headers that parse in all language modes (C, Objective-C, 
> C++, Objective-C++), so I think it is quite important to test this feature in 
> all modes.

In that case, I definitely agree. This should have multiple RUN lines to test 
the various language modes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84005



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


[PATCH] D83877: [Analyzer] Handle unique_ptr::swap() in SmartPtrModeling

2020-07-17 Thread Nithin VR via Phabricator via cfe-commits
vrnithinkumar updated this revision to Diff 278759.
vrnithinkumar marked 11 inline comments as done.
vrnithinkumar edited the summary of this revision.
vrnithinkumar added a comment.

- Changes from review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83877

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/smart-ptr.cpp

Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -67,14 +67,14 @@
   std::unique_ptr P(new A());
   P.release();
   clang_analyzer_numTimesReached(); // expected-warning {{1}}
-  P->foo(); // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
+  P->foo(); // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
 }
 
 void derefAfterReset() {
   std::unique_ptr P(new A());
   P.reset();
   clang_analyzer_numTimesReached(); // expected-warning {{1}}
-  P->foo(); // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
+  P->foo(); // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
 }
 
 void derefAfterResetWithNull() {
@@ -101,3 +101,30 @@
   A *AP = P.release();
   AP->foo(); // expected-warning {{Called C++ object pointer is null [core.CallAndMessage]}}
 }
+
+void derefOnSwappedNullPtr() {
+  std::unique_ptr P(new A());
+  std::unique_ptr PNull;
+  P.swap(PNull);
+  PNull->foo(); // No warning.
+  (*P).foo();   // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
+}
+
+void derefOnStdSwappedNullPtr() {
+  std::unique_ptr P;
+  std::unique_ptr PNull;
+  std::swap(P, PNull);
+  PNull->foo(); // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
+  P->foo(); // expected-warning {{Dereference of null smart pointer [alpha.cplusplus.SmartPtr]}}
+}
+
+void derefOnSwappedValidPtr() {
+  std::unique_ptr P(new A());
+  std::unique_ptr PValid(new A());
+  P.swap(PValid);
+  (*P).foo();// No warning.
+  PValid->foo(); // No warning.
+  std::swap(P, PValid);
+  P->foo();  // No warning.
+  PValid->foo(); // No warning.
+}
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -960,7 +960,13 @@
 T *operator->() const;
 operator bool() const;
   };
-}
+
+  // TODO :: Once the deleter parameter is added update with additional template parameter.
+  template 
+  void swap(unique_ptr &x, unique_ptr &y) noexcept {
+x.swap(y);
+  }
+  } // namespace std
 #endif
 
 #ifdef TEST_INLINABLE_ALLOCATORS
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -87,6 +87,17 @@
 } // namespace ento
 } // namespace clang
 
+static ProgramStateRef updateSwappedRegion(ProgramStateRef State,
+   const MemRegion *Region,
+   const SVal *RegionInnerPointerVal) {
+  if (RegionInnerPointerVal) {
+State = State->set(Region, *RegionInnerPointerVal);
+  } else {
+State = State->remove(Region);
+  }
+  return State;
+}
+
 bool SmartPtrModeling::isNullAfterMoveMethod(const CallEvent &Call) const {
   // TODO: Update CallDescription to support anonymous calls?
   // TODO: Handle other methods, such as .get() or .release().
@@ -169,7 +180,7 @@
 return;
   auto State = updateTrackedRegion(Call, C, ThisValRegion);
   C.addTransition(State);
-  // TODO: Make sure to ivalidate the the region in the Store if we don't have
+  // TODO: Make sure to ivalidate the region in the Store if we don't have
   // time to model all methods.
 }
 
@@ -197,7 +208,30 @@
 
 void SmartPtrModeling::handleSwap(const CallEvent &Call,
   CheckerContext &C) const {
-  // TODO: Add support to handle swap method.
+  // To model unique_ptr::swap() method.
+  const auto *IC = dyn_cast(&Call);
+  if (!IC)
+return;
+
+  const MemRegion *ThisRegion = IC->getCXXThisVal().getAsRegion();
+  if (!ThisRegion)
+return;
+
+  const auto *ArgRegion = Call.getArgSVal(0).getAsRegion();
+  if (!ArgRegion)
+return;
+
+  auto State = C.getState();
+  const auto *ThisRegionInnerPointerVal =
+  State->get(ThisRegion);
+  const auto *ArgRegionInnerPointerVal =
+  State->get(ArgRegion);
+
+  // Swap the tracked region values.
+  State = updateSwappedRegion(State, ThisRegion, ArgRe

[PATCH] D83877: [Analyzer] Handle unique_ptr::swap() in SmartPtrModeling

2020-07-17 Thread Nithin VR via Phabricator via cfe-commits
vrnithinkumar added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:198
 
 void SmartPtrModeling::handleSwap(const CallEvent &Call,
   CheckerContext &C) const {

vsavchenko wrote:
> I think it would be good to add some comments in the body of the function to 
> be more explicit about the situation you are handling.
Added comments



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:224-228
+  if (ThisRegionInnerPointerVal) {
+State = State->set(ArgRegion, 
*ThisRegionInnerPointerVal);
+  } else {
+State = State->remove(ArgRegion);
+  }

vsavchenko wrote:
> These two if's are clearly duplicates and it seems like a good candidate for 
> a separate function.
Thanks!
created a separate function `updateSwappedRegion()`



Comment at: clang/test/Analysis/Inputs/system-header-simulator-cxx.h:964-965
+
+  template 
+  void swap(unique_ptr &x, unique_ptr &y) noexcept {
+x.swap(y);

xazax.hun wrote:
> NoQ wrote:
> > You seem to be relying on the fact that global `std::swap` is implemented 
> > in terms of the member `std::swap`. That's an implementation detail of the 
> > standard library; i'm not sure that this is always the case. Ideally we 
> > should model the global `std::swap` separately.
> I am not sure how reliable cppreference is, but I think this overload might 
> actually be guaranteed by the standard: 
> https://en.cppreference.com/w/cpp/memory/unique_ptr/swap2
I also made the assumption based on this 
(https://en.cppreference.com/w/cpp/memory/unique_ptr/swap2).




Comment at: clang/test/Analysis/Inputs/system-header-simulator-cxx.h:965
+  template 
+  void swap(unique_ptr &x, unique_ptr &y) noexcept {
+x.swap(y);

xazax.hun wrote:
> Maybe it is worth to add a TODO to introduce an additional template parameter 
> once the deleter is added above.
> 
> https://en.cppreference.com/w/cpp/memory/unique_ptr/swap2
Added the TODO



Comment at: clang/test/Analysis/smart-ptr.cpp:124
+
+void derefOnStdSwappedNullPtr() {
+  std::unique_ptr P(new A());

vsavchenko wrote:
> xazax.hun wrote:
> > This test case is very similar to the first one. Maybe you could move them 
> > closer. And you could make both pointers invalid to make them more distinct.
> +1
Moved and made both pointers invalid in the test



Comment at: clang/test/Analysis/smart-ptr.cpp:131
+}
\ No newline at end of file


vrnithinkumar wrote:
> I will fix this.
Fixed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83877



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


[PATCH] D84009: [Syntax] expose API for expansions overlapping a spelled token range.

2020-07-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, LGTM! (and loved the choice of `overlapping`)




Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:431
+std::vector
+TokenBuffer::expansionsAffecting(llvm::ArrayRef Spelled) const {
+  if (Spelled.empty())

sammccall wrote:
> kadircet wrote:
> > this might be inconistent with spelledForExpanded from time to time, e.g:
> > 
> > ```
> > #define FOO(X) 123
> > #define BAR
> > 
> > void foo() {
> >   FOO(BA^R);
> > }
> > ```
> > 
> > normally BAR has no expansions, but I think it will get merged into outer 
> > macro expansion e.g. `123` coming from `FOO(BAR)`. (whereas 
> > spelledForExpanded will treat `BAR` in isolation)
> > 
> > not sure an important limitation but something to keep in mind.
> I don't understand the consistency you're looking for - AFAICS these are 
> different functions that do different things - spelledForExpanded is much 
> higher level.
> 
> Is there something in the name or comment I can add/remove to clarify?
> 
> > normally BAR has no expansions
> 
> Tokens don't really "have expansions" - they're *part of* expansions. 
> Generally expansionsOverlapping() will return the expansions themselves that 
> are overlapping, while spelledForExpanded will include the expanded tokens if 
> the whole expansion is in-range.
> 
> The former is a building-block (returning Expansions seems like a clear 
> indicator of that) that will usually require some postfiltering, while the 
> latter is fairly directly usable.
> Tokens don't really "have expansions" - they're *part of* expansions. 
> Generally expansionsOverlapping() will return the expansions themselves that 
> are overlapping, while spelledForExpanded will include the expanded tokens if 
> the whole expansion is in-range.

yeah `expansionsOverlapping() will return the expansions themselves that are 
overlapping` bit made my reasoning a little more solid, i am still thinking 
with the `spelled tokens might expand mindset` but I suppose `spelled tokens 
might be part of expansions` is a better reasoning.

I don't think any extra comments are necessary, at least in this layer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84009



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


[PATCH] D83551: [PATCH 2/4][Sema][AArch64] Add semantics for arm_sve_vector_bits attribute

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1541
 
+def ArmSveVectorBits128 : TypeAttr {
+  let Spellings = [];

c-rhodes wrote:
> aaron.ballman wrote:
> > c-rhodes wrote:
> > > c-rhodes wrote:
> > > > aaron.ballman wrote:
> > > > > aaron.ballman wrote:
> > > > > > c-rhodes wrote:
> > > > > > > sdesmalen wrote:
> > > > > > > > aaron.ballman wrote:
> > > > > > > > > sdesmalen wrote:
> > > > > > > > > > nit: Can you add a comment saying why these are 
> > > > > > > > > > undocumented (and have no spellings)
> > > > > > > > > Also, I think these are all missing `let SemaHandler = 0;` 
> > > > > > > > > and `let ASTNode = 0;`
> > > > > > > > > 
> > > > > > > > > Is there a reason why we need N different type attributes 
> > > > > > > > > instead of having a single type attribute which encodes the N 
> > > > > > > > > as an argument? I think this may simplify the patch somewhat 
> > > > > > > > > as you no longer need to switch over N as much.
> > > > > > > > > Is there a reason why we need N different type attributes 
> > > > > > > > > instead of having a single type attribute which encodes the N 
> > > > > > > > > as an argument?
> > > > > > > > AIUI this was a workaround for getting the value of N from an 
> > > > > > > > AttributedType, because this only has `getAttrKind` to return 
> > > > > > > > the attribute kind, but no way to get the corresponding 
> > > > > > > > argument/value. This seemed like a simple way to do that 
> > > > > > > > without having to create a new subclass for Type and having to 
> > > > > > > > support that in various places. Is the latter the approach you 
> > > > > > > > were thinking of? (or is there perhaps a simpler way?)
> > > > > > > > Also, I think these are all missing let SemaHandler = 0; and 
> > > > > > > > let ASTNode = 0;
> > > > > > > 
> > > > > > > Good to know. In SemaType I'm doing `CurType = 
> > > > > > > State.getAttributedType(A, CurType, CurType);` which gives an 
> > > > > > > `AttributedType` in the AST, should I still set `let ASTNode = 
> > > > > > > 0;` in this case?
> > > > > > > 
> > > > > > > > Is there a reason why we need N different type attributes 
> > > > > > > > instead of having a single type attribute which encodes the N 
> > > > > > > > as an argument?
> > > > > > > 
> > > > > > > As Sander mentioned, it seemed like the easiest solution, 
> > > > > > > interested to know if there's a better approach however
> > > > > > I was thinking specifically of creating a new `Type` subclass and 
> > > > > > supporting it rather than adding 5 new attributes that only vary by 
> > > > > > a bit-width (which means there's likely to be a 6th someday). It's 
> > > > > > not immediately clear to me whether that's a really big ask for 
> > > > > > little gain or not, though.
> > > > > Ah, you're right, we may still need `ASTNode` to be kept around for 
> > > > > that, good call.
> > > > > Also, I think these are all missing let SemaHandler = 0; and let 
> > > > > ASTNode = 0;
> > > > 
> > > > I've added `let SemaHandler = 0;` for the internal types and `let 
> > > > ASTNode = 0;` for the user-facing attr.
> > > > I was thinking specifically of creating a new Type subclass and 
> > > > supporting it rather than adding 5 new attributes that only vary by a 
> > > > bit-width (which means there's likely to be a 6th someday).
> > > 
> > > It would be nice if the `Attr` was accessible from the `AttributedType`, 
> > > similar to how it is for `Decl`s, so something like:
> > > ```  if (const auto *AT = T->getAs())
> > > if (ArmSveVectorBitsAttr *Attr = AT->getAttr())
> > >   unsigned Width = Attr->getNumBits();```
> > > Although I'm not sure if that makes sense or how easy it is. I do agree 
> > > adding 5 new attributes isn't ideal but for an initial implementation 
> > > it's nice and simple. Would you be ok with us addressing this in a later 
> > > patch?
> > > It would be nice if the Attr was accessible from the AttributedType, 
> > > similar to how it is for Decls, so something like:
> > 
> > You can do that through an `AttributedTypeLoc` object, which I think should 
> > be available from the situations you need to check this through a 
> > `TypeSourceInfo *` for the type. Then you can use 
> > `AttributedTypeLoc::getAttr()` to get the semantic attribute.
> > 
> > > Would you be ok with us addressing this in a later patch?
> > 
> > No and yes. It's a novel design to have a user-facing attribute that is 
> > never hooked up in the AST but is instead used to decide which spellingless 
> > attribute to use instead, so I'd strongly prefer to find a solution that 
> > doesn't use this approach. I also think we'll wind up with cleaner code 
> > from this. That said, if it turns out to be awkward to do because there's 
> > too much code required to support it, then I can likely hold my nose.
> > You can do that through an AttributedTypeLoc object, which I think should 
> > be available 

[PATCH] D83174: Teach AttachPreviousImpl to inherit MSInheritanceAttr attribute

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: aaron.ballman, riccibruno, martong.
aaron.ballman added a comment.
Herald added a subscriber: rnkovacs.

In D83174#2156454 , @v.g.vassilev 
wrote:

> >> Also, I would like to add that the current test present in this diff does 
> >> not fail in the existing system but it was the best I and Vassil could 
> >> come up with to replicate our problem.
> > 
> > Is there a way to run something like creduce to come up with a test case 
> > that does replicate the issue? I'd like to ensure we have a test case that 
> > fails without the patch applied so that we can be sure we don't regress the 
> > behavior.
>
> Not easily. That bug comes from internal infrastructure which uses clang's 
> API and happens when calling directly the mangler. Running creduce would 
> require failure to be reproducible with bare clang. I was hoping @rsmith had 
> something up his sleeve.


Drat. While the code looks reasonable, this makes me less confident in the fix. 
I'm adding some more reviewers who have touched the AST serialization and 
modules before in case they also have ideas for test cases.


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

https://reviews.llvm.org/D83174



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


[PATCH] D83901: [clang] Disable a few formatting options for test/

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added reviewers: rsmith, dblaikie.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

I think this is a good improvement, but you should wait for a few days in case 
other reviewers have feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83901



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


[PATCH] D83061: [OpenMP] Implement TR8 `present` map type modifier in Clang (1/2)

2020-07-17 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:1252-1253
+  "incorrect map type modifier, expected 'always', 'close', 'mapper', or 
'present'">;
+def err_omp_map_type_modifier_wrong_version : Error<
+  "map type modifier '%0' requires OpenMP version %1 or above">;
 def err_omp_map_type_missing : Error<

Better to keep original message for <= 5.0. This is what we usually do



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:7043-7044
 OMP_MAP_CLOSE = 0x400,
+/// Produce a runtime error if the data is not already allocated.
+OMP_MAP_PRESENT = 0x800,
 /// The 16 MSBs of the flags indicate whether the entry is member of some

jdenny wrote:
> ABataev wrote:
> > Better to use thу next value to avoid compatibility issues with XLC. 
> You mean 0x1000?
Yes


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

https://reviews.llvm.org/D83061



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


[PATCH] D83680: [clang-tidy] Refactor IncludeInserter

2020-07-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp:55
 IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) {
+  assert(SourceMgr && "SourceMgr shouldn't be null");
   // std::unique_ptr is cheap to construct, so force a construction now to save

I think it might be useful to add something like `; did you remember to call 
registerPreprocessor()?` to the assertion message, as that seems like it would 
be the most likely issue if `SourceMgr` was null.



Comment at: clang-tools-extra/clang-tidy/utils/IncludeInserter.h:59
+  /// Initializes the IncludeInserter using the IncludeStyle \p Style.
+  /// In most cases the \p Style will be retrived from the ClangTidyOptios 
using
+  /// \code

retrived -> retrieved
ClangTidyOptios -> ClangTidyOptions 



Comment at: clang-tools-extra/clang-tidy/utils/IncludeInserter.h:70
+  /// Creates a \p Header inclusion directive fixit in the File \p FileID.
+  /// Returns ``llvm::None`` on error or if inclusion directive already exists.
+  llvm::Optional

or if inclusion -> or if the inclusion



Comment at: clang-tools-extra/clang-tidy/utils/IncludeInserter.h:75
+  /// Creates a \p Header inclusion directive fixit in the main file.
+  /// Returns``llvm::None`` on error or if inclusion directive already exists.
   llvm::Optional

or if inclusion -> or if the inclusion



Comment at: clang-tools-extra/clang-tidy/utils/IncludeInserter.h:89
+  llvm::DenseMap> InsertedHeaders;
+  const SourceManager *SourceMgr;
   const IncludeSorter::IncludeStyle Style;

In-class initialize this to nullptr instead of leaving it indeterminate?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83680



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


[PATCH] D83922: [OpenMP] Fix map clause for unused var: don't ignore it

2020-07-17 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:9470-9471
+  MappedVarSet.insert(CI->getCapturedVar()->getCanonicalDecl());
+else
+  MappedVarSet.insert(nullptr);
 if (CurBasePointers.empty())

jdenny wrote:
> ABataev wrote:
> > jdenny wrote:
> > > ABataev wrote:
> > > > No need to insert `nullptr` here, it is not used later.
> > > Without this `nulltpr` insertion, many tests fail because of duplicate 
> > > map entries.  Independently of my patch, `nulltptr` is used to indicate 
> > > `this` capture (see the `generateInfoForCapture` implementation) .
> > > 
> > > For example:
> > > 
> > > ```
> > > struct S {
> > >   int i;
> > >   void foo() {
> > > #pragma omp target map(i)
> > > i = 5;
> > >   }
> > > };
> > > ```
> > > 
> > > We should have:
> > > 
> > > ```
> > > @.offload_maptypes = private unnamed_addr constant [2 x i64] [i64 32, i64 
> > > 281474976710659]
> > > ```
> > > 
> > > Without the `nullptr` insertion, we have:
> > > 
> > > ```
> > > @.offload_maptypes = private unnamed_addr constant [4 x i64] [i64 32, i64 
> > > 281474976710659, i64 32, i64 844424930131971]
> > > ```
> > This is strange, because you don't check for `nullptr`. You only check for 
> > `ValueDecl`s, but not capture of `this`.
> I'm not sure what code you're referring to when you say "you check".
> 
> Both with and without my patch, my understanding is that `nullptr` is a 
> special key that means `this`.  I'm depending on that to avoid generating map 
> entries twice for `this`.
> 
> My understanding is based on the way `generateInfoForCapture` works.  If 
> `Cap->capturesThis()`, then `VD = nullptr`.  That `VD` is then used by 
> `C->decl_component_lists(VD)` to find entries for `this` in map clauses.
> 
> Unless I'm misreading it, the code that sets `nullptr` for `this` in decl 
> components is `checkMappableExpressionList` in SemaOpenMP.cpp.  The last few 
> lines of that function have a comment to this effect.  (That comment would 
> probably be more useful in a header file somewhere.)
`MappedVarSet` is a new variable, right? It is used only in 2 places: here, 
where you add elements to this set, and in `generateAllInfo` where you have a 
check:
```
if (SkipVarSet.count(VD))
return;
```
I don't see other places where it is used. And I don't see places where you 
check for the presence of `nullptr` in this set. That's why I think you don't 
need to add it, if you don't check for its presence later.


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

https://reviews.llvm.org/D83922



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


[PATCH] D72932: [ARM] Follow AACPS standard for volatile bit-fields access width

2020-07-17 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio marked 6 inline comments as done.
dnsampaio added a comment.

Indeed not all of them. Fixed this time.




Comment at: clang/include/clang/Basic/CodeGenOptions.def:396
+/// according to the field declaring type width.
+CODEGENOPT(ForceNoAAPCSBitfieldWidth, 1, 0)
+

ostannard wrote:
> Why is this a negative option, when the one above is positive?
The enforcing of number of accesses would not be accepted if it was not an 
opt-in option. This one I expect it should be accepted with a single opt-out 
option.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72932



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


[PATCH] D84029: [clang][Driver] Default to /usr/bin/ld on Solaris

2020-07-17 Thread Rainer Orth via Phabricator via cfe-commits
ro created this revision.
ro added reviewers: clang, rsmith, mehdi_amini, rnk.
ro added a project: clang.
Herald added a subscriber: fedor.sergeev.

`clang` currently requires the native linker on Solaris:

  - It passes `-C` to `ld` which GNU `ld` doesn't understand.
- To use `gld`, one needs to pass the correct `-m EMU` option to select the 
right emulation. Solaris `ld` cannot handle that option.

So far I've worked around this by passing `-DCLANG_DEFAULT_LINKER=/usr/bin/ld`
to `cmake`. However, if someone forgets this, it depends on the user's `PATH` 
whether
or not `clang` finds the correct linker, which doesn't make for a good user 
experience.

While it would be nice to detect the linker flavor at runtime, this is more 
involved.
Instead, this patch defaults to `/usr/bin/ld` on Solaris.  This doesn't work on 
its own, 
however: a link fails with

  clang-12: error: unable to execute command: Executable 
"x86_64-pc-solaris2.11-/usr/bin/ld" doesn't exist!

I avoid this by leaving absolute paths alone in `ToolChain::GetLinkerPath`.

Tested on `amd64-pc-solaris2.11`.

Ok for master?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84029

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Solaris.h


Index: clang/lib/Driver/ToolChains/Solaris.h
===
--- clang/lib/Driver/ToolChains/Solaris.h
+++ clang/lib/Driver/ToolChains/Solaris.h
@@ -65,6 +65,11 @@
   SanitizerMask getSupportedSanitizers() const override;
   unsigned GetDefaultDwarfVersion() const override { return 2; }
 
+  const char *getDefaultLinker() const override {
+// clang currently uses Solaris ld-only options.
+return "/usr/bin/ld";
+  }
+
 protected:
   Tool *buildAssembler() const override;
   Tool *buildLinker() const override;
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -558,7 +558,11 @@
   } else if (UseLinker.empty() || UseLinker == "ld") {
 // If we're passed -fuse-ld= with no argument, or with the argument ld,
 // then use whatever the default system linker is.
-return GetProgramPath(getDefaultLinker());
+const char *DefaultLinker = getDefaultLinker();
+if (llvm::sys::path::is_absolute(DefaultLinker))
+  return DefaultLinker;
+else
+  return GetProgramPath(DefaultLinker);
   } else {
 llvm::SmallString<8> LinkerName;
 if (Triple.isOSDarwin())


Index: clang/lib/Driver/ToolChains/Solaris.h
===
--- clang/lib/Driver/ToolChains/Solaris.h
+++ clang/lib/Driver/ToolChains/Solaris.h
@@ -65,6 +65,11 @@
   SanitizerMask getSupportedSanitizers() const override;
   unsigned GetDefaultDwarfVersion() const override { return 2; }
 
+  const char *getDefaultLinker() const override {
+// clang currently uses Solaris ld-only options.
+return "/usr/bin/ld";
+  }
+
 protected:
   Tool *buildAssembler() const override;
   Tool *buildLinker() const override;
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -558,7 +558,11 @@
   } else if (UseLinker.empty() || UseLinker == "ld") {
 // If we're passed -fuse-ld= with no argument, or with the argument ld,
 // then use whatever the default system linker is.
-return GetProgramPath(getDefaultLinker());
+const char *DefaultLinker = getDefaultLinker();
+if (llvm::sys::path::is_absolute(DefaultLinker))
+  return DefaultLinker;
+else
+  return GetProgramPath(DefaultLinker);
   } else {
 llvm::SmallString<8> LinkerName;
 if (Triple.isOSDarwin())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83822: [clangd] Support config over LSP.

2020-07-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:1220
   CDB->setCompileCommand(File, std::move(New));
   ModifiedFiles.insert(File);
 }

sammccall wrote:
> kadircet wrote:
> > nit: maybe just set `ReparseAllFiles` in here too, and change the condition 
> > below to only `return ReparseAllFiles`
> Is the idea here that triggering spurious reparses is cheap enough?
> Or that if it's cheap enough for our "future-facing" extension, we should be 
> able to stop optimizing it for the existing one?
none :( sorry i misread this and thought the code below was doing 
`ModifiedFiles.size() != 0` (that's way the comment was a nit)

OTOH, as you noted spurious reparses are cheap(still some IO and a task in the 
queue). We expect the usage of updating compile commands to migrate towards 
configs in the future, so in theory we won't be using that optimization most of 
the time.

Even though we've got enough info to prevent spurious reparses here, we might 
not in the future (e.g. reparses resulting from a config change). So I would 
drop the optimization(the whole Old-New comparison logic) to increase 
readability.

but definitely not something we should do now (probably ever), so feel free to 
ignore.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83822



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


[PATCH] D83922: [OpenMP] Fix map clause for unused var: don't ignore it

2020-07-17 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny marked an inline comment as done.
jdenny added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:9470-9471
+  MappedVarSet.insert(CI->getCapturedVar()->getCanonicalDecl());
+else
+  MappedVarSet.insert(nullptr);
 if (CurBasePointers.empty())

ABataev wrote:
> jdenny wrote:
> > ABataev wrote:
> > > jdenny wrote:
> > > > ABataev wrote:
> > > > > No need to insert `nullptr` here, it is not used later.
> > > > Without this `nulltpr` insertion, many tests fail because of duplicate 
> > > > map entries.  Independently of my patch, `nulltptr` is used to indicate 
> > > > `this` capture (see the `generateInfoForCapture` implementation) .
> > > > 
> > > > For example:
> > > > 
> > > > ```
> > > > struct S {
> > > >   int i;
> > > >   void foo() {
> > > > #pragma omp target map(i)
> > > > i = 5;
> > > >   }
> > > > };
> > > > ```
> > > > 
> > > > We should have:
> > > > 
> > > > ```
> > > > @.offload_maptypes = private unnamed_addr constant [2 x i64] [i64 32, 
> > > > i64 281474976710659]
> > > > ```
> > > > 
> > > > Without the `nullptr` insertion, we have:
> > > > 
> > > > ```
> > > > @.offload_maptypes = private unnamed_addr constant [4 x i64] [i64 32, 
> > > > i64 281474976710659, i64 32, i64 844424930131971]
> > > > ```
> > > This is strange, because you don't check for `nullptr`. You only check 
> > > for `ValueDecl`s, but not capture of `this`.
> > I'm not sure what code you're referring to when you say "you check".
> > 
> > Both with and without my patch, my understanding is that `nullptr` is a 
> > special key that means `this`.  I'm depending on that to avoid generating 
> > map entries twice for `this`.
> > 
> > My understanding is based on the way `generateInfoForCapture` works.  If 
> > `Cap->capturesThis()`, then `VD = nullptr`.  That `VD` is then used by 
> > `C->decl_component_lists(VD)` to find entries for `this` in map clauses.
> > 
> > Unless I'm misreading it, the code that sets `nullptr` for `this` in decl 
> > components is `checkMappableExpressionList` in SemaOpenMP.cpp.  The last 
> > few lines of that function have a comment to this effect.  (That comment 
> > would probably be more useful in a header file somewhere.)
> `MappedVarSet` is a new variable, right? It is used only in 2 places: here, 
> where you add elements to this set, and in `generateAllInfo` where you have a 
> check:
> ```
> if (SkipVarSet.count(VD))
> return;
> ```
> I don't see other places where it is used. And I don't see places where you 
> check for the presence of `nullptr` in this set. That's why I think you don't 
> need to add it, if you don't check for its presence later.
> MappedVarSet is a new variable, right?

Right.

> It is used only in 2 places: here, where you add elements to this set, and in 
> generateAllInfo where you have a check:
> 
> ```
> if (SkipVarSet.count(VD))
> return;
> ```
> I don't see other places where it is used.

That's all.

> And I don't see places where you check for the presence of nullptr in this 
> set. That's why I think you don't need to add it, if you don't check for its 
> presence later.

The `SkipVarSet.count(VD)` you mentioned checks for presence of any key in 
order to avoid creating duplicate map entries.  `nullptr` is one such key.  It 
happens to indicate `this`.

For comparison, look inside `generateInfoForCapture` where the following code 
establishes that `nullptr` is the key for `this`:

```
const ValueDecl *VD = Cap->capturesThis()
  ? nullptr
  : Cap->getCapturedVar()->getCanonicalDecl();
```

After that, does `generateInfoForCapture` ever check for `VD == nullptr`?  I 
don't see where it does.  But it does use `VD`, which might be `nulltpr`, as a 
decl components key in the following code:

```
  for (const auto L : C->decl_component_lists(VD)) {
```

Likewise, my code is also using a `VD` that might be `nullptr` as a key in 
`SkipVarSet`.  I don't have to special case `nullptr` at this point.  It's just 
another key.


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

https://reviews.llvm.org/D83922



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


[PATCH] D83061: [OpenMP] Implement TR8 `present` map type modifier in Clang (1/2)

2020-07-17 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:1252-1253
+  "incorrect map type modifier, expected 'always', 'close', 'mapper', or 
'present'">;
+def err_omp_map_type_modifier_wrong_version : Error<
+  "map type modifier '%0' requires OpenMP version %1 or above">;
 def err_omp_map_type_missing : Error<

ABataev wrote:
> Better to keep original message for <= 5.0. This is what we usually do
What message do you mean?  Which `err_` diag id?


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

https://reviews.llvm.org/D83061



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


[PATCH] D83061: [OpenMP] Implement TR8 `present` map type modifier in Clang (1/2)

2020-07-17 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:1252-1253
+  "incorrect map type modifier, expected 'always', 'close', 'mapper', or 
'present'">;
+def err_omp_map_type_modifier_wrong_version : Error<
+  "map type modifier '%0' requires OpenMP version %1 or above">;
 def err_omp_map_type_missing : Error<

jdenny wrote:
> ABataev wrote:
> > Better to keep original message for <= 5.0. This is what we usually do
> What message do you mean?  Which `err_` diag id?
For <= 5.0 the error message should be the same.
```
def err_omp_unknown_map_type_modifier : Error<
  "incorrect map type modifier, expected 'always', 'close', %select{or 
'mapper'|'mapper', or 'presence'}0">;
```
In code:
```
Diag(..., diags::err_omp_unknown_map_type_modifier) << (LangOpts.OpenMP <= 50 ? 
0 : 1);
```


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

https://reviews.llvm.org/D83061



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


[PATCH] D83974: [AIX] report_fatal_error on `-fregister_global_dtors_with_atexit` for static init

2020-07-17 Thread Xiangling Liao via Phabricator via cfe-commits
Xiangling_L updated this revision to Diff 278777.
Xiangling_L marked 2 inline comments as done.
Xiangling_L added a comment.

Adjust the quesry;


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

https://reviews.llvm.org/D83974

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenCXX/aix-sinit-register-global-dtors-with-atexit.cpp
  clang/test/Driver/cxa-atexit.cpp


Index: clang/test/Driver/cxa-atexit.cpp
===
--- clang/test/Driver/cxa-atexit.cpp
+++ clang/test/Driver/cxa-atexit.cpp
@@ -36,6 +36,7 @@
 // RUN: FileCheck --check-prefix=WITHATEXIT %s
 // RUN: %clang -target x86_64-apple-darwin -c -mkernel -### %s 2>&1 | \
 // RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+
 // RUN: %clang -target x86_64-pc-linux-gnu -fregister-global-dtors-with-atexit 
-fno-register-global-dtors-with-atexit -c -### %s 2>&1 | \
 // RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
 // RUN: %clang -target x86_64-pc-linux-gnu 
-fno-register-global-dtors-with-atexit -fregister-global-dtors-with-atexit -c 
-### %s 2>&1 | \
@@ -43,5 +44,18 @@
 // RUN: %clang -target x86_64-pc-linux-gnu -c -### %s 2>&1 | \
 // RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
 
+// RUN: %clang -target powerpc-ibm-aix-xcoff 
-fregister-global-dtors-with-atexit -fno-register-global-dtors-with-atexit -c 
-### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+// RUN: %clang -target powerpc-ibm-aix-xcoff 
-fno-register-global-dtors-with-atexit -fregister-global-dtors-with-atexit -c 
-### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHATEXIT %s
+// RUN: %clang -target powerpc-ibm-aix-xcoff -c -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+// RUN: %clang -target powerpc64-ibm-aix-xcoff 
-fregister-global-dtors-with-atexit -fno-register-global-dtors-with-atexit -c 
-### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+// RUN: %clang -target powerpc64-ibm-aix-xcoff 
-fno-register-global-dtors-with-atexit -fregister-global-dtors-with-atexit -c 
-### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHATEXIT %s
+// RUN: %clang -target powerpc64-ibm-aix-xcoff -c -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+
 // WITHATEXIT: -fregister-global-dtors-with-atexit
 // WITHOUTATEXIT-NOT: -fregister-global-dtors-with-atexit
Index: clang/test/CodeGenCXX/aix-sinit-register-global-dtors-with-atexit.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/aix-sinit-register-global-dtors-with-atexit.cpp
@@ -0,0 +1,14 @@
+// RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -S -emit-llvm -x c++ \
+// RUN: -fregister-global-dtors-with-atexit < %s 2>&1 | \
+// RUN:   FileCheck %s
+
+// RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -S -emit-llvm -x c++ \
+// RUN: -fregister-global-dtors-with-atexit < %s 2>&1 | \
+// RUN:   FileCheck %s
+
+struct T {
+  T();
+  ~T();
+} t;
+
+// CHECK: error in backend: register global dtors with atexit() is not 
supported yet
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1209,6 +1209,9 @@
 /// when the module is unloaded.
 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
+if (getCXXABI().useSinitAndSterm())
+  llvm::report_fatal_error(
+  "register global dtors with atexit() is not supported yet");
 DtorsUsingAtExit[Priority].push_back(Dtor);
 return;
   }


Index: clang/test/Driver/cxa-atexit.cpp
===
--- clang/test/Driver/cxa-atexit.cpp
+++ clang/test/Driver/cxa-atexit.cpp
@@ -36,6 +36,7 @@
 // RUN: FileCheck --check-prefix=WITHATEXIT %s
 // RUN: %clang -target x86_64-apple-darwin -c -mkernel -### %s 2>&1 | \
 // RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+
 // RUN: %clang -target x86_64-pc-linux-gnu -fregister-global-dtors-with-atexit -fno-register-global-dtors-with-atexit -c -### %s 2>&1 | \
 // RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
 // RUN: %clang -target x86_64-pc-linux-gnu -fno-register-global-dtors-with-atexit -fregister-global-dtors-with-atexit -c -### %s 2>&1 | \
@@ -43,5 +44,18 @@
 // RUN: %clang -target x86_64-pc-linux-gnu -c -### %s 2>&1 | \
 // RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
 
+// RUN: %clang -target powerpc-ibm-aix-xcoff -fregister-global-dtors-with-atexit -fno-register-global-dtors-with-atexit -c -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+// RUN: %clang -target powerpc-ibm-aix-xcoff -fno-register-global-dtors-with-atexit -fregister-global-dtors-with-atexit -c -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHATEXIT %s
+// RUN: %clang -target powerpc-ibm-aix-xcoff -c -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=WITHOUTATEXIT %s
+/

[PATCH] D84032: [clang] Make clear Sema::CheckForConstantInitializer is for C-only codepath.

2020-07-17 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added reviewers: sammccall, efriedma.
Herald added a project: clang.

- add an assertion;
- remove the changes introduced in 
https://github.com/llvm/llvm-project/commit/4a962f03bebef9e3c7d501580357a303638b2700,
 looks like clang can handle that well at the moment, the diagnostic seems 
better;


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84032

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaCXX/compound-literal.cpp


Index: clang/test/SemaCXX/compound-literal.cpp
===
--- clang/test/SemaCXX/compound-literal.cpp
+++ clang/test/SemaCXX/compound-literal.cpp
@@ -89,9 +89,7 @@
   }
 }
 
-// This doesn't necessarily need to be an error, but CodeGen can't handle it
-// at the moment.
-int PR17415 = (int){PR17415}; // expected-error {{initializer element is not a 
compile-time constant}}
+int PR17415 = (int){PR17415}; // expected-warning {{variable 'PR17415' is 
uninitialized when used within its own initialization}}
 
 // Make sure we accept this.  (Not sure if we actually should... but we do
 // at the moment.)
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -6816,12 +6816,9 @@
 
   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
   VK, LiteralExpr, isFileScope);
-  if (isFileScope) {
-if (!LiteralExpr->isTypeDependent() &&
-!LiteralExpr->isValueDependent() &&
-!literalType->isDependentType()) // C99 6.5.2.5p3
-  if (CheckForConstantInitializer(LiteralExpr, literalType))
-return ExprError();
+  if (isFileScope && !getLangOpts().CPlusPlus) { // C99 6.5.2.5p3
+if (CheckForConstantInitializer(LiteralExpr, literalType))
+  return ExprError();
   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  literalType.getAddressSpace() != LangAS::Default) {
 // Embedded-C extensions to C99 6.5.2.5:
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -11069,6 +11069,7 @@
   // "may accept other forms of constant expressions" exception.
   // (We never end up here for C++, so the constant expression
   // rules there don't matter.)
+  assert(!getLangOpts().CPlusPlus || getLangOpts().OpenCLCPlusPlus);
   const Expr *Culprit;
   if (Init->isConstantInitializer(Context, false, &Culprit))
 return false;


Index: clang/test/SemaCXX/compound-literal.cpp
===
--- clang/test/SemaCXX/compound-literal.cpp
+++ clang/test/SemaCXX/compound-literal.cpp
@@ -89,9 +89,7 @@
   }
 }
 
-// This doesn't necessarily need to be an error, but CodeGen can't handle it
-// at the moment.
-int PR17415 = (int){PR17415}; // expected-error {{initializer element is not a compile-time constant}}
+int PR17415 = (int){PR17415}; // expected-warning {{variable 'PR17415' is uninitialized when used within its own initialization}}
 
 // Make sure we accept this.  (Not sure if we actually should... but we do
 // at the moment.)
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -6816,12 +6816,9 @@
 
   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
   VK, LiteralExpr, isFileScope);
-  if (isFileScope) {
-if (!LiteralExpr->isTypeDependent() &&
-!LiteralExpr->isValueDependent() &&
-!literalType->isDependentType()) // C99 6.5.2.5p3
-  if (CheckForConstantInitializer(LiteralExpr, literalType))
-return ExprError();
+  if (isFileScope && !getLangOpts().CPlusPlus) { // C99 6.5.2.5p3
+if (CheckForConstantInitializer(LiteralExpr, literalType))
+  return ExprError();
   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  literalType.getAddressSpace() != LangAS::Default) {
 // Embedded-C extensions to C99 6.5.2.5:
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -11069,6 +11069,7 @@
   // "may accept other forms of constant expressions" exception.
   // (We never end up here for C++, so the constant expression
   // rules there don't matter.)
+  assert(!getLangOpts().CPlusPlus || getLangOpts().OpenCLCPlusPlus);
   const Expr *Culprit;
   if (Init->isConstantInitializer(Context, false, &Culprit))
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83922: [OpenMP] Fix map clause for unused var: don't ignore it

2020-07-17 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG




Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:9470-9471
+  MappedVarSet.insert(CI->getCapturedVar()->getCanonicalDecl());
+else
+  MappedVarSet.insert(nullptr);
 if (CurBasePointers.empty())

jdenny wrote:
> ABataev wrote:
> > jdenny wrote:
> > > ABataev wrote:
> > > > jdenny wrote:
> > > > > ABataev wrote:
> > > > > > No need to insert `nullptr` here, it is not used later.
> > > > > Without this `nulltpr` insertion, many tests fail because of 
> > > > > duplicate map entries.  Independently of my patch, `nulltptr` is used 
> > > > > to indicate `this` capture (see the `generateInfoForCapture` 
> > > > > implementation) .
> > > > > 
> > > > > For example:
> > > > > 
> > > > > ```
> > > > > struct S {
> > > > >   int i;
> > > > >   void foo() {
> > > > > #pragma omp target map(i)
> > > > > i = 5;
> > > > >   }
> > > > > };
> > > > > ```
> > > > > 
> > > > > We should have:
> > > > > 
> > > > > ```
> > > > > @.offload_maptypes = private unnamed_addr constant [2 x i64] [i64 32, 
> > > > > i64 281474976710659]
> > > > > ```
> > > > > 
> > > > > Without the `nullptr` insertion, we have:
> > > > > 
> > > > > ```
> > > > > @.offload_maptypes = private unnamed_addr constant [4 x i64] [i64 32, 
> > > > > i64 281474976710659, i64 32, i64 844424930131971]
> > > > > ```
> > > > This is strange, because you don't check for `nullptr`. You only check 
> > > > for `ValueDecl`s, but not capture of `this`.
> > > I'm not sure what code you're referring to when you say "you check".
> > > 
> > > Both with and without my patch, my understanding is that `nullptr` is a 
> > > special key that means `this`.  I'm depending on that to avoid generating 
> > > map entries twice for `this`.
> > > 
> > > My understanding is based on the way `generateInfoForCapture` works.  If 
> > > `Cap->capturesThis()`, then `VD = nullptr`.  That `VD` is then used by 
> > > `C->decl_component_lists(VD)` to find entries for `this` in map clauses.
> > > 
> > > Unless I'm misreading it, the code that sets `nullptr` for `this` in decl 
> > > components is `checkMappableExpressionList` in SemaOpenMP.cpp.  The last 
> > > few lines of that function have a comment to this effect.  (That comment 
> > > would probably be more useful in a header file somewhere.)
> > `MappedVarSet` is a new variable, right? It is used only in 2 places: here, 
> > where you add elements to this set, and in `generateAllInfo` where you have 
> > a check:
> > ```
> > if (SkipVarSet.count(VD))
> > return;
> > ```
> > I don't see other places where it is used. And I don't see places where you 
> > check for the presence of `nullptr` in this set. That's why I think you 
> > don't need to add it, if you don't check for its presence later.
> > MappedVarSet is a new variable, right?
> 
> Right.
> 
> > It is used only in 2 places: here, where you add elements to this set, and 
> > in generateAllInfo where you have a check:
> > 
> > ```
> > if (SkipVarSet.count(VD))
> > return;
> > ```
> > I don't see other places where it is used.
> 
> That's all.
> 
> > And I don't see places where you check for the presence of nullptr in this 
> > set. That's why I think you don't need to add it, if you don't check for 
> > its presence later.
> 
> The `SkipVarSet.count(VD)` you mentioned checks for presence of any key in 
> order to avoid creating duplicate map entries.  `nullptr` is one such key.  
> It happens to indicate `this`.
> 
> For comparison, look inside `generateInfoForCapture` where the following code 
> establishes that `nullptr` is the key for `this`:
> 
> ```
> const ValueDecl *VD = Cap->capturesThis()
>   ? nullptr
>   : Cap->getCapturedVar()->getCanonicalDecl();
> ```
> 
> After that, does `generateInfoForCapture` ever check for `VD == nullptr`?  I 
> don't see where it does.  But it does use `VD`, which might be `nulltpr`, as 
> a decl components key in the following code:
> 
> ```
>   for (const auto L : C->decl_component_lists(VD)) {
> ```
> 
> Likewise, my code is also using a `VD` that might be `nullptr` as a key in 
> `SkipVarSet`.  I don't have to special case `nullptr` at this point.  It's 
> just another key.
Ah, I see, I missed the previous line.


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

https://reviews.llvm.org/D83922



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


[PATCH] D84032: [clang] Make clear Sema::CheckForConstantInitializer is for C-only codepath.

2020-07-17 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:11072
   // rules there don't matter.)
+  assert(!getLangOpts().CPlusPlus || getLangOpts().OpenCLCPlusPlus);
   const Expr *Culprit;

openCL for C++ is tricky, see 
https://github.com/llvm/llvm-project/blob/master/clang/lib/Sema/SemaDecl.cpp#L12134-L12135.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84032



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


[PATCH] D83922: [OpenMP] Fix map clause for unused var: don't ignore it

2020-07-17 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny marked 3 inline comments as done.
jdenny added a comment.

Thanks for the review.  Will try to push soon.


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

https://reviews.llvm.org/D83922



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


[PATCH] D84021: [Driver] Add suppoort for -msve-vector-bits=scalable.

2020-07-17 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen accepted this revision.
sdesmalen added a comment.
This revision is now accepted and ready to land.

nit: s/suppoort/support/ (in title)
LGTM otherwise!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84021



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


[PATCH] D83492: [OpenMP] Use common interface to access GPU Grid Values

2020-07-17 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam marked an inline comment as done.
saiislam added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp:654
+  unsigned LaneIDBits =
+  CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
   return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");

jdoerfert wrote:
> Why do we keep the enum value with this name then?
Enums in OMPGridValues.h has been named like this because many of the values 
are dependent on a different value in the same enum. For example, hardcoded 
value of number of bits required to represent the max number of threads in a 
warp (LaneIDBits here), is computed as log of WarpSize. Similarly, mask of this 
value (LaneIDMask below) is based on WarpSize. A future change in WarpSize thus 
will require update in all the enums based on (and prefixed as) WarpSize, so 
less chances of a manual error.

See this: 
https://github.com/llvm/llvm-project/blob/8b6821a5843bb321b3738e2519beae7142e62928/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h#L120


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83492



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


[PATCH] D83974: [AIX] report_fatal_error on `-fregister_global_dtors_with_atexit` for static init

2020-07-17 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast accepted this revision.
hubert.reinterpretcast added a comment.

LGTM; thanks.


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

https://reviews.llvm.org/D83974



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


[PATCH] D83492: [OpenMP] Use common interface to access GPU Grid Values

2020-07-17 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 278787.
saiislam added a comment.

Removed getNVPTXWarpSize() changes for a separate patch and rebased.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83492

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp


Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/Cuda.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Frontend/OpenMP/OMPGridValues.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 
 using namespace clang;
@@ -195,11 +196,9 @@
 /// code.  For all practical purposes this is fine because the configuration
 /// is the same for all known NVPTX architectures.
 enum MachineConfiguration : unsigned {
-  WarpSize = 32,
-  /// Number of bits required to represent a lane identifier, which is
-  /// computed as log_2(WarpSize).
-  LaneIDBits = 5,
-  LaneIDMask = WarpSize - 1,
+  /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
+  /// specific Grid Values like GV_Warp_Size, GV_Warp_Size_Log2,
+  /// and GV_Warp_Size_Log2_Mask.
 
   /// Global memory alignment for performance.
   GlobalMemoryAlignment = 128,
@@ -431,6 +430,7 @@
 assert(!GlobalizedRD &&
"Record for globalized variables is built already.");
 ArrayRef EscapedDeclsForParallel, EscapedDeclsForTeams;
+unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
 if (IsInTTDRegion)
   EscapedDeclsForTeams = EscapedDecls.getArrayRef();
 else
@@ -634,6 +634,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDBits =
+  CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
   return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
 }
 
@@ -642,6 +644,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDMask = CGF.getContext().getTargetInfo().getGridValue(
+  llvm::omp::GV_Warp_Size_Log2_Mask);
   return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
"nvptx_lane_id");
 }


Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/Cuda.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Frontend/OpenMP/OMPGridValues.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 
 using namespace clang;
@@ -195,11 +196,9 @@
 /// code.  For all practical purposes this is fine because the configuration
 /// is the same for all known NVPTX architectures.
 enum MachineConfiguration : unsigned {
-  WarpSize = 32,
-  /// Number of bits required to represent a lane identifier, which is
-  /// computed as log_2(WarpSize).
-  LaneIDBits = 5,
-  LaneIDMask = WarpSize - 1,
+  /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
+  /// specific Grid Values like GV_Warp_Size, GV_Warp_Size_Log2,
+  /// and GV_Warp_Size_Log2_Mask.
 
   /// Global memory alignment for performance.
   GlobalMemoryAlignment = 128,
@@ -431,6 +430,7 @@
 assert(!GlobalizedRD &&
"Record for globalized variables is built already.");
 ArrayRef EscapedDeclsForParallel, EscapedDeclsForTeams;
+unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
 if (IsInTTDRegion)
   EscapedDeclsForTeams = EscapedDecls.getArrayRef();
 else
@@ -634,6 +634,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDBits =
+  CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
   return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
 }
 
@@ -642,6 +644,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDMask = CGF.getContext().getTargetInfo().getGridValue(
+  llvm::omp::GV_Warp_Size_Log2_Mask);
   return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
"nvptx_lane_id");
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83822: [clangd] Support config over LSP.

2020-07-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

There are lots of choices and overlapping ideas for how the protocol should 
look, little urgency (it isn't going to make clangd 11), and few concrete use 
cases to evaluate the options.

Let's table this for now and let the ideas sink in and more use cases crop up. 
I definitely think we should have this, probably for clangd 12, but it's worth 
getting right.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83822



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


[PATCH] D83915: [PowerPC] Remove QPX/A2Q BGQ/BGP support

2020-07-17 Thread Jinsong Ji via Phabricator via cfe-commits
jsji added a comment.

In D83915#2156346 , @jsji wrote:

> In D83915#2155650 , 
> @hubert.reinterpretcast wrote:
>
> > Should we indicate planned removal in the Release Notes for version 11 and 
> > actual removal in those for version 12?
>
>
> Good suggestion. https://reviews.llvm.org/D83968 for adding the section in 
> master, will add conent in v11 branch if approved.


Notes added to ReleaseNotes in release/11.x in 
https://reviews.llvm.org/rG297be788a797c0ab98d9677f50e3dc57faab363b


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83915



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


[PATCH] D83901: [clang] Disable a few formatting options for test/

2020-07-17 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

In D83901#2155127 , @MyDeveloperDay 
wrote:

> clang-format -n warnings before this change in clang/test/Analysis/*.cpp  
> (clang-format -n *.cpp |& grep warning | wc -l)
>
> before = 6903 vs  after=6595, if it helps I'd say this looks good. A very 
> brief review of changes seem to be mainly whitespace/extra lines and 
> indentation  (44 in headers files vs 43)
>  (Note: There are 11 warnings after the first iteration, clang-format 
> sometimes has to be run twice)
>
> The real proof is how many of the unit tests can be clang-formatted and still 
> pass, but I completely approve of this effort, if the test directories were 
> formatted this would give us a massive test suite of lots of different 
> examples of c++ code to validate any clang-format changes.
>
> If having this in the clang-format file means users can use "Format on Save" 
> options in their editors and not break tests then I think this is a good 
> thing. As this will drive good behavior in all the other files rather than 
> having to turn "Format on Save" off because we cannot maintain running tests.
>
> My 2 cents worth.


Thank you for your comment.

FWIW I think that the current approach with the lint bot needs to be changed 
for the following reasons:

1. `clang-format` lets me forget about formatting and for this I like it very 
much. This only works because running `clang-format` is almost always safe to 
run. ie: it doesn't change the meaning of the code. This breaks down with most 
tests in `test/` because the meaning of many test *is* changed by 
`clang-format`: ie: `clang-format` is very much *not* safe to run on a test.

2. Even after running `clang-format` on a test and fixing it manually, the bot 
will still complain in some cases if the formatting was done with a different 
version of `clang-format`. This has happened to me multiple times and for some 
reason always in a test. The bot should not complain if the formatting is fine 
in one of the previous n versions.

3. Tests are written in a different style optimised for conciseness. For 
example `struct S { S() = default; ~S() = delete; }; // not at all unusual in a 
test`. This could be accounted for in `.clang-format` but...

4. ...`clang-format-diff` does not respect (as far as I know?) the 
`.clang-format` in a sub-folder.

5. The lint bot is very noisy and makes reviews much harder because the 
formatting complaints are inline. Moving them out-of-line would be significant 
improvement.

I must admit I am very much tempted to put a generic `// clang-format off` in 
the tests I write.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83901



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


[PATCH] D83492: [OpenMP] Use common interface to access GPU Grid Values

2020-07-17 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 278799.
saiislam added a comment.

Corrected.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83492

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp


Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/Cuda.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Frontend/OpenMP/OMPGridValues.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 
 using namespace clang;
@@ -195,11 +196,9 @@
 /// code.  For all practical purposes this is fine because the configuration
 /// is the same for all known NVPTX architectures.
 enum MachineConfiguration : unsigned {
-  WarpSize = 32,
-  /// Number of bits required to represent a lane identifier, which is
-  /// computed as log_2(WarpSize).
-  LaneIDBits = 5,
-  LaneIDMask = WarpSize - 1,
+  /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
+  /// specific Grid Values like GV_Warp_Size, GV_Warp_Size_Log2,
+  /// and GV_Warp_Size_Log2_Mask.
 
   /// Global memory alignment for performance.
   GlobalMemoryAlignment = 128,
@@ -431,6 +430,7 @@
 assert(!GlobalizedRD &&
"Record for globalized variables is built already.");
 ArrayRef EscapedDeclsForParallel, EscapedDeclsForTeams;
+unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
 if (IsInTTDRegion)
   EscapedDeclsForTeams = EscapedDecls.getArrayRef();
 else
@@ -634,6 +634,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDBits =
+  CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
   return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
 }
 
@@ -642,6 +644,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDMask = CGF.getContext().getTargetInfo().getGridValue(
+  llvm::omp::GV_Warp_Size_Log2_Mask);
   return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
"nvptx_lane_id");
 }
@@ -2058,6 +2062,7 @@
   const RecordDecl *GlobalizedRD = nullptr;
   llvm::SmallVector LastPrivatesReductions;
   llvm::SmallDenseMap MappedDeclsFields;
+  unsigned WarpSize = CGM.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
   // Globalize team reductions variable unconditionally in all modes.
   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
@@ -3233,6 +3238,7 @@
   "__openmp_nvptx_data_transfer_temporary_storage";
   llvm::GlobalVariable *TransferMedium =
   M.getGlobalVariable(TransferMediumName);
+  unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
   if (!TransferMedium) {
 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);


Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/Cuda.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Frontend/OpenMP/OMPGridValues.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 
 using namespace clang;
@@ -195,11 +196,9 @@
 /// code.  For all practical purposes this is fine because the configuration
 /// is the same for all known NVPTX architectures.
 enum MachineConfiguration : unsigned {
-  WarpSize = 32,
-  /// Number of bits required to represent a lane identifier, which is
-  /// computed as log_2(WarpSize).
-  LaneIDBits = 5,
-  LaneIDMask = WarpSize - 1,
+  /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
+  /// specific Grid Values like GV_Warp_Size, GV_Warp_Size_Log2,
+  /// and GV_Warp_Size_Log2_Mask.
 
   /// Global memory alignment for performance.
   GlobalMemoryAlignment = 128,
@@ -431,6 +430,7 @@
 assert(!GlobalizedRD &&
"Record for globalized variables is built already.");
 ArrayRef EscapedDeclsForParallel, EscapedDeclsForTeams;
+unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
 if (IsInTTDRegion)
   EscapedDeclsForTeams = EscapedDecls.getArrayRef();
 else
@@ -634,6 +634,8 @@
 /// on the NVPTX device, to generate more efficient code.
 static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
   CGBuilderTy &Bld = CGF.Builder;
+  unsigned LaneIDBits =
+  CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
   return Bld.CreateASh

[PATCH] D83492: [OpenMP] Use common interface to access GPU Grid Values

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83492



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


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

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

The problem with `fgetc` is here that the returned value indicates not only if 
there was failure or not. In the following (over simplified) example no warning 
is needed even if there is no check for EOF. Because this case, for such kind 
of functions any comparison of the return value should be treated as an error 
check. Similar functions are the `strtol` family.

  c = fgetc(fd);
  if (c == 'a') {
// this is the expected input
  } else {
// any other value is handled as error
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72705



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


[PATCH] D84021: [Driver] Add suppoort for -msve-vector-bits=scalable.

2020-07-17 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm updated this revision to Diff 278803.
paulwalker-arm added a comment.
Herald added a subscriber: dang.

Sorry for the post acceptance change, but I spotted the help text needed an 
update also.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84021

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/aarch64-sve-vector-bits.c

Index: clang/test/Driver/aarch64-sve-vector-bits.c
===
--- clang/test/Driver/aarch64-sve-vector-bits.c
+++ clang/test/Driver/aarch64-sve-vector-bits.c
@@ -12,12 +12,15 @@
 // RUN:  -msve-vector-bits=1024 2>&1 | FileCheck --check-prefix=CHECK-1024 %s
 // RUN: %clang -c %s -### -target aarch64-none-linux-gnu -march=armv8-a+sve \
 // RUN:  -msve-vector-bits=2048 2>&1 | FileCheck --check-prefix=CHECK-2048 %s
+// RUN: %clang -c %s -### -target aarch64-none-linux-gnu -march=armv8-a+sve \
+// RUN:  -msve-vector-bits=scalable 2>&1 | FileCheck --check-prefix=CHECK-SCALABLE %s
 
 // CHECK-128: "-msve-vector-bits=128"
 // CHECK-256: "-msve-vector-bits=256"
 // CHECK-512: "-msve-vector-bits=512"
 // CHECK-1024: "-msve-vector-bits=1024"
 // CHECK-2048: "-msve-vector-bits=2048"
+// CHECK-SCALABLE-NOT: "-msve-vector-bits=
 
 // Bail out if -msve-vector-bits is specified without SVE enabled
 // -
@@ -47,11 +50,13 @@
 // -
 // RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
 // RUN:  -march=armv8-a+sve 2>&1 | FileCheck --check-prefix=CHECK-NO-FLAG-ERROR %s
+// RUN: not %clang -c %s -o /dev/null -target aarch64-none-linux-gnu \
+// RUN:  -march=armv8-a+sve -msve-vector-bits=scalable 2>&1 | FileCheck --check-prefix=CHECK-NO-FLAG-ERROR %s
 
 typedef __SVInt32_t svint32_t;
 typedef svint32_t noflag __attribute__((arm_sve_vector_bits(256)));
 
-// CHECK-NO-FLAG-ERROR: error: 'arm_sve_vector_bits' is not supported when '-msve-vector-bits=' is not specified
+// CHECK-NO-FLAG-ERROR: error: 'arm_sve_vector_bits' is only supported when '-msve-vector-bits=' is specified with a value of 128, 256, 512, 1024 or 2048
 
 // Error if attribute vector size != -msve-vector-bits
 // -
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1720,15 +1720,15 @@
   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
 StringRef Val = A->getValue();
 const Driver &D = getToolChain().getDriver();
-if (!Val.equals("128") && !Val.equals("256") && !Val.equals("512") &&
-!Val.equals("1024") && !Val.equals("2048")) {
+if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
+Val.equals("1024") || Val.equals("2048"))
+  CmdArgs.push_back(
+  Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
+// Silently drop requests for vector-length agnostic code as it's implied.
+else if (!Val.equals("scalable"))
   // Handle the unsupported values passed to msve-vector-bits.
   D.Diag(diag::err_drv_unsupported_option_argument)
   << A->getOption().getName() << Val;
-} else if (A->getOption().matches(options::OPT_msve_vector_bits_EQ)) {
-  CmdArgs.push_back(
-  Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
-}
   }
 }
 
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -370,8 +370,8 @@
 V8_6Pos = Features.insert(std::next(V8_6Pos), {"+i8mm", "+bf16"});
 
   bool HasSve = llvm::is_contained(Features, "+sve");
-  // -msve_vector_bits= flag is valid only if SVE is enabled.
-  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
+  // -msve-vector-bits= flag is valid only if SVE is enabled.
+  if (Args.hasArg(options::OPT_msve_vector_bits_EQ))
 if (!HasSve)
   D.Diag(diag::err_drv_invalid_sve_vector_bits);
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2346,8 +2346,9 @@
 
 def msve_vector_bits_EQ : Joined<["-"], "msve-vector-bits=">,
   Group, Flags<[DriverOption,CC1Option]>,
-  HelpText<"Set the size of fixed-length SVE vectors in bits.">,
-  Values<"128,256,512,1024,2048">;
+  HelpText<"Specify the size in bits of an SVE vector register. Defaults to the"
+   " vect

[PATCH] D83680: [clang-tidy] Refactor IncludeInserter

2020-07-17 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 278807.
njames93 marked 5 inline comments as done.
njames93 added a comment.

Address reviewer comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83680

Files:
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.h
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.h
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.h
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.h
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.h
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.h
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.h
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.h
  clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeInserter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
  clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
@@ -33,9 +33,7 @@
 
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override {
-Inserter = std::make_unique(
-SM, getLangOpts(), utils::IncludeSorter::IS_Google);
-PP->addPPCallbacks(Inserter->CreatePPCallbacks());
+Inserter.registerPreprocessor(PP);
   }
 
   void registerMatchers(ast_matchers::MatchFinder *Finder) override {
@@ -46,15 +44,15 @@
 auto Diag = diag(Result.Nodes.getNodeAs("stmt")->getBeginLoc(),
  "foo, bar");
 for (StringRef Header : HeadersToInclude()) {
-  Diag << Inserter->CreateIncludeInsertion(
-  Result.SourceManager->getMainFileID(), Header, IsAngledInclude());
+  Diag << Inserter.createMainFileIncludeInsertion(Header,
+  IsAngledInclude());
 }
   }
 
   virtual std::vector HeadersToInclude() const = 0;
   virtual bool IsAngledInclude() const = 0;
 
-  std::unique_ptr Inserter;
+  utils::IncludeInserter Inserter{utils::IncludeSorter::IS_Google};
 };
 
 class NonSystemHeaderInserterCheck : public IncludeInserterCheckBase {
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
@@ -70,8 +70,7 @@
 
 private:
   Optional Rule;
-  const IncludeSorter::IncludeStyle IncludeStyle;
-  std::unique_ptr Inserter;
+  IncludeInserter Inserter;
 };
 
 } // namespace utils
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -32,8 +32,8 @@
 MakeRule,
 StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(MakeRule(getLangOpts(), Options)),
-  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
-IncludeSorter::IS_LLVM)) {
+  Inserter(
+  Options.getLocalOrGlobal("IncludeStyle", IncludeSorter::IS_LLVM)) {
   if (Rule)
 assert(llvm::all_of(Rule->Cases, hasExplanation) &&
"clang-tidy checks must have an explanation by default;"
@@ -44,8 +44,8 @@
  StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(std::move(R)),
-  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
-  

[PATCH] D83149: [gcov] Add __gcov_dump/__gcov_reset and delete __gcov_flush

2020-07-17 Thread calixte via Phabricator via cfe-commits
calixte accepted this revision.
calixte added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83149



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


[PATCH] D83680: [clang-tidy] Refactor IncludeInserter

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83680



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


[clang] 14dde43 - With MSVC, file needs to be compiled with /BIGOBJ

2020-07-17 Thread Adrian McCarthy via cfe-commits

Author: Adrian McCarthy
Date: 2020-07-17T09:43:06-07:00
New Revision: 14dde438d69c81ab4651157a94d32ee804ff

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

LOG: With MSVC, file needs to be compiled with /BIGOBJ

MSVC, by default, limits the number of sections generated by a single
translation unit to 2^16.  In a debug build, each function or method
can require 4 sections, so it's not uncommon to hit it.

I saw the problem when building tests for LLDB (but, interestingly, not
for LLDB itself).

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

Added: 


Modified: 
clang/lib/ARCMigrate/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/ARCMigrate/CMakeLists.txt 
b/clang/lib/ARCMigrate/CMakeLists.txt
index 6f19bea476da..1d5a185c3b6a 100644
--- a/clang/lib/ARCMigrate/CMakeLists.txt
+++ b/clang/lib/ARCMigrate/CMakeLists.txt
@@ -2,6 +2,12 @@ set(LLVM_LINK_COMPONENTS
   Support
   )
 
+# By default MSVC has a 2^16 limit on the number of sections in an object
+# file, and Transforms.cpp needs more than that.
+if (MSVC)
+  set_source_files_properties(Transforms.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+endif()
+
 add_clang_library(clangARCMigrate
   ARCMT.cpp
   ARCMTActions.cpp



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


[PATCH] D83991: With MSVC, file needs to be compiled with /BIGOBJ

2020-07-17 Thread Adrian McCarthy via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG14dde438d69c: With MSVC, file needs to be compiled with 
/BIGOBJ (authored by amccarth).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83991

Files:
  clang/lib/ARCMigrate/CMakeLists.txt


Index: clang/lib/ARCMigrate/CMakeLists.txt
===
--- clang/lib/ARCMigrate/CMakeLists.txt
+++ clang/lib/ARCMigrate/CMakeLists.txt
@@ -2,6 +2,12 @@
   Support
   )
 
+# By default MSVC has a 2^16 limit on the number of sections in an object
+# file, and Transforms.cpp needs more than that.
+if (MSVC)
+  set_source_files_properties(Transforms.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+endif()
+
 add_clang_library(clangARCMigrate
   ARCMT.cpp
   ARCMTActions.cpp


Index: clang/lib/ARCMigrate/CMakeLists.txt
===
--- clang/lib/ARCMigrate/CMakeLists.txt
+++ clang/lib/ARCMigrate/CMakeLists.txt
@@ -2,6 +2,12 @@
   Support
   )
 
+# By default MSVC has a 2^16 limit on the number of sections in an object
+# file, and Transforms.cpp needs more than that.
+if (MSVC)
+  set_source_files_properties(Transforms.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+endif()
+
 add_clang_library(clangARCMigrate
   ARCMT.cpp
   ARCMTActions.cpp
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82756: Port some floating point options to new option marshalling infrastructure

2020-07-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/test/CodeGen/fp-function-attrs.cpp:2
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -ffast-math -ffinite-math-only 
-menable-unsafe-fp-math \
+// RUN:   -menable-no-infs -menable-no-nans -fno-signed-zeros 
-freciprocal-math \
+// RUN:   -fapprox-func -mreassociate -ffp-contract=fast -emit-llvm -o - %s | 
FileCheck %s

dang wrote:
> Anastasia wrote:
> > Not clear why do you need to pass these extra flags now?
> Previously passing -ffast-math to CC1 implied all these other flags. I am 
> trying to make CC1 option parsing as simple as possible, so that we can then 
> make it easy to generate a command line from a CompilerInvocation instance. 
> You can refer to [[ 
> http://lists.llvm.org/pipermail/cfe-dev/2020-May/065421.html | 
> http://lists.llvm.org/pipermail/cfe-dev/2020-May/065421.html ]] for more 
> details on why we want to be able to do this
Just to understand, there used to be implied flags and it made the manual 
command line use of clang more compact and easy... Is the idea now to change 
those compound flags such that individul flags always need to be passed?

Although I thought you are still adding the implicit flags:

  {options::OPT_cl_fast_relaxed_math,
   [&](const Arg *Arg) {
 RenderArg(Arg);

 CmdArgs.push_back(GetArgString(options::OPT_cl_mad_enable));
 CmdArgs.push_back(GetArgString(options::OPT_ffast_math));
 CmdArgs.push_back(GetArgString(options::OPT_ffinite_math_only));
 CmdArgs.push_back(
 GetArgString(options::OPT_menable_unsafe_fp_math));
 CmdArgs.push_back(GetArgString(options::OPT_mreassociate));
 CmdArgs.push_back(GetArgString(options::OPT_menable_no_nans));
 CmdArgs.push_back(
 GetArgString(options::OPT_menable_no_infinities));
 CmdArgs.push_back(GetArgString(options::OPT_fno_signed_zeros));
 CmdArgs.push_back(GetArgString(options::OPT_freciprocal_math));
 CmdArgs.push_back(GetArgString(options::OPT_fapprox_func));
   }}

Do I just misunderstand something?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82756



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


[clang] d19f066 - [clang][Tooling] Try to avoid file system access if there is no record for the file in compile_commads.json

2020-07-17 Thread Sam McCall via cfe-commits

Author: Aleksandr Platonov
Date: 2020-07-17T18:49:14+02:00
New Revision: d19f0666bcd8f7d26aaf4019244c3ed91e47b1b7

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

LOG: [clang][Tooling] Try to avoid file system access if there is no record for 
the file in compile_commads.json

Summary:
If there is no record in compile_commands.json, we try to find suitable record 
with `MatchTrie.findEquivalent()` call.
This is very expensive operation with a lot of `llvm::sys::fs::equivalent()` 
calls in some cases.

This patch disables file symlinks for performance reasons.

Example scenario without this patch:
- compile_commands.json generated at clangd build (contains ~3000 files).
- it tooks more than 1 second to get compile command for newly created file in 
the root folder of LLVM project.
- we wait for 1 second every time when clangd requests compile command for this 
file (at file change).

Reviewers: sammccall, kadircet, hokein

Reviewed By: sammccall

Subscribers: chandlerc, djasper, klimek, ilya-biryukov, kadircet, usaxena95, 
cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/Tooling/FileMatchTrie.cpp
clang/unittests/Tooling/CompilationDatabaseTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/FileMatchTrie.cpp 
b/clang/lib/Tooling/FileMatchTrie.cpp
index 88dea6bb6c9f..3b02405da2f2 100644
--- a/clang/lib/Tooling/FileMatchTrie.cpp
+++ b/clang/lib/Tooling/FileMatchTrie.cpp
@@ -105,8 +105,13 @@ class FileMatchTrieNode {
StringRef FileName,
bool &IsAmbiguous,
unsigned ConsumedLength = 0) const {
+// Note: we support only directory symlinks for performance reasons.
 if (Children.empty()) {
-  if (Comparator.equivalent(StringRef(Path), FileName))
+  // As far as we do not support file symlinks, compare
+  // basenames here to avoid request to file system.
+  if (llvm::sys::path::filename(Path) ==
+  llvm::sys::path::filename(FileName) &&
+  Comparator.equivalent(StringRef(Path), FileName))
 return StringRef(Path);
   return {};
 }
@@ -121,6 +126,13 @@ class FileMatchTrieNode {
   if (!Result.empty() || IsAmbiguous)
 return Result;
 }
+
+// If `ConsumedLength` is zero, this is the root and we have no filename
+// match. Give up in this case, we don't try to find symlinks with
+// 
diff erent names.
+if (ConsumedLength == 0)
+  return {};
+
 std::vector AllChildren;
 getAll(AllChildren, MatchingChild);
 StringRef Result;

diff  --git a/clang/unittests/Tooling/CompilationDatabaseTest.cpp 
b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
index cc948b800f4e..3bfb0ec1f7d5 100644
--- a/clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -281,6 +281,15 @@ TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
   EXPECT_EQ("Cannot resolve relative paths", Error);
 }
 
+TEST_F(FileMatchTrieTest, SingleFile) {
+  Trie.insert("/root/RootFile.cc");
+  EXPECT_EQ("", find("/root/rootfile.cc"));
+  // Add subpath to avoid `if (Children.empty())` special case
+  // which we hit at previous `find()`.
+  Trie.insert("/root/otherpath/OtherFile.cc");
+  EXPECT_EQ("", find("/root/rootfile.cc"));
+}
+
 TEST(findCompileArgsInJsonDatabase, FindsNothingIfEmpty) {
   std::string ErrorMessage;
   CompileCommand NotFound = findCompileArgsInJsonDatabase(



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


  1   2   >