[PATCH] D52448: [clang-format] Break before next parameter after a formatted multiline raw string parameter

2018-10-25 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir marked an inline comment as done.
krasimir added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:1594
   StartColumn + NewPrefixSize - Style.ColumnLimit : 0;
-  return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
+  unsigned Penalty =
+  Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;

sammccall wrote:
> nit: why are you doing the multiline side-effect between computing the 
> penalty and returning it?
Thank you!


Repository:
  rC Clang

https://reviews.llvm.org/D52448



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


[PATCH] D52448: [clang-format] Break before next parameter after a formatted multiline raw string parameter

2018-10-25 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 171041.
krasimir marked an inline comment as done.
krasimir added a comment.

- Address review comment


Repository:
  rC Clang

https://reviews.llvm.org/D52448

Files:
  lib/Format/ContinuationIndenter.cpp
  unittests/Format/FormatTestRawStrings.cpp

Index: unittests/Format/FormatTestRawStrings.cpp
===
--- unittests/Format/FormatTestRawStrings.cpp
+++ unittests/Format/FormatTestRawStrings.cpp
@@ -576,10 +576,13 @@
 auto S = R"pb(item_1:1 item_2:2)pb"+rest;)test",
getRawStringPbStyleWithColumns(40)));
 
+  // `rest` fits on the line after )pb", but forced on newline since the raw
+  // string literal is multiline.
   expect_eq(R"test(
 auto S = R"pb(item_1: 1,
   item_2: 2,
-  item_3: 3)pb" + rest;)test",
+  item_3: 3)pb" +
+ rest;)test",
 format(R"test(
 auto S = R"pb(item_1:1,item_2:2,item_3:3)pb"+rest;)test",
getRawStringPbStyleWithColumns(40)));
@@ -615,7 +618,8 @@
   expect_eq(R"test(
 auto S = R"pb(item_1: 1,
   item_2: 2,
-  item_3: 3)pb" + rest;)test",
+  item_3: 3)pb" +
+ rest;)test",
 format(R"test(
 auto S = R"pb(item_1:1,item_2:2,item_3:3)pb"+rest;)test",
getRawStringPbStyleWithColumns(40)));
@@ -889,6 +893,95 @@
Style));
 }
 
+TEST_F(FormatTestRawStrings,
+   BreaksBeforeNextParamAfterMultilineRawStringParam) {
+  FormatStyle Style = getRawStringPbStyleWithColumns(60);
+  expect_eq(R"test(
+int f() {
+  int a = g(x, R"pb(
+  key: 1  #
+  key: 2
+)pb",
+3, 4);
+}
+)test",
+format(R"test(
+int f() {
+  int a = g(x, R"pb(
+  key: 1 #
+  key: 2
+)pb", 3, 4);
+}
+)test",
+   Style));
+
+  // Breaks after a parent of a multiline param.
+  expect_eq(R"test(
+int f() {
+  int a = g(x, h(R"pb(
+  key: 1  #
+  key: 2
+)pb"),
+3, 4);
+}
+)test",
+format(R"test(
+int f() {
+  int a = g(x, h(R"pb(
+  key: 1 #
+  key: 2
+)pb"), 3, 4);
+}
+)test",
+   Style));
+  
+  expect_eq(R"test(
+int f() {
+  int a = g(x,
+h(R"pb(
+key: 1  #
+key: 2
+  )pb",
+  2),
+3, 4);
+}
+)test",
+format(R"test(
+int f() {
+  int a = g(x, h(R"pb(
+  key: 1 #
+  key: 2
+)pb", 2), 3, 4);
+}
+)test",
+   Style));
+  // Breaks if formatting introduces a multiline raw string.
+  expect_eq(R"test(
+int f() {
+  int a = g(x, R"pb(key1: value1
+key2: value22)pb",
+3, 4);
+}
+)test",
+format(R"test(
+int f() {
+  int a = g(x, R"pb(key1: value1 key2: value22)pb", 3, 4);
+}
+)test",
+   Style));
+  // Does not force a break after an original multiline param that is
+  // reformatterd as on single line.
+  expect_eq(R"test(
+int f() {
+  int a = g(R"pb(key: 1)pb", 2);
+})test",
+format(R"test(
+int f() {
+  int a = g(R"pb(key:
+ 1)pb", 2);
+})test", Style));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1502,10 +1502,25 @@
   // violate the rectangle rule and visually flows within the surrounding
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
-  unsigned NextStartColumn =
-  ContentStartsOnNewline
-  ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
-  : FirstStartColumn;
+  // If this token is the last parameter (checked by looking if it's followed by
+  // `)`, the base the indent off the line's nested block indent. Otherwise,
+  // base the indent off the arguments indent, so we can achieve:
+  // fff(1, 2, 3, R"pb(
+  // key1: 1  #
+  // key2: 2)pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
+  // )pb",
+  // 5);
+  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
+   ? State.Stack.back().NestedBlockIndent
+   : State.Stack.back().Indent;
+  unsigned NextStartColumn = ContentStartsOnNewline
+ ? CurrentIndent + Style.IndentWidth
+ : FirstStartColumn;
 
   // The last start column is the column the raw string suffix starts if it is
   // put on a newline.
@@ -1517,7 +1532,7 @@
   // indent.
   unsigned LastStartColumn

r345242 - [clang-format] Break before next parameter after a formatted multiline raw string parameter

2018-10-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Oct 25 00:39:30 2018
New Revision: 345242

URL: http://llvm.org/viewvc/llvm-project?rev=345242&view=rev
Log:
[clang-format] Break before next parameter after a formatted multiline raw 
string parameter

Summary:
Currently clang-format breaks before the next parameter after multiline 
parameters (also recursively for the parent expressions of multiline 
parameters). However, it fails to do so for formatted multiline raw string 
literals:
```
$ cat test.cc
// Examples

// Regular multiline tokens
int x = f(R"(multi
 line)", 2);
}

int y = g(h(R"(multi
  line)"), 2);

// Formatted multiline tokens
int z = f(R"pb(multi: 1  #
   line: 2)pb", 2);

int w = g(h(R"pb(multi: 1  #
 line: 2)pb"), 2);
$ clang-format -style=google test.cc
// Examples

// Regular multiline tokens
int x = f(R"(multi
 line)",
  2);
}

int y = g(h(R"(multi
  line)"),
  2);

// Formatted multiline tokens
int z = f(R"pb(multi: 1  #
   line: 2)pb", 2);

int w = g(h(R"pb(multi: 1  #
 line: 2)pb"), 2);
```

This patch addresses this inconsistency by forcing breaking after multiline 
formatted raw string literals. This requires a little tweak to the indentation 
chosen for the contents of a formatted raw string literal: in case when that's 
a parameter and not the last one, the indentation is based off of the uniform 
indentation of all of the parameters.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=345242&r1=345241&r2=345242&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Oct 25 00:39:30 2018
@@ -1502,10 +1502,25 @@ unsigned ContinuationIndenter::reformatR
   // violate the rectangle rule and visually flows within the surrounding
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
-  unsigned NextStartColumn =
-  ContentStartsOnNewline
-  ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
-  : FirstStartColumn;
+  // If this token is the last parameter (checked by looking if it's followed 
by
+  // `)`, the base the indent off the line's nested block indent. Otherwise,
+  // base the indent off the arguments indent, so we can achieve:
+  // fff(1, 2, 3, R"pb(
+  // key1: 1  #
+  // key2: 2)pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
+  // )pb",
+  // 5);
+  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
+   ? State.Stack.back().NestedBlockIndent
+   : State.Stack.back().Indent;
+  unsigned NextStartColumn = ContentStartsOnNewline
+ ? CurrentIndent + Style.IndentWidth
+ : FirstStartColumn;
 
   // The last start column is the column the raw string suffix starts if it is
   // put on a newline.
@@ -1517,7 +1532,7 @@ unsigned ContinuationIndenter::reformatR
   // indent.
   unsigned LastStartColumn = Current.NewlinesBefore
  ? FirstStartColumn - NewPrefixSize
- : State.Stack.back().NestedBlockIndent;
+ : CurrentIndent;
 
   std::pair Fixes = internal::reformat(
   RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
@@ -1527,8 +1542,7 @@ unsigned ContinuationIndenter::reformatR
   auto NewCode = applyAllReplacements(RawText, Fixes.first);
   tooling::Replacements NoFixes;
   if (!NewCode) {
-State.Column += Current.ColumnWidth;
-return 0;
+return addMultilineToken(Current, State);
   }
   if (!DryRun) {
 if (NewDelimiter != OldDelimiter) {
@@ -1577,6 +1591,13 @@ unsigned ContinuationIndenter::reformatR
   unsigned PrefixExcessCharacters =
   StartColumn + NewPrefixSize > Style.ColumnLimit ?
   StartColumn + NewPrefixSize - Style.ColumnLimit : 0;
+  bool IsMultiline =
+  ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
+  if (IsMultiline) {
+// Break before further function parameters on all levels.
+for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
+  State.Stack[i].BreakBeforeParameter = true;
+  }
   return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
 }
 

Modified: cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/F

[PATCH] D52448: [clang-format] Break before next parameter after a formatted multiline raw string parameter

2018-10-25 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL345242: [clang-format] Break before next parameter after a 
formatted multiline raw… (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52448

Files:
  cfe/trunk/lib/Format/ContinuationIndenter.cpp
  cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Index: cfe/trunk/lib/Format/ContinuationIndenter.cpp
===
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp
@@ -1502,10 +1502,25 @@
   // violate the rectangle rule and visually flows within the surrounding
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
-  unsigned NextStartColumn =
-  ContentStartsOnNewline
-  ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
-  : FirstStartColumn;
+  // If this token is the last parameter (checked by looking if it's followed by
+  // `)`, the base the indent off the line's nested block indent. Otherwise,
+  // base the indent off the arguments indent, so we can achieve:
+  // fff(1, 2, 3, R"pb(
+  // key1: 1  #
+  // key2: 2)pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
+  // )pb",
+  // 5);
+  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
+   ? State.Stack.back().NestedBlockIndent
+   : State.Stack.back().Indent;
+  unsigned NextStartColumn = ContentStartsOnNewline
+ ? CurrentIndent + Style.IndentWidth
+ : FirstStartColumn;
 
   // The last start column is the column the raw string suffix starts if it is
   // put on a newline.
@@ -1517,7 +1532,7 @@
   // indent.
   unsigned LastStartColumn = Current.NewlinesBefore
  ? FirstStartColumn - NewPrefixSize
- : State.Stack.back().NestedBlockIndent;
+ : CurrentIndent;
 
   std::pair Fixes = internal::reformat(
   RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
@@ -1527,8 +1542,7 @@
   auto NewCode = applyAllReplacements(RawText, Fixes.first);
   tooling::Replacements NoFixes;
   if (!NewCode) {
-State.Column += Current.ColumnWidth;
-return 0;
+return addMultilineToken(Current, State);
   }
   if (!DryRun) {
 if (NewDelimiter != OldDelimiter) {
@@ -1577,6 +1591,13 @@
   unsigned PrefixExcessCharacters =
   StartColumn + NewPrefixSize > Style.ColumnLimit ?
   StartColumn + NewPrefixSize - Style.ColumnLimit : 0;
+  bool IsMultiline =
+  ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
+  if (IsMultiline) {
+// Break before further function parameters on all levels.
+for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
+  State.Stack[i].BreakBeforeParameter = true;
+  }
   return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
 }
 
Index: cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
===
--- cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
+++ cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
@@ -576,10 +576,13 @@
 auto S = R"pb(item_1:1 item_2:2)pb"+rest;)test",
getRawStringPbStyleWithColumns(40)));
 
+  // `rest` fits on the line after )pb", but forced on newline since the raw
+  // string literal is multiline.
   expect_eq(R"test(
 auto S = R"pb(item_1: 1,
   item_2: 2,
-  item_3: 3)pb" + rest;)test",
+  item_3: 3)pb" +
+ rest;)test",
 format(R"test(
 auto S = R"pb(item_1:1,item_2:2,item_3:3)pb"+rest;)test",
getRawStringPbStyleWithColumns(40)));
@@ -615,7 +618,8 @@
   expect_eq(R"test(
 auto S = R"pb(item_1: 1,
   item_2: 2,
-  item_3: 3)pb" + rest;)test",
+  item_3: 3)pb" +
+ rest;)test",
 format(R"test(
 auto S = R"pb(item_1:1,item_2:2,item_3:3)pb"+rest;)test",
getRawStringPbStyleWithColumns(40)));
@@ -889,6 +893,95 @@
Style));
 }
 
+TEST_F(FormatTestRawStrings,
+   BreaksBeforeNextParamAfterMultilineRawStringParam) {
+  FormatStyle Style = getRawStringPbStyleWithColumns(60);
+  expect_eq(R"test(
+int f() {
+  int a = g(x, R"pb(
+  key: 1  #
+  key: 2
+)pb",
+3, 4);
+}
+)test",
+format(R"test(
+int f() {
+  int a = g(x, R"pb(
+  key: 1 #
+  key: 2
+)pb", 3, 4);
+}
+)test",
+   Style));
+
+  // Breaks after a parent of a multiline param.
+  expect_eq(R"test(
+int f() {
+  int a = g(x, h(R"pb(

[PATCH] D53482: Add clang-format stability check with FormatTests

2018-10-25 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

The problem with this is that I believe fixing this issue is not worth it, 
hence this patch is unnecessary. Feel free to reach out to djasper@ for a 
second opinion. For completeness, was the unstability a problem just in 
FormatTest.cpp, how about the other FormatTest*.cpp in the same directory?


https://reviews.llvm.org/D53482



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


[PATCH] D52857: [clang-query] Add non-exclusive output API

2018-10-25 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 171046.
steveire added a comment.

New command design


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52857

Files:
  clang-query/Query.cpp
  clang-query/Query.h
  clang-query/QueryParser.cpp
  clang-query/QueryParser.h
  unittests/clang-query/QueryEngineTest.cpp
  unittests/clang-query/QueryParserTest.cpp

Index: unittests/clang-query/QueryParserTest.cpp
===
--- unittests/clang-query/QueryParserTest.cpp
+++ unittests/clang-query/QueryParserTest.cpp
@@ -90,6 +90,14 @@
   ASSERT_TRUE(isa(Q));
   EXPECT_EQ(&QuerySession::DetailedASTOutput, cast(Q)->Var);
 
+  Q = parse("enable output detailed-ast");
+  ASSERT_TRUE(isa(Q));
+  EXPECT_EQ(&QuerySession::DetailedASTOutput, cast(Q)->Var);
+
+  Q = parse("disable output detailed-ast");
+  ASSERT_TRUE(isa(Q));
+  EXPECT_EQ(&QuerySession::DetailedASTOutput, cast(Q)->Var);
+
   Q = parse("set bind-root foo");
   ASSERT_TRUE(isa(Q));
   EXPECT_EQ("expected 'true' or 'false', got 'foo'",
@@ -163,7 +171,7 @@
 TEST_F(QueryParserTest, Complete) {
   std::vector Comps =
   QueryParser::complete("", 0, QS);
-  ASSERT_EQ(6u, Comps.size());
+  ASSERT_EQ(8u, Comps.size());
   EXPECT_EQ("help ", Comps[0].TypedText);
   EXPECT_EQ("help", Comps[0].DisplayText);
   EXPECT_EQ("let ", Comps[1].TypedText);
@@ -174,14 +182,35 @@
   EXPECT_EQ("quit", Comps[3].DisplayText);
   EXPECT_EQ("set ", Comps[4].TypedText);
   EXPECT_EQ("set", Comps[4].DisplayText);
-  EXPECT_EQ("unlet ", Comps[5].TypedText);
-  EXPECT_EQ("unlet", Comps[5].DisplayText);
+  EXPECT_EQ("enable ", Comps[5].TypedText);
+  EXPECT_EQ("enable", Comps[5].DisplayText);
+  EXPECT_EQ("disable ", Comps[6].TypedText);
+  EXPECT_EQ("disable", Comps[6].DisplayText);
+  EXPECT_EQ("unlet ", Comps[7].TypedText);
+  EXPECT_EQ("unlet", Comps[7].DisplayText);
 
   Comps = QueryParser::complete("set o", 5, QS);
   ASSERT_EQ(1u, Comps.size());
   EXPECT_EQ("utput ", Comps[0].TypedText);
   EXPECT_EQ("output", Comps[0].DisplayText);
 
+  Comps = QueryParser::complete("enable ", 7, QS);
+  ASSERT_EQ(1u, Comps.size());
+  EXPECT_EQ("output ", Comps[0].TypedText);
+  EXPECT_EQ("output", Comps[0].DisplayText);
+
+  Comps = QueryParser::complete("enable output ", 14, QS);
+  ASSERT_EQ(4u, Comps.size());
+
+  EXPECT_EQ("diag ", Comps[0].TypedText);
+  EXPECT_EQ("diag", Comps[0].DisplayText);
+  EXPECT_EQ("print ", Comps[1].TypedText);
+  EXPECT_EQ("print", Comps[1].DisplayText);
+  EXPECT_EQ("detailed-ast ", Comps[2].TypedText);
+  EXPECT_EQ("detailed-ast", Comps[2].DisplayText);
+  EXPECT_EQ("dump ", Comps[3].TypedText);
+  EXPECT_EQ("dump", Comps[3].DisplayText);
+
   Comps = QueryParser::complete("match while", 11, QS);
   ASSERT_EQ(1u, Comps.size());
   EXPECT_EQ("Stmt(", Comps[0].TypedText);
Index: unittests/clang-query/QueryEngineTest.cpp
===
--- unittests/clang-query/QueryEngineTest.cpp
+++ unittests/clang-query/QueryEngineTest.cpp
@@ -111,6 +111,19 @@
 
   Str.clear();
 
+  EXPECT_TRUE(EnableOutputQuery(&QuerySession::DiagOutput).run(OS, S));
+  EXPECT_TRUE(EnableOutputQuery(&QuerySession::DetailedASTOutput).run(OS, S));
+  EXPECT_TRUE(MatchQuery(FooMatcherString, FooMatcher).run(OS, S));
+
+  {
+auto Output = OS.str();
+EXPECT_TRUE(Output.find("FunctionDecl") != std::string::npos);
+EXPECT_TRUE(Output.find("foo.cc:1:1: note: \"root\" binds here") !=
+std::string::npos);
+  }
+
+  Str.clear();
+
   EXPECT_TRUE(SetQuery(&QuerySession::BindRoot, false).run(OS, S));
   EXPECT_TRUE(MatchQuery(FooMatcherString, FooMatcher).run(OS, S));
 
Index: clang-query/QueryParser.h
===
--- clang-query/QueryParser.h
+++ clang-query/QueryParser.h
@@ -44,7 +44,7 @@
   template  struct LexOrCompleteWord;
 
   QueryRef parseSetBool(bool QuerySession::*Var);
-  QueryRef parseSetOutputKind();
+  template  QueryRef parseSetOutputKind();
   QueryRef completeMatcherExpression();
 
   QueryRef endQuery(QueryRef Q);
Index: clang-query/QueryParser.cpp
===
--- clang-query/QueryParser.cpp
+++ clang-query/QueryParser.cpp
@@ -106,7 +106,7 @@
   return new SetQuery(Var, Value);
 }
 
-QueryRef QueryParser::parseSetOutputKind() {
+template  QueryRef QueryParser::parseSetOutputKind() {
   StringRef ValStr;
   unsigned OutKind = LexOrCompleteWord(this, ValStr)
  .Case("diag", OK_Diag)
@@ -122,11 +122,11 @@
 
   switch (OutKind) {
   case OK_DetailedAST:
-return new SetExclusiveOutputQuery(&QuerySession::DetailedASTOutput);
+return new QueryType(&QuerySession::DetailedASTOutput);
   case OK_Diag:
-return new SetExclusiveOutputQuery(&QuerySession::DiagOutput);
+return new QueryType(&QuerySession::DiagOutput);
   case OK_Print:
-return new SetExclusiveOutputQuery(&QuerySession::PrintOutput);
+ 

[PATCH] D53644: [clangd] workspace/symbol should be async, it reads from the index.

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

LGTM


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53644



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


[PATCH] D53644: [clangd] workspace/symbol should be async, it reads from the index.

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: unittests/clangd/TUSchedulerTests.cpp:541
+  std::atomic Counter(0);
+  S.run("add 1", [&] { Counter.fetch_add(1); });
+  S.run("add 2", [&] { Counter.fetch_add(2); });

NIT: maybe simplify to `++Counter`?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53644



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


[PATCH] D51429: [AArch64] Return Address Signing B Key Support

2018-10-25 Thread Oliver Stannard via Phabricator via cfe-commits
olista01 accepted this revision.
olista01 added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


https://reviews.llvm.org/D51429



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Great idea, this will definitely improve the UX of completion!

NIT: a typo in the change description: 'bas' should be 'base'.
Pedantic NIT (sorry!): in the change description, we should probably use 
'initializers' instead of 'initializations'




Comment at: lib/Sema/SemaCodeComplete.cpp:815
+std::vector
+ResultBuilder::GetConstructorResults(const CXXRecordDecl *Record, Result R) {
+  ASTContext &Context = SemaRef.Context;

Maybe add the ctor results directly to the result list without creating an 
intermediate vector?
See other comments about passing the field name to this function instead of 
replacing it in the resulting CCS afterwards.



Comment at: lib/Sema/SemaCodeComplete.cpp:5093
+
+  auto CreatePrimitiveConstructor = [&](StringRef Name) {
+Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Name));

NIT: maybe pass the Builder explicitly? Even a local function that changes the 
state and without explicit data-flow (i.e. without accepting the thing it 
changes as a parameter) is a bit confusing?



Comment at: lib/Sema/SemaCodeComplete.cpp:5101
+const auto *ND = Base.getType()->getAsCXXRecordDecl();
+if (isa(ND) ||
+isa(ND)) {

Why special-case the template specializations?
Are we trying to provide results for dependent types here?



Comment at: lib/Sema/SemaCodeComplete.cpp:5103
+isa(ND)) {
+  CreatePrimitiveConstructor(Base.getType().getAsString(Policy));
+  Results.AddResult(CodeCompletionResult(

It seems this function is sometimes responsible for building the completion 
string and sometimes it's the responsibility of the calling function.
Could we move this responsibility to one of the places (probably the callers?)



Comment at: lib/Sema/SemaCodeComplete.cpp:5168
+// constructor.
+if (const CXXRecordDecl *RD = Field->getType()->getAsCXXRecordDecl()) {
+  auto ConstResults = Results.GetConstructorResults(

NIT: use [[ 
https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code
 | early exits ]] to simplify code.
I.e.
```
// NOTE: Moved from the end of the loop.
SawLastInitializer = false;

const CXXRecordDecl *RD = Field->getType()->getAsCXXRecordDecl();
if (!RD) {
  CreatePrimitiveConstructor(Builder.getAllocator().CopyString(FieldName));
  AddField(Field);
  continue;
}
...



Comment at: lib/Sema/SemaCodeComplete.cpp:5169
+if (const CXXRecordDecl *RD = Field->getType()->getAsCXXRecordDecl()) {
+  auto ConstResults = Results.GetConstructorResults(
+  RD, CodeCompletionResult(Field, SawLastInitializer

NIT: the `ConstResults` name is a bit confusing, because "const" has a another 
meaning in C++. Maybe rename to CtorResults and ConstructorResults?



Comment at: lib/Sema/SemaCodeComplete.cpp:5177
+CodeCompletionContext::CCC_Symbol, Policy);
+for (auto C : *CCS) {
+  switch (C.Kind) {

Could we pass the field name all the way down to the function that creates the 
original CodeCompletionString? (Instead of replacing the ctor name with a field 
name at the end)
This would mean less copies/allocations going around and would also be simpler 
to reason about (i.e. no "incomplete" code completion strings would be passed 
around).



Comment at: lib/Sema/SemaCodeComplete.cpp:5194
+} else {
+  CreatePrimitiveConstructor(Builder.getAllocator().CopyString(FieldName));
+  AddField(Field);

Maybe show a type of the field for non-class types? They can typically be 
initialized from a single value of that type (with some exceptions, but showing 
the type shouldn't be confusing).
E.g. 
```
struct X {
  X() : ^ {} // could complete 'a({$1:int})`
  int a;
  int b;
};


Repository:
  rC Clang

https://reviews.llvm.org/D53654



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


[PATCH] D52695: [clang][Parse] Diagnose useless null statements (PR39111)

2018-10-25 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

ping


Repository:
  rC Clang

https://reviews.llvm.org/D52695



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


[PATCH] D51949: [clang-tidy] new check 'readability-isolate-declaration'

2018-10-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

ping :)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51949



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


[PATCH] D53651: [clangd] Use thread pool for background indexing.

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

It's fine to spend one thread spinning on background tasks, but if we're going 
to do a threadpool, we should be more careful to not hurt the performance of 
foreground tasks. To do that, we should at least:

- share the semaphore for the number of actively running tasks between 
TUScheduler and BackgroundIndex.
- prioritize foreground tasks over background tasks.

Ideally, probably outside the scope of this change, we should make the 
background tasks cancellable (or find another way to keep them from interfering 
with the foreground tasks) in addition to that and make sure the scheduling is 
aware of distinction between foreground and background tasks. (@sammcall 
suggested simply using thread priorities for that).
Another high-level comment is that we should probably use llvm::ThreadPool 
here, this would have give code reuse and would make `BackgroundIndex` more 
focused on the actual indexing part.




Comment at: clangd/index/Background.h:80
+  // Must be last, spawned thread reads instance vars.
+  llvm::SmallVector ThreadPool;
 };

Why not `std::vector`? Memory allocs won't ever be a bottleneck here.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53651



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


[PATCH] D53483: [analyzer] Restrict AnalyzerOptions' interface so that non-checker objects have to be registered

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171060.
Szelethus edited the summary of this revision.
Szelethus added a comment.

This diff has numerous changed to the last, but it's all "cosmetic", the actual 
logic is untouched.

- Added documentation as @xazax.hun suggested
- Removed `getIntegerOption`, `getBooleanOption`, which I realized were 
redundant with `getOption`. Left `getStringOption` in, which is now a private 
function.
- `getOption`, used internally to initialize config fields, was renamed to 
`initOption` and it's function changed accordingly (is now `void`).
- Moved the generated getter functions inline.
- (woohoo!) Realize that checker options do not modify the state of 
`AnalyzerOptions`, make them const.


https://reviews.llvm.org/D53483

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
  lib/StaticAnalyzer/Checkers/CloneChecker.cpp
  lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
  lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  lib/StaticAnalyzer/Checkers/NumberObjectConversionChecker.cpp
  lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
  lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
  lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp

Index: unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp
===
--- unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp
+++ unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp
@@ -52,23 +52,25 @@
   // Checker one has Option specified as true. It should read true regardless of
   // search mode.
   CheckerOneMock CheckerOne;
-  EXPECT_TRUE(Opts.getBooleanOption("Option", false, &CheckerOne));
+  EXPECT_TRUE(Opts.getCheckerBooleanOption("Option", false, &CheckerOne));
   // The package option is overridden with a checker option.
-  EXPECT_TRUE(Opts.getBooleanOption("Option", false, &CheckerOne, true));
+  EXPECT_TRUE(Opts.getCheckerBooleanOption("Option", false, &CheckerOne,
+   true));
   // The Outer package option is overridden by the Inner package option. No
   // package option is specified.
-  EXPECT_TRUE(Opts.getBooleanOption("Option2", false, &CheckerOne, true));
+  EXPECT_TRUE(Opts.getCheckerBooleanOption("Option2", false, &CheckerOne,
+   true));
   // No package option is specified and search in packages is turned off. The
   // default value should be returned.
-  EXPECT_FALSE(Opts.getBooleanOption("Option2", false, &CheckerOne));
-  EXPECT_TRUE(Opts.getBooleanOption("Option2", true, &CheckerOne));
+  EXPECT_FALSE(Opts.getCheckerBooleanOption("Option2", false, &CheckerOne));
+  EXPECT_TRUE(Opts.getCheckerBooleanOption("Option2", true, &CheckerOne));
 
   // Checker true has no option specified. It should get the default value when
   // search in parents turned off and false when search in parents turned on.
   CheckerTwoMock CheckerTwo;
-  EXPECT_FALSE(Opts.getBooleanOption("Option", false, &CheckerTwo));
-  EXPECT_TRUE(Opts.getBooleanOption("Option", true, &CheckerTwo));
-  EXPECT_FALSE(Opts.getBooleanOption("Option", true, &CheckerTwo, true));
+  EXPECT_FALSE(Opts.getCheckerBooleanOption("Option", false, &CheckerTwo));
+  EXPECT_TRUE(Opts.getCheckerBooleanOption("Option", true, &CheckerTwo));
+  EXPECT_FALSE(Opts.getCheckerBooleanOption("Option", true, &CheckerTwo, true));
 }
 
 TEST(StaticAnalyzerOptions, StringOptions) {
@@ -83,9 +85,9 @@
 
   CheckerOneMock CheckerOne;
   EXPECT_TRUE("StringValue" ==
-  Opts.getOptionAsString("Option", "DefaultValue", &CheckerOne));
+Opts.getCheckerStringOption("Option", "DefaultValue", &CheckerOne));
   EXPECT_TRUE("DefaultValue" ==
-  Opts.getOptionAsString("Option2", "DefaultValue", &CheckerOne));
+   Opts.getCheckerStringOption("Option2", "DefaultValue", &CheckerOne));
 }
 } // end namespace ento
 } // end namespace clang
Index: lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
===
--- lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
+++ lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
@@ -51,7 +51,7 @@
 
 UserModeKind AnalyzerOptions::getUserMode() {
   if (!UserMode.hasValue()) {
-UserMode = getOptionAsString("mode", "deep");
+UserMode = getStringOption("mode", "deep");
   }
 
   auto K = llvm::StringSwitch>(*UserMode)
@@ -65,7 +65,7 @@
 ExplorationStrategyKind
 AnalyzerOptions::getExplorationStrategy() {
   if (!ExplorationStrategy.hasValue()) {
-ExplorationStrategy = getOptionAsString("exploration_strategy",
+ExplorationStrategy = getStringOption("exploration_strategy",
   

[PATCH] D53483: [analyzer] Restrict AnalyzerOptions' interface so that non-checker objects have to be registered

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus marked 3 inline comments as done.
Szelethus added a comment.

Changing asserts to warnings will be delivered in a followup patch.


https://reviews.llvm.org/D53483



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


r345258 - [ms] Prevent explicit constructor name lookup if scope is missing

2018-10-25 Thread Will Wilson via cfe-commits
Author: lantictac
Date: Thu Oct 25 04:45:32 2018
New Revision: 345258

URL: http://llvm.org/viewvc/llvm-project?rev=345258&view=rev
Log:
[ms] Prevent explicit constructor name lookup if scope is missing

MicrosoftExt allows explicit constructor calls. Prevent lookup of constructor 
name unless the name has explicit scope.
This avoids a compile-time crash due to confusing a member access for a 
constructor name.

Test case included. All tests pass.

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

Modified:
cfe/trunk/lib/Parse/ParseExpr.cpp
cfe/trunk/test/SemaCXX/MicrosoftCompatibility.cpp

Modified: cfe/trunk/lib/Parse/ParseExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseExpr.cpp?rev=345258&r1=345257&r2=345258&view=diff
==
--- cfe/trunk/lib/Parse/ParseExpr.cpp (original)
+++ cfe/trunk/lib/Parse/ParseExpr.cpp Thu Oct 25 04:45:32 2018
@@ -1809,7 +1809,8 @@ Parser::ParsePostfixExpressionSuffix(Exp
 /*EnteringContext=*/false,
 /*AllowDestructorName=*/true,
 /*AllowConstructorName=*/
-  getLangOpts().MicrosoftExt,
+getLangOpts().MicrosoftExt &&
+SS.isNotEmpty(),
 /*AllowDeductionGuide=*/false,
 ObjectType, &TemplateKWLoc, Name)) {
 (void)Actions.CorrectDelayedTyposInExpr(LHS);

Modified: cfe/trunk/test/SemaCXX/MicrosoftCompatibility.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/MicrosoftCompatibility.cpp?rev=345258&r1=345257&r2=345258&view=diff
==
--- cfe/trunk/test/SemaCXX/MicrosoftCompatibility.cpp (original)
+++ cfe/trunk/test/SemaCXX/MicrosoftCompatibility.cpp Thu Oct 25 04:45:32 2018
@@ -302,3 +302,23 @@ void function_to_voidptr_conv() {
   void *a2 = &function_prototype; // expected-warning {{implicit conversion 
between pointer-to-function and pointer-to-object is a Microsoft extension}}
   void *a3 = function_ptr;// expected-warning {{implicit conversion 
between pointer-to-function and pointer-to-object is a Microsoft extension}}
 }
+
+namespace member_lookup {
+
+template
+struct ConfuseLookup {
+  T* m_val;
+  struct m_val {
+static size_t ms_test;
+  };
+};
+
+// Microsoft mode allows explicit constructor calls
+// This could confuse name lookup in cases such as this
+template
+size_t ConfuseLookup::m_val::ms_test
+  = size_t(&(char&)(reinterpret_cast*>(0)->m_val));
+
+void instantiate() { ConfuseLookup::m_val::ms_test = 1; }
+}
+


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


[PATCH] D53441: [ms] Prevent explicit constructor name lookup if scope is missing

2018-10-25 Thread Will Wilson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC345258: [ms] Prevent explicit constructor name lookup if 
scope is missing (authored by lantictac, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D53441

Files:
  lib/Parse/ParseExpr.cpp
  test/SemaCXX/MicrosoftCompatibility.cpp


Index: test/SemaCXX/MicrosoftCompatibility.cpp
===
--- test/SemaCXX/MicrosoftCompatibility.cpp
+++ test/SemaCXX/MicrosoftCompatibility.cpp
@@ -302,3 +302,23 @@
   void *a2 = &function_prototype; // expected-warning {{implicit conversion 
between pointer-to-function and pointer-to-object is a Microsoft extension}}
   void *a3 = function_ptr;// expected-warning {{implicit conversion 
between pointer-to-function and pointer-to-object is a Microsoft extension}}
 }
+
+namespace member_lookup {
+
+template
+struct ConfuseLookup {
+  T* m_val;
+  struct m_val {
+static size_t ms_test;
+  };
+};
+
+// Microsoft mode allows explicit constructor calls
+// This could confuse name lookup in cases such as this
+template
+size_t ConfuseLookup::m_val::ms_test
+  = size_t(&(char&)(reinterpret_cast*>(0)->m_val));
+
+void instantiate() { ConfuseLookup::m_val::ms_test = 1; }
+}
+
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -1809,7 +1809,8 @@
 /*EnteringContext=*/false,
 /*AllowDestructorName=*/true,
 /*AllowConstructorName=*/
-  getLangOpts().MicrosoftExt,
+getLangOpts().MicrosoftExt &&
+SS.isNotEmpty(),
 /*AllowDeductionGuide=*/false,
 ObjectType, &TemplateKWLoc, Name)) {
 (void)Actions.CorrectDelayedTyposInExpr(LHS);


Index: test/SemaCXX/MicrosoftCompatibility.cpp
===
--- test/SemaCXX/MicrosoftCompatibility.cpp
+++ test/SemaCXX/MicrosoftCompatibility.cpp
@@ -302,3 +302,23 @@
   void *a2 = &function_prototype; // expected-warning {{implicit conversion between pointer-to-function and pointer-to-object is a Microsoft extension}}
   void *a3 = function_ptr;// expected-warning {{implicit conversion between pointer-to-function and pointer-to-object is a Microsoft extension}}
 }
+
+namespace member_lookup {
+
+template
+struct ConfuseLookup {
+  T* m_val;
+  struct m_val {
+static size_t ms_test;
+  };
+};
+
+// Microsoft mode allows explicit constructor calls
+// This could confuse name lookup in cases such as this
+template
+size_t ConfuseLookup::m_val::ms_test
+  = size_t(&(char&)(reinterpret_cast*>(0)->m_val));
+
+void instantiate() { ConfuseLookup::m_val::ms_test = 1; }
+}
+
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -1809,7 +1809,8 @@
 /*EnteringContext=*/false,
 /*AllowDestructorName=*/true,
 /*AllowConstructorName=*/
-  getLangOpts().MicrosoftExt,
+getLangOpts().MicrosoftExt &&
+SS.isNotEmpty(),
 /*AllowDeductionGuide=*/false,
 ObjectType, &TemplateKWLoc, Name)) {
 (void)Actions.CorrectDelayedTyposInExpr(LHS);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52311: [clangd] Add support for hierarchical documentSymbol

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 171067.
ilya-biryukov added a comment.

- Improve traversal of the AST.
- Update the tests.
- Add a fallback to SymbolInformation (flat structure) if the client does not 
support the hierarhical reponse.

Still some work left to do:

- Do not drop the qualifiers for out-of-line declarations, i.e. 'X::foo' is 
presented as 'foo' now, which is a bit confusing.
- See why some names pop up at the global scope (GTest generates macros like 
that).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52311

Files:
  clangd/AST.cpp
  clangd/AST.h
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/FindSymbols.cpp
  clangd/FindSymbols.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/clients/clangd-vscode/package.json
  unittests/clangd/FindSymbolsTests.cpp
  unittests/clangd/SyncAPI.cpp
  unittests/clangd/SyncAPI.h

Index: unittests/clangd/SyncAPI.h
===
--- unittests/clangd/SyncAPI.h
+++ unittests/clangd/SyncAPI.h
@@ -47,7 +47,7 @@
 llvm::Expected>
 runWorkspaceSymbols(ClangdServer &Server, StringRef Query, int Limit);
 
-llvm::Expected>
+llvm::Expected>
 runDocumentSymbols(ClangdServer &Server, PathRef File);
 
 SymbolSlab runFuzzyFind(const SymbolIndex &Index, StringRef Query);
Index: unittests/clangd/SyncAPI.cpp
===
--- unittests/clangd/SyncAPI.cpp
+++ unittests/clangd/SyncAPI.cpp
@@ -119,9 +119,9 @@
   return std::move(*Result);
 }
 
-Expected>
+llvm::Expected>
 runDocumentSymbols(ClangdServer &Server, PathRef File) {
-  Optional>> Result;
+  llvm::Optional>> Result;
   Server.documentSymbols(File, capture(Result));
   return std::move(*Result);
 }
Index: unittests/clangd/FindSymbolsTests.cpp
===
--- unittests/clangd/FindSymbolsTests.cpp
+++ unittests/clangd/FindSymbolsTests.cpp
@@ -23,6 +23,7 @@
 using ::testing::AnyOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
+using ::testing::Field;
 using ::testing::IsEmpty;
 using ::testing::UnorderedElementsAre;
 
@@ -37,9 +38,22 @@
 return arg.name == Name;
   return (arg.containerName + "::" + arg.name) == Name;
 }
+MATCHER_P(WithName, N, "") { return arg.name == N; }
 MATCHER_P(WithKind, Kind, "") { return arg.kind == Kind; }
 MATCHER_P(SymRange, Range, "") { return arg.location.range == Range; }
 
+// GMock helpers for matching DocumentSymbol.
+MATCHER_P(SymNameRange, Range, "") { return arg.selectionRange == Range; }
+testing::Matcher
+Children(testing::Matcher> ChildrenM) {
+  return Field(&DocumentSymbol::children, ChildrenM);
+}
+template 
+testing::Matcher ChildrenAre(ChildMatchers... ChildrenM) {
+  return Children(ElementsAre(ChildrenM...));
+}
+testing::Matcher NoChildren() { return Children(IsEmpty()); }
+
 ClangdServer::Options optsForTests() {
   auto ServerOpts = ClangdServer::optsForTest();
   ServerOpts.WorkspaceRoot = testRoot();
@@ -301,7 +315,7 @@
   IgnoreDiagnostics DiagConsumer;
   ClangdServer Server;
 
-  std::vector getSymbols(PathRef File) {
+  std::vector getSymbols(PathRef File) {
 EXPECT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
 auto SymbolInfos = runDocumentSymbols(Server, File);
 EXPECT_TRUE(bool(SymbolInfos)) << "documentSymbols returned an error";
@@ -364,31 +378,49 @@
 )");
 
   addFile(FilePath, Main.code());
-  EXPECT_THAT(getSymbols(FilePath),
-  ElementsAreArray(
-  {AllOf(QName("Foo"), WithKind(SymbolKind::Class)),
-   AllOf(QName("Foo"), WithKind(SymbolKind::Class)),
-   AllOf(QName("Foo::Foo"), WithKind(SymbolKind::Method)),
-   AllOf(QName("Foo::Foo"), WithKind(SymbolKind::Method)),
-   AllOf(QName("Foo::f"), WithKind(SymbolKind::Method)),
-   AllOf(QName("f1"), WithKind(SymbolKind::Function)),
-   AllOf(QName("Foo::operator="), WithKind(SymbolKind::Method)),
-   AllOf(QName("Foo::~Foo"), WithKind(SymbolKind::Method)),
-   AllOf(QName("Foo::Nested"), WithKind(SymbolKind::Class)),
-   AllOf(QName("Foo::Nested::f"), WithKind(SymbolKind::Method)),
-   AllOf(QName("Friend"), WithKind(SymbolKind::Class)),
-   AllOf(QName("f1"), WithKind(SymbolKind::Function)),
-   AllOf(QName("f2"), WithKind(SymbolKind::Function)),
-   AllOf(QName("KInt"), WithKind(SymbolKind::Variable)),
-   AllOf(QName("kStr"), WithKind(SymbolKind::Variable)),
-   AllOf(QName("f1"), WithKind(SymbolKind::Function)),
-   AllOf(QName("foo"), WithKind(SymbolKind::Namespace)),
-   AllOf(QName("foo::int32"), WithKind(SymbolKind::Class)),
-   AllOf(QName("foo::int32_t"), WithKind(Symb

[PATCH] D53692: [analyzer] Evaluate all non-checker config options before analysis

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added reviewers: xazax.hun, NoQ, george.karpenkov, MTC, rnkovacs.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, mgrang, szepet, whisperity.
Szelethus added a dependency: D53483: [analyzer] Restrict AnalyzerOptions' 
interface so that non-checker objects have to be registered.

This patch contains very little logic but touches a lot of lines.

Now that we're confident that //all// non-checker configs are gathered, I went 
ahead and did some actual changes to how `AnalyzerOptions` works.

This patch is a proposal to evaluate all config options (and possibly emit 
warning about them) at the beginning of the analysis, rather then whenever a 
getter function is called for it. This is done by changing the generated 
`Optional` fields' accessibility to public, evaluating all options as 
soon as the `ConfigTable` is assembled, and removing generated getters, as are 
they are no longer necessary. Now, every single public function (except 
`parseConfigs`) is const, as should `AnalyzerOptions` be after options are 
parsed (coming soon™ in a followup patch).

One important thing to notice is that the `ConfigTable` is no longer modified 
once received, so I needed to update `debug.ConfigDumper` accordingly.

The removal of those getters implied however that every single use of those 
getters had to be changed (`Opts.shouldDoThat()` -> 
`Opts.ShouldDoThat.getValue()`), and I got to simplify the def file. I 
clang-formatted it, and since I don't expect the format to change for a good 
long while, I think it should be clang-formatted in the future whenever.

Also coming soon™, the actual implementation of warnings.


Repository:
  rC Clang

https://reviews.llvm.org/D53692

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/Frontend/CompilerInvocation.cpp
  lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
  lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  lib/StaticAnalyzer/Core/CallEvent.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  lib/StaticAnalyzer/Core/RegionStore.cpp
  lib/StaticAnalyzer/Core/SValBuilder.cpp
  lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp

Index: test/Analysis/analyzer-config.cpp
===
--- test/Analysis/analyzer-config.cpp
+++ test/Analysis/analyzer-config.cpp
@@ -19,6 +19,9 @@
 };
 
 // CHECK: [config]
+// CHECK-NEXT: aggressive-binary-operation-simplification = false
+// CHECK-NEXT: avoid-suppressing-null-argument-paths = false
+// CHECK-NEXT: c++-allocator-inlining = true
 // CHECK-NEXT: c++-container-inlining = false
 // CHECK-NEXT: c++-inlining = destructors
 // CHECK-NEXT: c++-shared_ptr-inlining = false
@@ -32,6 +35,9 @@
 // CHECK-NEXT: cfg-rich-constructors = true
 // CHECK-NEXT: cfg-scopes = false
 // CHECK-NEXT: cfg-temporary-dtors = true
+// CHECK-NEXT: crosscheck-with-z3 = false
+// CHECK-NEXT: ctu-dir = ""
+// CHECK-NEXT: ctu-index-name = externalFnMap.txt
 // CHECK-NEXT: eagerly-assume = true
 // CHECK-NEXT: elide-constructors = true
 // CHECK-NEXT: experimental-enable-naive-ctu-analysis = false
@@ -43,12 +49,22 @@
 // CHECK-NEXT: ipa-always-inline-size = 3
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
+// CHECK-NEXT: max-symbol-complexity = 35
 // CHECK-NEXT: max-times-inline-large = 32
 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14
 // CHECK-NEXT: mode = deep
+// CHECK-NEXT: model-path = ""
+// CHECK-NEXT: notes-as-events = false
+// CHECK-NEXT: objc-inlining = true
+// CHECK-NEXT: prune-paths = true
 // CHECK-NEXT: region-store-small-struct-limit = 2
+// CHECK-NEXT: report-in-main-source-file = false
 // CHECK-NEXT: serialize-stats = false
+// CHECK-NEXT: stable-report-filename = false
+// CHECK-NEXT: suppress-c++-stdlib = true
+// CHECK-NEXT: suppress-inlined-defensive-checks = true
+// CHECK-NEXT: suppress-null-return-paths = true
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 31
+// CHECK-NEXT: num-entries = 47
Index: test/Analysis/analyzer-config.c
===
--- test/Analysis/analyzer-config.c
+++ test/Analysis/analyzer-config.c
@@ -11,29 +11,52 @@
 }
 
 // CHECK: [config]
+// CHECK-NEXT: aggressive-binary-operation-simplification = false
+// CHECK-NEXT: avo

[PATCH] D53693: [ASTImporter] Typedef import brings in the complete type

2018-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, Szelethus, dkrupp, rnkovacs.
Herald added a reviewer: a.sidorin.

When we already have an incomplete underlying type of a typedef in the
"To" context, and the "From" context has the same typedef, but the
underlying type is complete, then the imported type should be complete.

Fixes an assertion in Xerces:
Assertion `DD && "queried property of class with no definition"' failed.
This assert is happening in the analyzer engine, because that attempts
to query an underlying type of a typedef, which happens to be
incomplete.


Repository:
  rC Clang

https://reviews.llvm.org/D53693

Files:
  lib/AST/ASTImporter.cpp
  unittests/AST/ASTImporterTest.cpp


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3726,6 +3726,38 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase, ImportingTypedefShouldImportTheCompleteType) {
+  // We already have an incomplete underlying type in the "To" context.
+  auto Code =
+  R"(
+  template 
+  struct S {
+void foo();
+  };
+  using U = S;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
+  auto *ToD = FirstDeclMatcher().match(ToTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType());
+
+  // The "From" context has the same typedef, but the underlying type is
+  // complete this time.
+  Decl *FromTU = getTuDecl(std::string(Code) +
+  R"(
+  void foo(U* u) {
+u->foo();
+  }
+  )", Lang_CXX11);
+  auto *FromD = FirstDeclMatcher().match(FromTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType());
+
+  // The imported type should be complete.
+  auto *ImportedD = cast(Import(FromD, Lang_CXX11));
+  EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType());
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2306,8 +2306,14 @@
 continue;
   if (auto *FoundTypedef = dyn_cast(FoundDecl)) {
 if (Importer.IsStructurallyEquivalent(
-D->getUnderlyingType(), FoundTypedef->getUnderlyingType()))
+D->getUnderlyingType(), FoundTypedef->getUnderlyingType())) {
+  QualType FromUT = D->getUnderlyingType();
+  QualType FoundUT = FoundTypedef->getUnderlyingType();
+  // If the "From" context has a complete underlying type but we
+  // already have a complete underlying type then return with that.
+  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
 return Importer.MapImported(D, FoundTypedef);
+}
   }
 
   ConflictingDecls.push_back(FoundDecl);


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3726,6 +3726,38 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase, ImportingTypedefShouldImportTheCompleteType) {
+  // We already have an incomplete underlying type in the "To" context.
+  auto Code =
+  R"(
+  template 
+  struct S {
+void foo();
+  };
+  using U = S;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
+  auto *ToD = FirstDeclMatcher().match(ToTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType());
+
+  // The "From" context has the same typedef, but the underlying type is
+  // complete this time.
+  Decl *FromTU = getTuDecl(std::string(Code) +
+  R"(
+  void foo(U* u) {
+u->foo();
+  }
+  )", Lang_CXX11);
+  auto *FromD = FirstDeclMatcher().match(FromTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType());
+
+  // The imported type should be complete.
+  auto *ImportedD = cast(Import(FromD, Lang_CXX11));
+  EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType());
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2306,8 +2306,14 @@
 continue;
   if (auto *FoundTypedef = dyn_cast(FoundDecl)) {
 if (Importer.IsStructurallyEquivalent(
-D->getUnderlyingType(), FoundTypedef->getUnderlyingType()))
+D->getUnderlyingType(), FoundTypedef->getUnderlyingType())) {
+  QualType FromUT = 

[PATCH] D53687: [clangd] Make in-memory CDB always available as an overlay, refactor.

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

FWIW, the old implementation of the CDB looked simpler (which makes sense, 
since it only allowed the in-memory compile commands, but the new 
implementation also falls back to the base CDB, i.e. it's now doing two things).
However, if we can't avoid this protocol extension, the change LG and the model 
behind it should hopefully make sense from the user's perspective.
Still not sure whether overriding the normal command (not the fallback command) 
when we also read from the CDB is a useful feature.




Comment at: clangd/ClangdLSPServer.cpp:670
+  /*Output=*/"");
+  if (Old != New)
+CDB->setCompileCommand(File, std::move(New));

Is this an optimization to not trigger compile command changes?
Can we perform it on the CDB level to make sure we hit it in the future if more 
code calling `setCompileCommand` is added?



Comment at: clangd/ClangdLSPServer.h:42
   ClangdLSPServer(Transport &Transp, const clangd::CodeCompleteOptions &CCOpts,
-  llvm::Optional CompileCommandsDir,
-  bool ShouldUseInMemoryCDB, const ClangdServer::Options 
&Opts);
+  llvm::Optional CompileCommandsDir, bool NoReadCDB,
+  const ClangdServer::Options &Opts);

NIT: the negative variable names might cause confusion (i.e. the double 
negations are hard to read). Maybe use the name of the corresponding field 
(UseDirectoryCDB)?



Comment at: clangd/ClangdLSPServer.h:139
+  llvm::Optional CDB;
+  std::unique_ptr BaseCDB;
   // The ClangdServer is created by the "initialize" LSP method.

Maybe add a comment on how the two compilation databases are combined?



Comment at: clangd/GlobalCompilationDatabase.h:79
+/// using an in-memory mapping.
+class OverlayCDB : public GlobalCompilationDatabase {
 public:

The name does not seem to fully capture what this class does, i.e. allowing to 
override compile commands for some files.
Maybe use `OverridenCDB` or something similar?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53687



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


[PATCH] D53688: [clangd] Add fallbackFlags initialization extension.

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This feels like a configuration option that might be changed in the course of 
running clangd.
Are there any strong reasons to make it work only upon initialization? My guess 
is that it keeps the code simpler, but if we approached it purely from the UX 
perspective, changing it while running clangd seems to make sense. WDYT?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53688



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


[PATCH] D52311: [clangd] Add support for hierarchical documentSymbol

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Another annoyance to fix:

- 'using namespace' are shown as ''


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52311



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


[PATCH] D53696: [Haiku] Support __float128 for Haiku x86 and x86_64

2018-10-25 Thread Calvin Hill via Phabricator via cfe-commits
return created this revision.
return added reviewers: chandlerc, joerg.
return added a project: clang.
Herald added a subscriber: cfe-commits.

This patch addresses a compilation error with clang when running in Haiku being 
unable to compile code using  __float128 (throws compilation error such as  
'__float128 is not supported on this target').


Repository:
  rC Clang

https://reviews.llvm.org/D53696

Files:
  lib/Basic/Targets/OSTargets.h
  test/CodeGenCXX/float128-declarations.cpp


Index: test/CodeGenCXX/float128-declarations.cpp
===
--- test/CodeGenCXX/float128-declarations.cpp
+++ test/CodeGenCXX/float128-declarations.cpp
@@ -16,6 +16,10 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-pc-solaris2.11 -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple i586-pc-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86 and different calling
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -257,6 +257,10 @@
 Builder.defineMacro("__HAIKU__");
 Builder.defineMacro("__ELF__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128) {
+  Builder.defineMacro("__FLOAT128__");
+  Builder.defineMacro("_GLIBCXX_USE_FLOAT128");
+}
   }
 
 public:
@@ -267,6 +271,14 @@
 this->PtrDiffType = TargetInfo::SignedLong;
 this->ProcessIDType = TargetInfo::SignedLong;
 this->TLSSupported = false;
+switch (Triple.getArch()) {
+default:
+  break;
+case llvm::Triple::x86:
+case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
+  break;
+}
   }
 };
 


Index: test/CodeGenCXX/float128-declarations.cpp
===
--- test/CodeGenCXX/float128-declarations.cpp
+++ test/CodeGenCXX/float128-declarations.cpp
@@ -16,6 +16,10 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-pc-solaris2.11 -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple i586-pc-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86 and different calling
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -257,6 +257,10 @@
 Builder.defineMacro("__HAIKU__");
 Builder.defineMacro("__ELF__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128) {
+  Builder.defineMacro("__FLOAT128__");
+  Builder.defineMacro("_GLIBCXX_USE_FLOAT128");
+}
   }
 
 public:
@@ -267,6 +271,14 @@
 this->PtrDiffType = TargetInfo::SignedLong;
 this->ProcessIDType = TargetInfo::SignedLong;
 this->TLSSupported = false;
+switch (Triple.getArch()) {
+default:
+  break;
+case llvm::Triple::x86:
+case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
+  break;
+}
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53692: [analyzer] Evaluate all non-checker config options before analysis

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

The reason why I removed the getter functions and went ahead with the gigantic 
refactor is that getter functions actually changed the state of 
`AnalyzerOptions`, as they were responsible with the initialization of each 
option. Now, in the .def file, not all options had getter functions, so I 
couldn't just get away with calling every getter function once. Besides, a 
separate identifier for a field name (`NAME`) and getter function name 
(`CREATE_FN`) didn't make much sense anyways.




Comment at: lib/StaticAnalyzer/Core/AnalyzerOptions.cpp:227
-CTUDir = getStringOption("ctu-dir", "");
-if (!llvm::sys::fs::is_directory(*CTUDir))
-  CTUDir = "";

This check should and will be moved to `parseConfigs` in a followup patch.


Repository:
  rC Clang

https://reviews.llvm.org/D53692



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


[PATCH] D53697: [Structural Eq] Check for isBeingDefined

2018-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, Szelethus, dkrupp, rnkovacs.
martong added a dependency: D53693: [ASTImporter] Typedef import brings in the 
complete type.

If one definition is currently being defined, we do not compare for
equality and we assume that the decls are equal.


Repository:
  rC Clang

https://reviews.llvm.org/D53697

Files:
  lib/AST/ASTStructuralEquivalence.cpp
  unittests/AST/ASTImporterTest.cpp

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3726,6 +3726,77 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase, ImportingTypedefShouldImportTheCompleteType) {
+  // We already have an incomplete underlying type in the "To" context.
+  auto Code =
+  R"(
+  template 
+  struct S {
+void foo();
+  };
+  using U = S;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
+  auto *ToD = FirstDeclMatcher().match(ToTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType());
+
+  // The "From" context has the same typedef, but the underlying type is
+  // complete this time.
+  Decl *FromTU = getTuDecl(std::string(Code) +
+  R"(
+  void foo(U* u) {
+u->foo();
+  }
+  )", Lang_CXX11);
+  auto *FromD = FirstDeclMatcher().match(FromTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType());
+
+  // The imported type should be complete.
+  auto *ImportedD = cast(Import(FromD, Lang_CXX11));
+  EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType());
+}
+
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTStructuralEquivalence.cpp
===
--- lib/AST/ASTStructuralEquivalence.cpp
+++ lib/AST/ASTStructuralEquivalence.cpp
@@ -1016,7 +1016,8 @@
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that the decls are equal.
+  if (D1->isBeingDefined() || D2->isBeingDefined())
+return true;
+
   if (auto *D1CXX = dyn_cast(D1)) {
 if (auto *D2CXX = dyn_cast(D2)) {
   if (D1CXX->hasExternalLexicalStorage() &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:5101
+const auto *ND = Base.getType()->getAsCXXRecordDecl();
+if (isa(ND) ||
+isa(ND)) {

ilya-biryukov wrote:
> Why special-case the template specializations?
> Are we trying to provide results for dependent types here?
Sorry, my bad forgot to add a comment. It is rather for backward compatibility. 
Since previous version was adding results directly without consulting results, 
it also added template specializations, whereas current version can't add them 
due to the filtering in 
resultbuilder(https://github.com/llvm-mirror/clang/blob/master/lib/Sema/SemaCodeComplete.cpp#L543).
 So, special casing in here to make sure we still provide those results, but 
can be deleted if seems unimportant.

Not adding a comment until we decide on keeping/deleting the special case.


Repository:
  rC Clang

https://reviews.llvm.org/D53654



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:5101
+const auto *ND = Base.getType()->getAsCXXRecordDecl();
+if (isa(ND) ||
+isa(ND)) {

kadircet wrote:
> ilya-biryukov wrote:
> > Why special-case the template specializations?
> > Are we trying to provide results for dependent types here?
> Sorry, my bad forgot to add a comment. It is rather for backward 
> compatibility. Since previous version was adding results directly without 
> consulting results, it also added template specializations, whereas current 
> version can't add them due to the filtering in 
> resultbuilder(https://github.com/llvm-mirror/clang/blob/master/lib/Sema/SemaCodeComplete.cpp#L543).
>  So, special casing in here to make sure we still provide those results, but 
> can be deleted if seems unimportant.
> 
> Not adding a comment until we decide on keeping/deleting the special case.
without consulting results -> without consulting "ResultBuilder"


Repository:
  rC Clang

https://reviews.llvm.org/D53654



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:5101
+const auto *ND = Base.getType()->getAsCXXRecordDecl();
+if (isa(ND) ||
+isa(ND)) {

kadircet wrote:
> kadircet wrote:
> > ilya-biryukov wrote:
> > > Why special-case the template specializations?
> > > Are we trying to provide results for dependent types here?
> > Sorry, my bad forgot to add a comment. It is rather for backward 
> > compatibility. Since previous version was adding results directly without 
> > consulting results, it also added template specializations, whereas current 
> > version can't add them due to the filtering in 
> > resultbuilder(https://github.com/llvm-mirror/clang/blob/master/lib/Sema/SemaCodeComplete.cpp#L543).
> >  So, special casing in here to make sure we still provide those results, 
> > but can be deleted if seems unimportant.
> > 
> > Not adding a comment until we decide on keeping/deleting the special case.
> without consulting results -> without consulting "ResultBuilder"
Maybe call AddResult instead of MaybeAddResult (it does not do the checking)? 
I can hardly see why we might want to filter out any of the results.

Also, maybe pass a decl the particular constructor, rather than the 
CXXRecordDecl to the `ResultBuilder`?


Repository:
  rC Clang

https://reviews.llvm.org/D53654



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 171077.
kadircet marked 7 inline comments as done.
kadircet added a comment.

- Address comments.


Repository:
  rC Clang

https://reviews.llvm.org/D53654

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/ctor-initializer.cpp
  test/Index/complete-ctor-inits.cpp
  test/Index/complete-cxx-inline-methods.cpp

Index: test/Index/complete-cxx-inline-methods.cpp
===
--- test/Index/complete-cxx-inline-methods.cpp
+++ test/Index/complete-cxx-inline-methods.cpp
@@ -35,10 +35,10 @@
 // CHECK-NEXT: Container Kind: StructDecl
 
 // RUN: c-index-test -code-completion-at=%s:18:41 %s | FileCheck -check-prefix=CHECK-CTOR-INIT %s
-// CHECK-CTOR-INIT: NotImplemented:{TypedText MyCls}{LeftParen (}{Placeholder args}{RightParen )} (7)
-// CHECK-CTOR-INIT: MemberRef:{TypedText object}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CTOR-INIT: MemberRef:{TypedText value}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CTOR-INIT: ClassDecl:{TypedText MyCls} (7)
+// CHECK-CTOR-INIT: MemberRef:{TypedText object}{LeftParen (}{Placeholder MyCls *}{RightParen )} (35)
+// CHECK-CTOR-INIT: MemberRef:{TypedText value}{LeftParen (}{Placeholder int}{RightParen )} (35)
 // RUN: c-index-test -code-completion-at=%s:18:55 %s | FileCheck -check-prefix=CHECK-CTOR-INIT-2 %s
-// CHECK-CTOR-INIT-2-NOT: NotImplemented:{TypedText MyCls}{LeftParen (}{Placeholder args}{RightParen )}
-// CHECK-CTOR-INIT-2: MemberRef:{TypedText object}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CTOR-INIT-2: MemberRef:{TypedText value}{LeftParen (}{Placeholder args}{RightParen )} (7)
+// CHECK-CTOR-INIT-2-NOT: ClassDecl:{TypedText MyCls} (7)
+// CHECK-CTOR-INIT-2: MemberRef:{TypedText object}{LeftParen (}{Placeholder MyCls *}{RightParen )} (35)
+// CHECK-CTOR-INIT-2: MemberRef:{TypedText value}{LeftParen (}{Placeholder int}{RightParen )} (35)
Index: test/Index/complete-ctor-inits.cpp
===
--- test/Index/complete-ctor-inits.cpp
+++ test/Index/complete-ctor-inits.cpp
@@ -30,27 +30,33 @@
 };
 
 // RUN: c-index-test -code-completion-at=%s:18:10 %s | FileCheck -check-prefix=CHECK-CC1 %s
-// CHECK-CC1: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: MemberRef:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CC1: MemberRef:{TypedText a}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: MemberRef:{TypedText b}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: MemberRef:{TypedText c}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder const Virt &}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder Virt &&}{RightParen )} (35)
 // CHECK-CC1: NotImplemented:{TypedText X}{LeftParen (}{Placeholder args}{RightParen )} (7)
-// CHECK-CC1: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder const Y &}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder Y &&}{RightParen )} (35)
 
 // RUN: c-index-test -code-completion-at=%s:18:23 %s | FileCheck -check-prefix=CHECK-CC2 %s
-// CHECK-CC2: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: MemberRef:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (7)
+// CHECK-CC2: MemberRef:{TypedText a}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: MemberRef:{TypedText b}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: MemberRef:{TypedText c}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder const Virt &}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder Virt &&}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder const Y &}{RightParen )} (7)
+// CHECK-CC2: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder Y &&}{RightParen )} (7)
 
 // RUN: c-index-test -code-completion-at=%s:18:36 %s | FileCheck -check-prefix=CHECK-CC3 %s
-// CHECK-CC3: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC3-NOT: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{

[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 171081.
gtbercea added a comment.

  Refactor chunk one checking.


Repository:
  rC Clang

https://reviews.llvm.org/D53448

Files:
  include/clang/AST/StmtOpenMP.h
  lib/AST/StmtOpenMP.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/OpenMP/distribute_parallel_for_codegen.cpp
  test/OpenMP/distribute_parallel_for_simd_codegen.cpp

Index: test/OpenMP/distribute_parallel_for_simd_codegen.cpp
===
--- test/OpenMP/distribute_parallel_for_simd_codegen.cpp
+++ test/OpenMP/distribute_parallel_for_simd_codegen.cpp
@@ -406,18 +406,16 @@
   a[i] = b[i] + c[i];
   // LAMBDA: define{{.+}} void [[OMP_OUTLINED_3]](
   // LAMBDA-DAG: [[OMP_IV:%.omp.iv]] = alloca
+  // LAMBDA-DAG: [[OMP_CAPT_EXPR:%.capture_expr.1]] = alloca
   // LAMBDA-DAG: [[OMP_LB:%.omp.comb.lb]] = alloca
   // LAMBDA-DAG: [[OMP_UB:%.omp.comb.ub]] = alloca
   // LAMBDA-DAG: [[OMP_ST:%.omp.stride]] = alloca
 
-  // unlike the previous tests, in this one we have a outer and inner loop for 'distribute'
   // LAMBDA: call void @__kmpc_for_static_init_4({{.+}}, {{.+}}, i32 91,
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER:.+]]
 
-  // LAMBDA: [[DIST_OUTER_LOOP_HEADER]]:
   // check EUB for distribute
   // LAMBDA-DAG: [[OMP_UB_VAL_1:%.+]] = load{{.+}} [[OMP_UB]],
-  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}},
+  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}} [[OMP_CAPT_EXPR]],
   // LAMBDA-DAG: [[CMP_UB_NUM_IT:%.+]] = icmp sgt {{.+}}  [[OMP_UB_VAL_1]], [[NUM_IT_1]]
   // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT]], label %[[EUB_TRUE:.+]], label %[[EUB_FALSE:.+]]
   // LAMBDA-DAG: [[EUB_TRUE]]:
@@ -436,18 +434,9 @@
 
   // check exit condition
   // LAMBDA-DAG: [[OMP_IV_VAL_1:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_UB]],
+  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_CAPT_EXPR]],
   // LAMBDA: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], [[OMP_UB_VAL_3]]
-  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_OUTER_LOOP_BODY:.+]], label %[[DIST_OUTER_LOOP_END:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_BODY]]:
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER:.+]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_HEADER]]:
-  // LAMBDA-DAG: [[OMP_IV_VAL_2:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_4:%.+]] = load {{.+}} [[OMP_UB]],
-  // LAMBDA: [[CMP_IV_UB_2:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_2]], [[OMP_UB_VAL_4]]
-  // LAMBDA: br{{.+}} [[CMP_IV_UB_2]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
+  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
 
   // check that PrevLB and PrevUB are passed to the 'for'
   // LAMBDA: [[DIST_INNER_LOOP_BODY]]:
@@ -466,25 +455,39 @@
   // LAMBDA-DAG: [[OMP_ST_VAL_1:%.+]] = load {{.+}}, {{.+}}* [[OMP_ST]],
   // LAMBDA: [[OMP_IV_INC:%.+]] = add{{.+}} [[OMP_IV_VAL_3]], [[OMP_ST_VAL_1]]
   // LAMBDA: store{{.+}} [[OMP_IV_INC]], {{.+}}* [[OMP_IV]],
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_END]]:
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_INC:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_INC]]:
-  // check NextLB and NextUB
   // LAMBDA-DAG: [[OMP_LB_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_LB_NEXT:%.+]] = add{{.+}} [[OMP_LB_VAL_2]], [[OMP_ST_VAL_2]]
   // LAMBDA: store{{.+}} [[OMP_LB_NEXT]], {{.+}}* [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_UB_VAL_5:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_3:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_UB_NEXT:%.+]] = add{{.+}} [[OMP_UB_VAL_5]], [[OMP_ST_VAL_3]]
   // LAMBDA: store{{.+}} [[OMP_UB_NEXT]], {{.+}}* [[OMP_UB]],
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER]]
 
-  // outer loop exit
-  // LAMBDA: [[DIST_OUTER_LOOP_END]]:
+  // Update UB
+  // LAMBDA-DAG: [[OMP_UB_VAL_6:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
+  // LAMBDA: [[OMP_EXPR_VAL:%.+]] = load{{.+}}, {{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA-DAG: [[CMP_UB_NUM_IT_1:%.+]] = icmp sgt {{.+}}[[OMP_UB_VAL_6]], [[OMP_EXPR_VAL]]
+  // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT_1]], label %[[EUB_TRUE_1:.+]], label %[[EUB_FALSE_1:.+]]
+  // LAMBDA-DAG: [[EUB_TRUE_1]]:
+  // LAMBDA: [[NUM_IT_3:%.+]] = load{{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA: br label %[[EUB_END_1:.+]]
+  // LAMBDA-DAG: [[EUB_FALSE_1]]:
+  // LAMBDA: [[OMP_UB_VAL3:%.+]] = load{{.+}} [[OM

[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 171084.
gtbercea marked an inline comment as done.
gtbercea added a comment.

Use NumIterations.


Repository:
  rC Clang

https://reviews.llvm.org/D53448

Files:
  include/clang/AST/StmtOpenMP.h
  lib/AST/StmtOpenMP.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/OpenMP/distribute_parallel_for_codegen.cpp
  test/OpenMP/distribute_parallel_for_simd_codegen.cpp

Index: test/OpenMP/distribute_parallel_for_simd_codegen.cpp
===
--- test/OpenMP/distribute_parallel_for_simd_codegen.cpp
+++ test/OpenMP/distribute_parallel_for_simd_codegen.cpp
@@ -406,18 +406,16 @@
   a[i] = b[i] + c[i];
   // LAMBDA: define{{.+}} void [[OMP_OUTLINED_3]](
   // LAMBDA-DAG: [[OMP_IV:%.omp.iv]] = alloca
+  // LAMBDA-DAG: [[OMP_CAPT_EXPR:%.capture_expr.1]] = alloca
   // LAMBDA-DAG: [[OMP_LB:%.omp.comb.lb]] = alloca
   // LAMBDA-DAG: [[OMP_UB:%.omp.comb.ub]] = alloca
   // LAMBDA-DAG: [[OMP_ST:%.omp.stride]] = alloca
 
-  // unlike the previous tests, in this one we have a outer and inner loop for 'distribute'
   // LAMBDA: call void @__kmpc_for_static_init_4({{.+}}, {{.+}}, i32 91,
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER:.+]]
 
-  // LAMBDA: [[DIST_OUTER_LOOP_HEADER]]:
   // check EUB for distribute
   // LAMBDA-DAG: [[OMP_UB_VAL_1:%.+]] = load{{.+}} [[OMP_UB]],
-  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}},
+  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}} [[OMP_CAPT_EXPR]],
   // LAMBDA-DAG: [[CMP_UB_NUM_IT:%.+]] = icmp sgt {{.+}}  [[OMP_UB_VAL_1]], [[NUM_IT_1]]
   // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT]], label %[[EUB_TRUE:.+]], label %[[EUB_FALSE:.+]]
   // LAMBDA-DAG: [[EUB_TRUE]]:
@@ -436,18 +434,9 @@
 
   // check exit condition
   // LAMBDA-DAG: [[OMP_IV_VAL_1:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_UB]],
+  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_CAPT_EXPR]],
   // LAMBDA: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], [[OMP_UB_VAL_3]]
-  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_OUTER_LOOP_BODY:.+]], label %[[DIST_OUTER_LOOP_END:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_BODY]]:
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER:.+]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_HEADER]]:
-  // LAMBDA-DAG: [[OMP_IV_VAL_2:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_4:%.+]] = load {{.+}} [[OMP_UB]],
-  // LAMBDA: [[CMP_IV_UB_2:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_2]], [[OMP_UB_VAL_4]]
-  // LAMBDA: br{{.+}} [[CMP_IV_UB_2]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
+  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
 
   // check that PrevLB and PrevUB are passed to the 'for'
   // LAMBDA: [[DIST_INNER_LOOP_BODY]]:
@@ -466,25 +455,39 @@
   // LAMBDA-DAG: [[OMP_ST_VAL_1:%.+]] = load {{.+}}, {{.+}}* [[OMP_ST]],
   // LAMBDA: [[OMP_IV_INC:%.+]] = add{{.+}} [[OMP_IV_VAL_3]], [[OMP_ST_VAL_1]]
   // LAMBDA: store{{.+}} [[OMP_IV_INC]], {{.+}}* [[OMP_IV]],
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_END]]:
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_INC:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_INC]]:
-  // check NextLB and NextUB
   // LAMBDA-DAG: [[OMP_LB_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_LB_NEXT:%.+]] = add{{.+}} [[OMP_LB_VAL_2]], [[OMP_ST_VAL_2]]
   // LAMBDA: store{{.+}} [[OMP_LB_NEXT]], {{.+}}* [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_UB_VAL_5:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_3:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_UB_NEXT:%.+]] = add{{.+}} [[OMP_UB_VAL_5]], [[OMP_ST_VAL_3]]
   // LAMBDA: store{{.+}} [[OMP_UB_NEXT]], {{.+}}* [[OMP_UB]],
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER]]
 
-  // outer loop exit
-  // LAMBDA: [[DIST_OUTER_LOOP_END]]:
+  // Update UB
+  // LAMBDA-DAG: [[OMP_UB_VAL_6:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
+  // LAMBDA: [[OMP_EXPR_VAL:%.+]] = load{{.+}}, {{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA-DAG: [[CMP_UB_NUM_IT_1:%.+]] = icmp sgt {{.+}}[[OMP_UB_VAL_6]], [[OMP_EXPR_VAL]]
+  // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT_1]], label %[[EUB_TRUE_1:.+]], label %[[EUB_FALSE_1:.+]]
+  // LAMBDA-DAG: [[EUB_TRUE_1]]:
+  // LAMBDA: [[NUM_IT_3:%.+]] = load{{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA: br label %[[EUB_END_1:.+]]
+  // LAMBDA-DAG: [[EUB_FALSE_1]]:
+  // LAMBDA: [[OMP_

[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea marked 3 inline comments as done.
gtbercea added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.h:904
+  ///
+  virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind,
+   bool Chunked) const;

ABataev wrote:
> I'd rename this into `isDistStaticChunked`
I've used the same naming convention as the isStaticNonchunked function for 
consistency.


Repository:
  rC Clang

https://reviews.llvm.org/D53448



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


[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.h:904
+  ///
+  virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind,
+   bool Chunked) const;

gtbercea wrote:
> ABataev wrote:
> > I'd rename this into `isDistStaticChunked`
> I've used the same naming convention as the isStaticNonchunked function for 
> consistency.
What about this?



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:2360
 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
+  } else if (RT.isStaticChunked(ScheduleKind.Schedule,
+/* Chunked */ Chunk != nullptr) &&

ABataev wrote:
> This whole code is very similar to the unchunked case. Could you merge it?
What about this?



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:3421
 RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
+  } else if (RT.isStaticChunked(ScheduleKind,
+/* Chunked */ Chunk != nullptr) &&

ABataev wrote:
> Again, very similar to the unchunked code. Merge it.
?



Comment at: lib/Sema/SemaOpenMP.cpp:5207
+CombDistCond =
+SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), 
LastIteration.get());
+  }

ABataev wrote:
> Seems to me, you need to use `NumIterations` instead of `LastIteration`
Add the tests for the collapsed loops.


Repository:
  rC Clang

https://reviews.llvm.org/D53448



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


[PATCH] D53699: [ASTImporter] Fix inequality of functions with different attributes

2018-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, Szelethus, dkrupp, rnkovacs.
Herald added a reviewer: a.sidorin.

FunctionType::ExtInfo holds such properties of a function which are needed
mostly for code gen. We should not compare these bits when checking for
structural equivalency.
Checking ExtInfo caused false ODR errors during CTU analysis (of tmux).


Repository:
  rC Clang

https://reviews.llvm.org/D53699

Files:
  lib/AST/ASTStructuralEquivalence.cpp
  unittests/AST/StructuralEquivalenceTest.cpp


Index: unittests/AST/StructuralEquivalenceTest.cpp
===
--- unittests/AST/StructuralEquivalenceTest.cpp
+++ unittests/AST/StructuralEquivalenceTest.cpp
@@ -370,6 +370,15 @@
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+TEST_F(StructuralEquivalenceFunctionTest,
+FunctionsWithDifferentAttributesButSameTypesShouldBeEqual) {
+  auto t = makeNamedDecls(
+  "__attribute__((noreturn)) void foo();",
+  "  void foo();",
+  Lang_C);
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
 struct StructuralEquivalenceCXXMethodTest : StructuralEquivalenceTest {
 };
 
Index: lib/AST/ASTStructuralEquivalence.cpp
===
--- lib/AST/ASTStructuralEquivalence.cpp
+++ lib/AST/ASTStructuralEquivalence.cpp
@@ -540,8 +540,6 @@
 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
   Function2->getReturnType()))
   return false;
-if (Function1->getExtInfo() != Function2->getExtInfo())
-  return false;
 break;
   }
 


Index: unittests/AST/StructuralEquivalenceTest.cpp
===
--- unittests/AST/StructuralEquivalenceTest.cpp
+++ unittests/AST/StructuralEquivalenceTest.cpp
@@ -370,6 +370,15 @@
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+TEST_F(StructuralEquivalenceFunctionTest,
+FunctionsWithDifferentAttributesButSameTypesShouldBeEqual) {
+  auto t = makeNamedDecls(
+  "__attribute__((noreturn)) void foo();",
+  "  void foo();",
+  Lang_C);
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
 struct StructuralEquivalenceCXXMethodTest : StructuralEquivalenceTest {
 };
 
Index: lib/AST/ASTStructuralEquivalence.cpp
===
--- lib/AST/ASTStructuralEquivalence.cpp
+++ lib/AST/ASTStructuralEquivalence.cpp
@@ -540,8 +540,6 @@
 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
   Function2->getReturnType()))
   return false;
-if (Function1->getExtInfo() != Function2->getExtInfo())
-  return false;
 break;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53651: [clangd] Use thread pool for background indexing.

2018-10-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In https://reviews.llvm.org/D53651#1275517, @ilya-biryukov wrote:

> It's fine to spend one thread spinning on background tasks, but if we're 
> going to do a threadpool, we should be more careful to not hurt the 
> performance of foreground tasks. To do that, we should at least:
>
> - share the semaphore for the number of actively running tasks between 
> TUScheduler and BackgroundIndex.
> - prioritize foreground tasks over background tasks.


I don't think I agree with this, at least not without evidence. Can we try 
thread priorities first?




Comment at: clangd/index/Background.cpp:89
   }
-  QueueCV.notify_all();
+  QueueCV.notify_one();
 }

I always forget the details of how these work :-\
Is it possible for the "one" notification to be consumed by a waiter on 
blockUntilIdleForTest?

In general I'm not sure whether the `notify_one` optimization is worth the 
correctness risk as the code evolves.



Comment at: clangd/index/Background.h:80
+  // Must be last, spawned thread reads instance vars.
+  llvm::SmallVector ThreadPool;
 };

ilya-biryukov wrote:
> Why not `std::vector`? Memory allocs won't ever be a bottleneck here.
ilya was saying nice things about `llvm::ThreadPool` recently - worth a look?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53651



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


[PATCH] D53586: Implement Function Multiversioning for Non-ELF Systems.

2018-10-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 171088.
erichkeane marked an inline comment as done.
erichkeane added a comment.

Added test as requested by @rnk.  How's it look?  I hope I got the balance of 
check-lines right.


https://reviews.llvm.org/D53586

Files:
  include/clang/AST/Decl.h
  include/clang/Basic/Attr.td
  include/clang/Basic/TargetInfo.h
  lib/AST/Decl.cpp
  lib/Basic/Targets/X86.h
  lib/CodeGen/CodeGenFunction.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  test/CodeGen/attr-cpuspecific.c
  test/CodeGen/attr-target-mv-func-ptrs.c
  test/CodeGen/attr-target-mv-va-args.c
  test/CodeGen/attr-target-mv.c
  test/CodeGenCXX/attr-target-mv-diff-ns.cpp
  test/CodeGenCXX/attr-target-mv-func-ptrs.cpp
  test/CodeGenCXX/attr-target-mv-member-funcs.cpp
  test/CodeGenCXX/attr-target-mv-out-of-line-defs.cpp
  test/CodeGenCXX/attr-target-mv-overloads.cpp
  test/Sema/attr-target-mv-bad-target.c

Index: test/Sema/attr-target-mv-bad-target.c
===
--- test/Sema/attr-target-mv-bad-target.c
+++ test/Sema/attr-target-mv-bad-target.c
@@ -1,4 +1,3 @@
-// RUN: %clang_cc1 -triple x86_64-windows-pc  -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple arm-none-eabi  -fsyntax-only -verify %s
 
 int __attribute__((target("sse4.2"))) redecl1(void) { return 1; }
Index: test/CodeGenCXX/attr-target-mv-overloads.cpp
===
--- test/CodeGenCXX/attr-target-mv-overloads.cpp
+++ test/CodeGenCXX/attr-target-mv-overloads.cpp
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix=LINUX
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-windows-pc -emit-llvm %s -o - | FileCheck %s --check-prefix=WINDOWS
 
 int __attribute__((target("sse4.2"))) foo_overload(int) { return 0; }
 int __attribute__((target("arch=sandybridge"))) foo_overload(int);
@@ -13,38 +14,69 @@
   return foo_overload() + foo_overload(1);
 }
 
-// CHECK: @_Z12foo_overloadv.ifunc = ifunc i32 (), i32 ()* ()* @_Z12foo_overloadv.resolver
-// CHECK: @_Z12foo_overloadi.ifunc = ifunc i32 (i32), i32 (i32)* ()* @_Z12foo_overloadi.resolver
-
-
-// CHECK: define i32 @_Z12foo_overloadi.sse4.2(i32)
-// CHECK: ret i32 0
-// CHECK: define i32 @_Z12foo_overloadi.arch_ivybridge(i32)
-// CHECK: ret i32 1
-// CHECK: define i32 @_Z12foo_overloadi(i32)
-// CHECK: ret i32 2
-// CHECK: define i32 @_Z12foo_overloadv.sse4.2()
-// CHECK: ret i32 0
-// CHECK: define i32 @_Z12foo_overloadv.arch_ivybridge()
-// CHECK: ret i32 1
-// CHECK: define i32 @_Z12foo_overloadv()
-// CHECK: ret i32 2
-
-// CHECK: define i32 @_Z4bar2v()
-// CHECK: call i32 @_Z12foo_overloadv.ifunc()
-// CHECK: call i32 @_Z12foo_overloadi.ifunc(i32 1)
-
-// CHECK: define i32 ()* @_Z12foo_overloadv.resolver() comdat
-// CHECK: ret i32 ()* @_Z12foo_overloadv.arch_sandybridge
-// CHECK: ret i32 ()* @_Z12foo_overloadv.arch_ivybridge
-// CHECK: ret i32 ()* @_Z12foo_overloadv.sse4.2
-// CHECK: ret i32 ()* @_Z12foo_overloadv
-
-// CHECK: define i32 (i32)* @_Z12foo_overloadi.resolver() comdat
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi.arch_sandybridge
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi.arch_ivybridge
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi.sse4.2
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi
-
-// CHECK: declare i32 @_Z12foo_overloadv.arch_sandybridge()
-// CHECK: declare i32 @_Z12foo_overloadi.arch_sandybridge(i32)
+// LINUX: @_Z12foo_overloadv.ifunc = ifunc i32 (), i32 ()* ()* @_Z12foo_overloadv.resolver
+// LINUX: @_Z12foo_overloadi.ifunc = ifunc i32 (i32), i32 (i32)* ()* @_Z12foo_overloadi.resolver
+
+// LINUX: define i32 @_Z12foo_overloadi.sse4.2(i32)
+// LINUX: ret i32 0
+// LINUX: define i32 @_Z12foo_overloadi.arch_ivybridge(i32)
+// LINUX: ret i32 1
+// LINUX: define i32 @_Z12foo_overloadi(i32)
+// LINUX: ret i32 2
+// LINUX: define i32 @_Z12foo_overloadv.sse4.2()
+// LINUX: ret i32 0
+// LINUX: define i32 @_Z12foo_overloadv.arch_ivybridge()
+// LINUX: ret i32 1
+// LINUX: define i32 @_Z12foo_overloadv()
+// LINUX: ret i32 2
+
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.sse4.2"(i32)
+// WINDOWS: ret i32 0
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.arch_ivybridge"(i32)
+// WINDOWS: ret i32 1
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z"(i32)
+// WINDOWS: ret i32 2
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.sse4.2"()
+// WINDOWS: ret i32 0
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.arch_ivybridge"()
+// WINDOWS: ret i32 1
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ"()
+// WINDOWS: ret i32 2
+
+// LINUX: define i32 @_Z4bar2v()
+// LINUX: call i32 @_Z12foo_overloadv.ifunc()
+// LINUX: call i32 @_Z12foo_overloadi.ifunc(i32 1)
+
+// WINDOWS: define dso_local i32 @"?bar2@@YAHXZ"()
+// WINDOWS: call i32 @"?foo_ove

r345267 - update the clang doc about contributions

2018-10-25 Thread Sylvestre Ledru via cfe-commits
Author: sylvestre
Date: Thu Oct 25 07:19:06 2018
New Revision: 345267

URL: http://llvm.org/viewvc/llvm-project?rev=345267&view=rev
Log:
update the clang doc about contributions

Modified:
cfe/trunk/www/hacking.html

Modified: cfe/trunk/www/hacking.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/www/hacking.html?rev=345267&r1=345266&r2=345267&view=diff
==
--- cfe/trunk/www/hacking.html (original)
+++ cfe/trunk/www/hacking.html Thu Oct 25 07:19:06 2018
@@ -276,9 +276,8 @@ Testing Time: 81.52s
   
 
   To return changes to the Clang team, unless you have checkin
-  privileges, the preferred way is to send patch files to the
-  cfe-commits mailing list, with an explanation of what the patch is
-  for.  clang follows https://llvm.org/docs/Contributing.html#how-to-submit-a-patch";>using 
LLVM's Phabricator with an explanation of what the patch is for. Clang 
follows http://llvm.org/docs/DeveloperPolicy.html";>LLVM's developer policy.
   If your patch requires a wider discussion (for example, because it is an
   architectural change), you can use the cfe-dev mailing list.
@@ -299,6 +298,8 @@ Testing Time: 81.52s
   Note that the paths embedded in the patch depend on where you run it,
   so changing directory to the llvm/tools/clang directory is recommended.
 
+  It is also possible to https://llvm.org/docs/GettingStarted.html#sending-patches-with-git";>use 
git to contribute to Clang.
+
   
   LLVM IR Generation
   


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


[clang-tools-extra] r345268 - [clangd] workspace/symbol should be async, it reads from the index.

2018-10-25 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Oct 25 07:19:14 2018
New Revision: 345268

URL: http://llvm.org/viewvc/llvm-project?rev=345268&view=rev
Log:
[clangd] workspace/symbol should be async, it reads from the index.

Summary:
To enable this, TUScheduler has to provide a way to run async tasks without
needing a preamble or AST!

Reviewers: ilya-biryukov

Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, jfb, kadircet, 
cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=345268&r1=345267&r2=345268&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Thu Oct 25 07:19:14 2018
@@ -482,8 +482,15 @@ void ClangdServer::onFileEvent(const Did
 
 void ClangdServer::workspaceSymbols(
 StringRef Query, int Limit, Callback> CB) {
-  CB(clangd::getWorkspaceSymbols(Query, Limit, Index,
- WorkspaceRoot.getValueOr("")));
+  std::string QueryCopy = Query;
+  WorkScheduler.run(
+  "getWorkspaceSymbols",
+  Bind(
+  [QueryCopy, Limit, this](decltype(CB) CB) {
+CB(clangd::getWorkspaceSymbols(QueryCopy, Limit, Index,
+   WorkspaceRoot.getValueOr("")));
+  },
+  std::move(CB)));
 }
 
 void ClangdServer::documentSymbols(

Modified: clang-tools-extra/trunk/clangd/TUScheduler.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.cpp?rev=345268&r1=345267&r2=345268&view=diff
==
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp Thu Oct 25 07:19:14 2018
@@ -720,6 +720,12 @@ void TUScheduler::remove(PathRef File) {
  File);
 }
 
+void TUScheduler::run(StringRef Name, unique_function Action) {
+  if (!PreambleTasks)
+return Action();
+  PreambleTasks->runAsync(Name, std::move(Action));
+}
+
 void TUScheduler::runWithAST(
 StringRef Name, PathRef File,
 unique_function)> Action) {

Modified: clang-tools-extra/trunk/clangd/TUScheduler.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.h?rev=345268&r1=345267&r2=345268&view=diff
==
--- clang-tools-extra/trunk/clangd/TUScheduler.h (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.h Thu Oct 25 07:19:14 2018
@@ -108,6 +108,9 @@ public:
   /// resources.
   void remove(PathRef File);
 
+  /// Schedule an async task with no dependencies.
+  void run(llvm::StringRef Name, llvm::unique_function Action);
+
   /// Schedule an async read of the AST. \p Action will be called when AST is
   /// ready. The AST passed to \p Action refers to the version of \p File
   /// tracked at the time of the call, even if new updates are received before

Modified: clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp?rev=345268&r1=345267&r2=345268&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp Thu Oct 25 
07:19:14 2018
@@ -532,6 +532,18 @@ TEST_F(TUSchedulerTests, NoChangeDiags)
   ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
 }
 
+TEST_F(TUSchedulerTests, Run) {
+  TUScheduler S(/*AsyncThreadsCount=*/getDefaultAsyncThreadsCount(),
+/*StorePreambleInMemory=*/true, /*ASTCallbacks=*/nullptr,
+/*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+ASTRetentionPolicy());
+  std::atomic Counter(0);
+  S.run("add 1", [&] { ++Counter; });
+  S.run("add 2", [&] { Counter += 2; });
+  ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_EQ(Counter.load(), 3);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


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


[PATCH] D53644: [clangd] workspace/symbol should be async, it reads from the index.

2018-10-25 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rCTE345268: [clangd] workspace/symbol should be async, it 
reads from the index. (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D53644?vs=170874&id=171090#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53644

Files:
  clangd/ClangdServer.cpp
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  unittests/clangd/TUSchedulerTests.cpp


Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -532,6 +532,18 @@
   ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
 }
 
+TEST_F(TUSchedulerTests, Run) {
+  TUScheduler S(/*AsyncThreadsCount=*/getDefaultAsyncThreadsCount(),
+/*StorePreambleInMemory=*/true, /*ASTCallbacks=*/nullptr,
+/*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+ASTRetentionPolicy());
+  std::atomic Counter(0);
+  S.run("add 1", [&] { ++Counter; });
+  S.run("add 2", [&] { Counter += 2; });
+  ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_EQ(Counter.load(), 3);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -720,6 +720,12 @@
  File);
 }
 
+void TUScheduler::run(StringRef Name, unique_function Action) {
+  if (!PreambleTasks)
+return Action();
+  PreambleTasks->runAsync(Name, std::move(Action));
+}
+
 void TUScheduler::runWithAST(
 StringRef Name, PathRef File,
 unique_function)> Action) {
Index: clangd/TUScheduler.h
===
--- clangd/TUScheduler.h
+++ clangd/TUScheduler.h
@@ -108,6 +108,9 @@
   /// resources.
   void remove(PathRef File);
 
+  /// Schedule an async task with no dependencies.
+  void run(llvm::StringRef Name, llvm::unique_function Action);
+
   /// Schedule an async read of the AST. \p Action will be called when AST is
   /// ready. The AST passed to \p Action refers to the version of \p File
   /// tracked at the time of the call, even if new updates are received before
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -482,8 +482,15 @@
 
 void ClangdServer::workspaceSymbols(
 StringRef Query, int Limit, Callback> CB) {
-  CB(clangd::getWorkspaceSymbols(Query, Limit, Index,
- WorkspaceRoot.getValueOr("")));
+  std::string QueryCopy = Query;
+  WorkScheduler.run(
+  "getWorkspaceSymbols",
+  Bind(
+  [QueryCopy, Limit, this](decltype(CB) CB) {
+CB(clangd::getWorkspaceSymbols(QueryCopy, Limit, Index,
+   WorkspaceRoot.getValueOr("")));
+  },
+  std::move(CB)));
 }
 
 void ClangdServer::documentSymbols(


Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -532,6 +532,18 @@
   ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
 }
 
+TEST_F(TUSchedulerTests, Run) {
+  TUScheduler S(/*AsyncThreadsCount=*/getDefaultAsyncThreadsCount(),
+/*StorePreambleInMemory=*/true, /*ASTCallbacks=*/nullptr,
+/*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+ASTRetentionPolicy());
+  std::atomic Counter(0);
+  S.run("add 1", [&] { ++Counter; });
+  S.run("add 2", [&] { Counter += 2; });
+  ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  EXPECT_EQ(Counter.load(), 3);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -720,6 +720,12 @@
  File);
 }
 
+void TUScheduler::run(StringRef Name, unique_function Action) {
+  if (!PreambleTasks)
+return Action();
+  PreambleTasks->runAsync(Name, std::move(Action));
+}
+
 void TUScheduler::runWithAST(
 StringRef Name, PathRef File,
 unique_function)> Action) {
Index: clangd/TUScheduler.h
===
--- clangd/TUScheduler.h
+++ clangd/TUScheduler.h
@@ -108,6 +108,9 @@
   /// resources.
   void remove(PathRef File);
 
+  /// Schedule an async task with no dependencies.
+  void run(llvm::StringRef Name, llvm::unique_function Action);
+
   /// Schedule an async read of the AST. \p Action will be called when AST is
   /// ready. The AST passed to \p Action refers to the version of \p File
   /// tracked at the time of the cal

[PATCH] D53700: Support _Clang as a scoped attribute identifier

2018-10-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: rsmith, echristo, dblaikie.
Herald added a subscriber: krytarowski.

Currently, we only accept `clang` as the scoped attribute identifier for double 
square bracket attributes provided by Clang, but this has the potential to 
conflict with user-defined macros. To help alleviate these concerns, this patch 
introduces the `_Clang` scoped attribute identifier as an alias for `clang`.

GCC elected to go with `__gnu__` for their protected name, but we cannot follow 
suit due to `__clang__` being a predefined macro that identifies the 
implementation.  I added a warning with a fixit on the off chance someone 
attempts to use `__clang__` as the scoped attribute identifier, but do not 
support the spelling fully (for instance, `__has_cpp_attribute` does not 
support `__clang__`).


https://reviews.llvm.org/D53700

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  lib/Basic/Attributes.cpp
  lib/Parse/ParseDeclCXX.cpp
  lib/Sema/ParsedAttr.cpp
  test/FixIt/fixit-cxx11-attributes.cpp
  test/Parser/cxx0x-attributes.cpp
  test/Preprocessor/has_attribute.cpp
  test/SemaCXX/attr-optnone.cpp

Index: test/SemaCXX/attr-optnone.cpp
===
--- test/SemaCXX/attr-optnone.cpp
+++ test/SemaCXX/attr-optnone.cpp
@@ -71,3 +71,9 @@
   static void bar();
 };
 
+// Verify that we can handle the [[_Clang::optnone]] and
+// [[__clang__::optnone]] spellings.
+[[_Clang::optnone]] int foo3();
+[[__clang__::optnone]] int foo4(); // expected-warning {{'__clang__' is a predefined macro name, not an attribute scope specifier; did you mean '_Clang' instead?}}
+
+[[_Clang::optnone]] int foo5; // expected-warning {{'optnone' attribute only applies to functions}}
Index: test/Preprocessor/has_attribute.cpp
===
--- test/Preprocessor/has_attribute.cpp
+++ test/Preprocessor/has_attribute.cpp
@@ -21,11 +21,27 @@
   int has_clang_fallthrough_2();
 #endif
 
-// The scope cannot be bracketed with double underscores unless it is for gnu.
+// The scope cannot be bracketed with double underscores unless it is
+// for gnu or clang.
+// CHECK: does_not_have___gsl___suppress
+#if !__has_cpp_attribute(__gsl__::suppress)
+  int does_not_have___gsl___suppress();
+#endif
+
+// We do somewhat support the __clang__ vendor namespace, but it is a
+// predefined macro and thus we encourage users to use _Clang instead.
+// Because of this, we do not support __has_cpp_attribute for that
+// vendor namespace.
 // CHECK: does_not_have___clang___fallthrough
 #if !__has_cpp_attribute(__clang__::fallthrough)
   int does_not_have___clang___fallthrough();
 #endif
+
+// CHECK: does_have_Clang_fallthrough
+#if __has_cpp_attribute(_Clang::fallthrough)
+  int does_have_Clang_fallthrough();
+#endif
+
 // CHECK: has_gnu_const
 #if __has_cpp_attribute(__gnu__::__const__)
   int has_gnu_const();
Index: test/Parser/cxx0x-attributes.cpp
===
--- test/Parser/cxx0x-attributes.cpp
+++ test/Parser/cxx0x-attributes.cpp
@@ -373,3 +373,11 @@
 [[attr_name, attr_name_2(bitor), attr_name_3(com, pl)]] int macro_attrs; // expected-warning {{unknown attribute 'compl' ignored}} \
expected-warning {{unknown attribute 'bitor' ignored}} \
expected-warning {{unknown attribute 'bitand' ignored}}
+
+// Check that we can parse an attribute in our vendor namespace.
+[[clang::annotate("test")]] void annotate1();
+[[_Clang::annotate("test")]] void annotate2();
+// Note: __clang__ is a predefined macro, which is why _Clang is the
+// prefered "protected" vendor namespace. We support __clang__ only for
+// people expecting it to behave the same as __gnu__.
+[[__clang__::annotate("test")]] void annotate3();  // expected-warning {{'__clang__' is a predefined macro name, not an attribute scope specifier; did you mean '_Clang' instead?}}
Index: test/FixIt/fixit-cxx11-attributes.cpp
===
--- test/FixIt/fixit-cxx11-attributes.cpp
+++ test/FixIt/fixit-cxx11-attributes.cpp
@@ -16,15 +16,15 @@
// CHECK: fix-it:{{.*}}:{14:37-14:51}
 
   class base {};
-  class [[]] [[]] final_class 
+  class [[]] [[]] final_class
 alignas(float) [[]] final // expected-error {{an attribute list cannot appear here}}
 alignas(float) [[]] [[]] alignas(float): base{}; // expected-error {{an attribute list cannot appear here}}
 // CHECK: fix-it:{{.*}}:{19:19-19:19}
 // CHECK: fix-it:{{.*}}:{20:5-20:25}
 // CHECK: fix-it:{{.*}}:{19:19-19:19}
 // CHECK: fix-it:{{.*}}:{21:5-21:44}
 
-  class [[]] [[]] final_class_another 
+  class [[]] [[]] final_class_another
 [[]] [[]] alignas(16) final // expected-error {{an attribute list cannot appear here}}
 [[]] [[]] alignas(16) [[]]{}; // expected-error {{an attribute list cannot appear here}}
 // CHECK: fix-it:{{.*}}:{27:19-27:19}
@@ -49,3 +49

[PATCH] D53701: [Analyzer] Record and process comparison of symbols instead of iterator positions in interator checkers

2018-10-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added a reviewer: NoQ.
baloghadamsoftware added a project: clang.
Herald added subscribers: donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, 
rnkovacs, szepet, whisperity.
Herald added a reviewer: george.karpenkov.

Currently iterator checkers record comparison of iterator positions and process 
them for keeping track the distance between them (e.g. whether a position is 
the same as the end position). However this makes some processing unnecessarily 
complex and it is not needed at all: we only need to keep track between the 
abstract symbols stored in these iterator positions. This patch changes this 
and opens the path to comparisons to the `begin()` and `end()` symbols between 
the container (e.g. size, emptiness) which are stored as symbols, not iterator 
positions. The functionality of the checker is unchanged.


Repository:
  rC Clang

https://reviews.llvm.org/D53701

Files:
  lib/StaticAnalyzer/Checkers/IteratorChecker.cpp

Index: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
+++ lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
@@ -134,8 +134,6 @@
   }
 };
 
-typedef llvm::PointerUnion RegionOrSymbol;
-
 // Structure to record the symbolic begin and end position of a container
 struct ContainerData {
 private:
@@ -173,27 +171,31 @@
   }
 };
 
-// Structure fo recording iterator comparisons. We needed to retrieve the
-// original comparison expression in assumptions.
-struct IteratorComparison {
+// Structure fo recording symbol comparisons. We need to retrieve the original
+// comparison expression in assumptions.
+struct SymbolComparison {
 private:
-  RegionOrSymbol Left, Right;
+  SymbolRef Left, Right;
   bool Equality;
 
 public:
-  IteratorComparison(RegionOrSymbol L, RegionOrSymbol R, bool Eq)
+  SymbolComparison(SymbolRef L, SymbolRef R, bool Eq)
   : Left(L), Right(R), Equality(Eq) {}
 
-  RegionOrSymbol getLeft() const { return Left; }
-  RegionOrSymbol getRight() const { return Right; }
+  SymbolRef getLeft() const { return Left; }
+  SymbolRef getRight() const { return Right; }
   bool isEquality() const { return Equality; }
-  bool operator==(const IteratorComparison &X) const {
+  bool operator==(const SymbolComparison &X) const {
 return Left == X.Left && Right == X.Right && Equality == X.Equality;
   }
-  bool operator!=(const IteratorComparison &X) const {
+  bool operator!=(const SymbolComparison &X) const {
 return Left != X.Left || Right != X.Right || Equality != X.Equality;
   }
-  void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(Equality); }
+  void Profile(llvm::FoldingSetNodeID &ID) const {
+ID.Add(Left);
+ID.Add(Right);
+ID.AddInteger(Equality);
+  }
 };
 
 class IteratorChecker
@@ -206,8 +208,12 @@
   std::unique_ptr MismatchedBugType;
   std::unique_ptr InvalidatedBugType;
 
-  void handleComparison(CheckerContext &C, const SVal &RetVal, const SVal &LVal,
-const SVal &RVal, OverloadedOperatorKind Op) const;
+  void handleComparison(CheckerContext &C, const Expr *CE, const SVal &RetVal,
+const SVal &LVal, const SVal &RVal,
+OverloadedOperatorKind Op) const;
+  void processComparison(CheckerContext &C, ProgramStateRef State,
+ SymbolRef Sym1, SymbolRef Sym2, const SVal &RetVal,
+ OverloadedOperatorKind Op) const;
   void verifyAccess(CheckerContext &C, const SVal &Val) const;
   void verifyDereference(CheckerContext &C, const SVal &Val) const;
   void handleIncrement(CheckerContext &C, const SVal &RetVal, const SVal &Iter,
@@ -290,8 +296,8 @@
 
 REGISTER_MAP_WITH_PROGRAMSTATE(ContainerMap, const MemRegion *, ContainerData)
 
-REGISTER_MAP_WITH_PROGRAMSTATE(IteratorComparisonMap, const SymExpr *,
-   IteratorComparison)
+REGISTER_MAP_WITH_PROGRAMSTATE(SymbolComparisonMap, const SymExpr *,
+   SymbolComparison)
 
 namespace {
 
@@ -323,15 +329,10 @@
 bool frontModifiable(ProgramStateRef State, const MemRegion *Reg);
 bool backModifiable(ProgramStateRef State, const MemRegion *Reg);
 BinaryOperator::Opcode getOpcode(const SymExpr *SE);
-const RegionOrSymbol getRegionOrSymbol(const SVal &Val);
-const ProgramStateRef processComparison(ProgramStateRef State,
-RegionOrSymbol LVal,
-RegionOrSymbol RVal, bool Equal);
-const ProgramStateRef saveComparison(ProgramStateRef State,
- const SymExpr *Condition, const SVal &LVal,
- const SVal &RVal, bool Eq);
-const IteratorComparison *loadComparison(ProgramStateRef State,
- const SymExpr *Condition);
+const ProgramStateRef saveComparison(ProgramStateRef State, 

[PATCH] D53702: [ASTImporter] Set redecl chain of functions before any other import

2018-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, Szelethus, dkrupp, rnkovacs.
Herald added a reviewer: a.sidorin.

FunctionDecl import starts with a lookup and then we create a new Decl.
Then in case of CXXConstructorDecl we further import other Decls
(base classes, members through CXXConstructorDecl::inits()) before connecting
the redecl chain.  During those in-between imports structural eq fails
because the canonical decl is different.  This commit fixes this.
Synthesizing a test seemed extremely hard, however, Xerces analysis
reproduces the problem.


Repository:
  rC Clang

https://reviews.llvm.org/D53702

Files:
  lib/AST/ASTImporter.cpp


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -3139,19 +3139,6 @@
 FromConstructor->isExplicit(),
 D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()))
   return ToFunction;
-if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
-  SmallVector CtorInitializers(NumInitializers);
-  // Import first, then allocate memory and copy if there was no error.
-  if (Error Err = ImportContainerChecked(
-  FromConstructor->inits(), CtorInitializers))
-return std::move(Err);
-  auto **Memory =
-  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
-  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
-  auto *ToCtor = cast(ToFunction);
-  ToCtor->setCtorInitializers(Memory);
-  ToCtor->setNumCtorInitializers(NumInitializers);
-}
   } else if (isa(D)) {
 if (GetImportedOrCreateDecl(
 ToFunction, D, Importer.getToContext(), cast(DC),
@@ -3179,6 +3166,30 @@
   return ToFunction;
   }
 
+  // Connect the redecl chain.
+  if (FoundByLookup) {
+auto *Recent = const_cast(
+  FoundByLookup->getMostRecentDecl());
+ToFunction->setPreviousDecl(Recent);
+  }
+
+  // Import Ctor initializers.
+  if (auto *FromConstructor = dyn_cast(D)) {
+if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
+  SmallVector CtorInitializers(NumInitializers);
+  // Import first, then allocate memory and copy if there was no error.
+  if (Error Err = ImportContainerChecked(
+  FromConstructor->inits(), CtorInitializers))
+return std::move(Err);
+  auto **Memory =
+  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
+  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
+  auto *ToCtor = cast(ToFunction);
+  ToCtor->setCtorInitializers(Memory);
+  ToCtor->setNumCtorInitializers(NumInitializers);
+}
+  }
+
   ToFunction->setQualifierInfo(ToQualifierLoc);
   ToFunction->setAccess(D->getAccess());
   ToFunction->setLexicalDeclContext(LexicalDC);
@@ -3194,12 +3205,6 @@
   }
   ToFunction->setParams(Parameters);
 
-  if (FoundByLookup) {
-auto *Recent = const_cast(
-  FoundByLookup->getMostRecentDecl());
-ToFunction->setPreviousDecl(Recent);
-  }
-
   // We need to complete creation of FunctionProtoTypeLoc manually with setting
   // params it refers to.
   if (TInfo) {


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -3139,19 +3139,6 @@
 FromConstructor->isExplicit(),
 D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()))
   return ToFunction;
-if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
-  SmallVector CtorInitializers(NumInitializers);
-  // Import first, then allocate memory and copy if there was no error.
-  if (Error Err = ImportContainerChecked(
-  FromConstructor->inits(), CtorInitializers))
-return std::move(Err);
-  auto **Memory =
-  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
-  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
-  auto *ToCtor = cast(ToFunction);
-  ToCtor->setCtorInitializers(Memory);
-  ToCtor->setNumCtorInitializers(NumInitializers);
-}
   } else if (isa(D)) {
 if (GetImportedOrCreateDecl(
 ToFunction, D, Importer.getToContext(), cast(DC),
@@ -3179,6 +3166,30 @@
   return ToFunction;
   }
 
+  // Connect the redecl chain.
+  if (FoundByLookup) {
+auto *Recent = const_cast(
+  FoundByLookup->getMostRecentDecl());
+ToFunction->setPreviousDecl(Recent);
+  }
+
+  // Import Ctor initializers.
+  if (auto *FromConstructor = dyn_cast(D)) {
+if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
+  SmallVector CtorInitializers(NumInitializers);
+  // Import first, then allocate memory and copy if there was no error.
+  if (Error Err = ImportContainerChecked(
+  FromCon

[PATCH] D53488: [clang-tidy] Catching narrowing from double to float.

2018-10-25 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet marked 2 inline comments as done.
gchatelet added a comment.

In https://reviews.llvm.org/D53488#1274205, @JonasToth wrote:

> Did you run this code over a real-world code-base and did you find new stuff 
> and/or false positives or the like?


Yes I did run it over our code base. I didn't find false positive but 98% of 
the warnings are from large generated lookup table initializers, e.g. `const 
static float kTable[] = {0.0, 2.0, ... };`
Since every number in the list triggers the warning, it accounts for most of 
them.

I scrutinized a few hundreds of the rest: none were actual bugs (although it's 
hard to tell sometimes), most are legit like `float value = 0.0;` but I also 
found some oddities 

 from generated headers.

To me the warnings are useful and if it were my code I'd be willing to fix 
them. That said, I'd totally understand that many people would find them 
useless or annoying.
What do you think? Shall we still commit this as is?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488



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


[PATCH] D53692: [analyzer] Evaluate all non-checker config options before analysis

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171094.
Szelethus edited the summary of this revision.

https://reviews.llvm.org/D53692

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/Frontend/CompilerInvocation.cpp
  lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
  lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  lib/StaticAnalyzer/Core/CallEvent.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  lib/StaticAnalyzer/Core/RegionStore.cpp
  lib/StaticAnalyzer/Core/SValBuilder.cpp
  lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp

Index: test/Analysis/analyzer-config.cpp
===
--- test/Analysis/analyzer-config.cpp
+++ test/Analysis/analyzer-config.cpp
@@ -19,6 +19,9 @@
 };
 
 // CHECK: [config]
+// CHECK-NEXT: aggressive-binary-operation-simplification = false
+// CHECK-NEXT: avoid-suppressing-null-argument-paths = false
+// CHECK-NEXT: c++-allocator-inlining = true
 // CHECK-NEXT: c++-container-inlining = false
 // CHECK-NEXT: c++-inlining = destructors
 // CHECK-NEXT: c++-shared_ptr-inlining = false
@@ -32,6 +35,9 @@
 // CHECK-NEXT: cfg-rich-constructors = true
 // CHECK-NEXT: cfg-scopes = false
 // CHECK-NEXT: cfg-temporary-dtors = true
+// CHECK-NEXT: crosscheck-with-z3 = false
+// CHECK-NEXT: ctu-dir = ""
+// CHECK-NEXT: ctu-index-name = externalFnMap.txt
 // CHECK-NEXT: eagerly-assume = true
 // CHECK-NEXT: elide-constructors = true
 // CHECK-NEXT: experimental-enable-naive-ctu-analysis = false
@@ -43,12 +49,22 @@
 // CHECK-NEXT: ipa-always-inline-size = 3
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
+// CHECK-NEXT: max-symbol-complexity = 35
 // CHECK-NEXT: max-times-inline-large = 32
 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14
 // CHECK-NEXT: mode = deep
+// CHECK-NEXT: model-path = ""
+// CHECK-NEXT: notes-as-events = false
+// CHECK-NEXT: objc-inlining = true
+// CHECK-NEXT: prune-paths = true
 // CHECK-NEXT: region-store-small-struct-limit = 2
+// CHECK-NEXT: report-in-main-source-file = false
 // CHECK-NEXT: serialize-stats = false
+// CHECK-NEXT: stable-report-filename = false
+// CHECK-NEXT: suppress-c++-stdlib = true
+// CHECK-NEXT: suppress-inlined-defensive-checks = true
+// CHECK-NEXT: suppress-null-return-paths = true
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 31
+// CHECK-NEXT: num-entries = 47
Index: test/Analysis/analyzer-config.c
===
--- test/Analysis/analyzer-config.c
+++ test/Analysis/analyzer-config.c
@@ -11,29 +11,52 @@
 }
 
 // CHECK: [config]
+// CHECK-NEXT: aggressive-binary-operation-simplification = false
+// CHECK-NEXT: avoid-suppressing-null-argument-paths = false
+// CHECK-NEXT: c++-allocator-inlining = true
+// CHECK-NEXT: c++-container-inlining = false
+// CHECK-NEXT: c++-inlining = destructors
+// CHECK-NEXT: c++-shared_ptr-inlining = false
+// CHECK-NEXT: c++-stdlib-inlining = true
+// CHECK-NEXT: c++-temp-dtor-inlining = true
+// CHECK-NEXT: c++-template-inlining = true
 // CHECK-NEXT: cfg-conditional-static-initializers = true
 // CHECK-NEXT: cfg-implicit-dtors = true
 // CHECK-NEXT: cfg-lifetime = false
 // CHECK-NEXT: cfg-loopexit = false
 // CHECK-NEXT: cfg-rich-constructors = true
 // CHECK-NEXT: cfg-scopes = false
 // CHECK-NEXT: cfg-temporary-dtors = true
+// CHECK-NEXT: crosscheck-with-z3 = false
+// CHECK-NEXT: ctu-dir = ""
+// CHECK-NEXT: ctu-index-name = externalFnMap.txt
 // CHECK-NEXT: eagerly-assume = true
 // CHECK-NEXT: elide-constructors = true
+// CHECK-NEXT: experimental-enable-naive-ctu-analysis = false
 // CHECK-NEXT: exploration_strategy = unexplored_first_queue
 // CHECK-NEXT: faux-bodies = true
 // CHECK-NEXT: graph-trim-interval = 1000
 // CHECK-NEXT: inline-lambdas = true
 // CHECK-NEXT: ipa = dynamic-bifurcate
 // CHECK-NEXT: ipa-always-inline-size = 3
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
+// CHECK-NEXT: max-symbol-complexity = 35
 // CHECK-NEXT: max-times-inline-large = 32
 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14
 // CHECK-NEXT: mode = deep
+// CHECK-NEXT: model-path = ""
+// CHECK-NEXT: notes-as-events = false
+// CHECK-NEXT: objc-inlining = true
+// CHECK-NEXT: prune-paths = true
 // CHECK-NEXT: region-store-small-struct-limit = 2
+// CHECK-

[PATCH] D53704: [ASTImporter] Import overrides before importing the rest of the chain

2018-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, Szelethus, dkrupp, rnkovacs.
Herald added a reviewer: a.sidorin.

During method import we check for structural eq of two methods.
In the structural eq check we check for their isVirtual() flag. That
flag, however, may depend on the number of overrides. Before this
change we imported the overrides *after* we had imported the rest of the
redecl chain.  So, during the import of another decl from the chain
IsVirtual() gave false result.

Writing tests for this is not really possible, because there is no way
to remove an overridden method via the AST API.
(We should access the private ASTContext::OverriddenMethods container.)
Also, we should do the remove in the middle of the import process.


Repository:
  rC Clang

https://reviews.llvm.org/D53704

Files:
  lib/AST/ASTImporter.cpp


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -3258,16 +3258,16 @@
 DC->makeDeclVisibleInContext(ToFunction);
   }
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+ImportOverrides(cast(ToFunction), FromCXXMethod);
+
   // Import the rest of the chain. I.e. import all subsequent declarations.
   for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
 if (!ToRedeclOrErr)
   return ToRedeclOrErr.takeError();
   }
 
-  if (auto *FromCXXMethod = dyn_cast(D))
-ImportOverrides(cast(ToFunction), FromCXXMethod);
-
   return ToFunction;
 }
 


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -3258,16 +3258,16 @@
 DC->makeDeclVisibleInContext(ToFunction);
   }
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+ImportOverrides(cast(ToFunction), FromCXXMethod);
+
   // Import the rest of the chain. I.e. import all subsequent declarations.
   for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
 if (!ToRedeclOrErr)
   return ToRedeclOrErr.takeError();
   }
 
-  if (auto *FromCXXMethod = dyn_cast(D))
-ImportOverrides(cast(ToFunction), FromCXXMethod);
-
   return ToFunction;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53687: [clangd] Make in-memory CDB always available as an overlay, refactor.

2018-10-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added a comment.

In https://reviews.llvm.org/D53687#1275580, @ilya-biryukov wrote:

> FWIW, the old implementation of the CDB looked simpler (which makes sense, 
> since it only allowed the in-memory compile commands, but the new 
> implementation also falls back to the base CDB, i.e. it's now doing two 
> things).


Yeah, this is more complicated than the old `InMemoryCompilationDatabase`, but 
simpler than `InMemoryCompilationDatabase` + `ClangdLSPServer::CompilationDb` 
together, which it's replacing.




Comment at: clangd/ClangdLSPServer.cpp:670
+  /*Output=*/"");
+  if (Old != New)
+CDB->setCompileCommand(File, std::move(New));

ilya-biryukov wrote:
> Is this an optimization to not trigger compile command changes?
> Can we perform it on the CDB level to make sure we hit it in the future if 
> more code calling `setCompileCommand` is added?
> Is this an optimization to not trigger compile command changes?
This is my attempt to preserve the optimization from rL338597, without having 
to keep the more complex interface to setCompileCommand.
(And fix a bug in it: if there was an old command and you change it, you should 
refresh).

The optimisation seems kind of suspect to me to be honest (if it's worth doing, 
it's probably worth doing right - i.e. per-file, not globally), but it's easy 
enough to preserve for now.

> Can we perform it on the CDB level to make sure we hit it in the future if 
> more code calling setCompileCommand is added?
Not quite sure what you mean: ClangdLSPServer needs to check whether there were 
changes in order to decide whether to invalidate. Having CompilationDatabase 
*also* aware of changes seems more complex/coupled and no less error-prone.



Comment at: clangd/ClangdLSPServer.h:42
   ClangdLSPServer(Transport &Transp, const clangd::CodeCompleteOptions &CCOpts,
-  llvm::Optional CompileCommandsDir,
-  bool ShouldUseInMemoryCDB, const ClangdServer::Options 
&Opts);
+  llvm::Optional CompileCommandsDir, bool NoReadCDB,
+  const ClangdServer::Options &Opts);

ilya-biryukov wrote:
> NIT: the negative variable names might cause confusion (i.e. the double 
> negations are hard to read). Maybe use the name of the corresponding field 
> (UseDirectoryCDB)?
I was reluctant to replace a bool constructor parameter with a bool that does 
the exact opposite, but we do only have one callsite...



Comment at: clangd/GlobalCompilationDatabase.h:79
+/// using an in-memory mapping.
+class OverlayCDB : public GlobalCompilationDatabase {
 public:

ilya-biryukov wrote:
> The name does not seem to fully capture what this class does, i.e. allowing 
> to override compile commands for some files.
> Maybe use `OverridenCDB` or something similar?
Hmm, I feel the opposite way about these names - overlaying is exactly 
selective overriding of some elements, and overriding is more vague.

I did try to think of some other names, I almost like "mutable" but it's not 
actually essential, e.g. we don't allow the fallback flags to be mutated.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53687



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


[PATCH] D53687: [clangd] Make in-memory CDB always available as an overlay, refactor.

2018-10-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 171098.
sammccall marked an inline comment as done.
sammccall added a comment.

Switch boolean parameters to positive sense, rebase.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53687

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/tool/ClangdMain.cpp
  test/clangd/extra-flags.test
  unittests/clangd/GlobalCompilationDatabaseTests.cpp

Index: unittests/clangd/GlobalCompilationDatabaseTests.cpp
===
--- unittests/clangd/GlobalCompilationDatabaseTests.cpp
+++ unittests/clangd/GlobalCompilationDatabaseTests.cpp
@@ -33,6 +33,61 @@
testPath("foo/bar.h")));
 }
 
+static tooling::CompileCommand cmd(StringRef File, StringRef Arg) {
+  return tooling::CompileCommand(testRoot(), File, {"clang", Arg, File}, "");
+}
+
+class OverlayCDBTest : public ::testing::Test {
+  class BaseCDB : public GlobalCompilationDatabase {
+  public:
+Optional
+getCompileCommand(StringRef File) const override {
+  if (File == testPath("foo.cc"))
+return cmd(File, "-DA=1");
+  return None;
+}
+
+tooling::CompileCommand getFallbackCommand(StringRef File) const override {
+  return cmd(File, "-DA=2");
+}
+  };
+
+protected:
+  OverlayCDBTest() : Base(llvm::make_unique()) {}
+  std::unique_ptr Base;
+};
+
+TEST_F(OverlayCDBTest, GetCompileCommand) {
+  OverlayCDB CDB(Base.get());
+  EXPECT_EQ(CDB.getCompileCommand(testPath("foo.cc")),
+Base->getCompileCommand(testPath("foo.cc")));
+  EXPECT_EQ(CDB.getCompileCommand(testPath("missing.cc")), llvm::None);
+
+  auto Override = cmd(testPath("foo.cc"), "-DA=3");
+  CDB.setCompileCommand(testPath("foo.cc"), Override);
+  EXPECT_EQ(CDB.getCompileCommand(testPath("foo.cc")), Override);
+  EXPECT_EQ(CDB.getCompileCommand(testPath("missing.cc")), llvm::None);
+  CDB.setCompileCommand(testPath("missing.cc"), Override);
+  EXPECT_EQ(CDB.getCompileCommand(testPath("missing.cc")), Override);
+}
+
+TEST_F(OverlayCDBTest, GetFallbackCommand) {
+  OverlayCDB CDB(Base.get(), {"-DA=4"});
+  EXPECT_THAT(CDB.getFallbackCommand(testPath("bar.cc")).CommandLine,
+  ElementsAre("clang", "-DA=2", testPath("bar.cc"), "-DA=4"));
+}
+
+TEST_F(OverlayCDBTest, NoBase) {
+  OverlayCDB CDB(nullptr, {"-DA=6"});
+  EXPECT_EQ(CDB.getCompileCommand(testPath("bar.cc")), None);
+  auto Override = cmd(testPath("bar.cc"), "-DA=5");
+  CDB.setCompileCommand(testPath("bar.cc"), Override);
+  EXPECT_EQ(CDB.getCompileCommand(testPath("bar.cc")), Override);
+
+  EXPECT_THAT(CDB.getFallbackCommand(testPath("foo.cc")).CommandLine,
+  ElementsAre("clang", testPath("foo.cc"), "-DA=6"));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: test/clangd/extra-flags.test
===
--- test/clangd/extra-flags.test
+++ /dev/null
@@ -1,52 +0,0 @@
-# RUN: clangd -lit-test < %s | FileCheck -strict-whitespace %s
-{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}

-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","version":1,"text":"int main() { int i; return i; }"},"metadata":{"extraFlags":["-Wall"]}}}
-#  CHECK:  "method": "textDocument/publishDiagnostics",
-# CHECK-NEXT:  "params": {
-# CHECK-NEXT:"diagnostics": [
-# CHECK-NEXT:  {
-# CHECK-NEXT:"message": "Variable 'i' is uninitialized when used here",
-# CHECK-NEXT:"range": {
-# CHECK-NEXT:  "end": {
-# CHECK-NEXT:"character": 28,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "start": {
-# CHECK-NEXT:"character": 27,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  }
-# CHECK-NEXT:},
-# CHECK-NEXT:"severity": 2
-# CHECK-NEXT:  }
-# CHECK-NEXT:],
-# CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
-# CHECK-NEXT:  }

-{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"test:///foo.c","version":2},"contentChanges":[{"text":"int main() { int i; return i+1; }"}]}}
-#  CHECK:  "method": "textDocument/publishDiagnostics",
-# CHECK-NEXT:  "params": {
-# CHECK-NEXT:"diagnostics": [
-# CHECK-NEXT:  {
-# CHECK-NEXT:"message": "Variable 'i' is uninitialized when used here",
-# CHECK-NEXT:"range": {
-# CHECK-NEXT:  "end": {
-# CHECK-NEXT:"character": 28,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "start": {
-# CHECK-NEXT:"character": 27,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  }
-# CHECK-NEXT:},
-# CHECK-NEXT:"s

[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 171099.
kadircet marked an inline comment as done.
kadircet added a comment.

- Use addConstructorResult.


Repository:
  rC Clang

https://reviews.llvm.org/D53654

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/ctor-initializer.cpp
  test/Index/complete-ctor-inits.cpp
  test/Index/complete-cxx-inline-methods.cpp

Index: test/Index/complete-cxx-inline-methods.cpp
===
--- test/Index/complete-cxx-inline-methods.cpp
+++ test/Index/complete-cxx-inline-methods.cpp
@@ -35,10 +35,9 @@
 // CHECK-NEXT: Container Kind: StructDecl
 
 // RUN: c-index-test -code-completion-at=%s:18:41 %s | FileCheck -check-prefix=CHECK-CTOR-INIT %s
-// CHECK-CTOR-INIT: NotImplemented:{TypedText MyCls}{LeftParen (}{Placeholder args}{RightParen )} (7)
-// CHECK-CTOR-INIT: MemberRef:{TypedText object}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CTOR-INIT: MemberRef:{TypedText value}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CTOR-INIT: MemberRef:{TypedText object}{LeftParen (}{Placeholder MyCls *}{RightParen )} (35)
+// CHECK-CTOR-INIT: MemberRef:{TypedText value}{LeftParen (}{Placeholder int}{RightParen )} (35)
 // RUN: c-index-test -code-completion-at=%s:18:55 %s | FileCheck -check-prefix=CHECK-CTOR-INIT-2 %s
-// CHECK-CTOR-INIT-2-NOT: NotImplemented:{TypedText MyCls}{LeftParen (}{Placeholder args}{RightParen )}
-// CHECK-CTOR-INIT-2: MemberRef:{TypedText object}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CTOR-INIT-2: MemberRef:{TypedText value}{LeftParen (}{Placeholder args}{RightParen )} (7)
+// CHECK-CTOR-INIT-2-NOT: ClassDecl:{TypedText MyCls} (7)
+// CHECK-CTOR-INIT-2: MemberRef:{TypedText object}{LeftParen (}{Placeholder MyCls *}{RightParen )} (35)
+// CHECK-CTOR-INIT-2: MemberRef:{TypedText value}{LeftParen (}{Placeholder int}{RightParen )} (35)
Index: test/Index/complete-ctor-inits.cpp
===
--- test/Index/complete-ctor-inits.cpp
+++ test/Index/complete-ctor-inits.cpp
@@ -30,27 +30,33 @@
 };
 
 // RUN: c-index-test -code-completion-at=%s:18:10 %s | FileCheck -check-prefix=CHECK-CC1 %s
-// CHECK-CC1: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: MemberRef:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: NotImplemented:{TypedText X}{LeftParen (}{Placeholder args}{RightParen )} (7)
-// CHECK-CC1: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CC1: MemberRef:{TypedText a}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: MemberRef:{TypedText b}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: MemberRef:{TypedText c}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder const Virt &}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder Virt &&}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText X}{LeftParen (}{Placeholder int}{RightParen )} (7)
+// CHECK-CC1: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder const Y &}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder Y &&}{RightParen )} (35)
 
 // RUN: c-index-test -code-completion-at=%s:18:23 %s | FileCheck -check-prefix=CHECK-CC2 %s
-// CHECK-CC2: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: MemberRef:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (7)
+// CHECK-CC2: MemberRef:{TypedText a}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: MemberRef:{TypedText b}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: MemberRef:{TypedText c}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder const Virt &}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder Virt &&}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder const Y &}{RightParen )} (7)
+// CHECK-CC2: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder Y &&}{RightParen )} (7)
 
 // RUN: c-index-test -code-completion-at=%s:18:36 %s | FileCheck -check-prefix=CHECK-CC3 %s
-// CHECK-CC3: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC3-NOT: MemberRef

[PATCH] D53488: [clang-tidy] Catching narrowing from double to float.

2018-10-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In https://reviews.llvm.org/D53488#1275750, @gchatelet wrote:

> In https://reviews.llvm.org/D53488#1274205, @JonasToth wrote:
>
> > Did you run this code over a real-world code-base and did you find new 
> > stuff and/or false positives or the like?
>
>
> Yes I did run it over our code base. I didn't find false positive but 98% of 
> the warnings are from large generated lookup table initializers, e.g. `const 
> static float kTable[] = {0.0, 2.0, ... };`
>  Since every number in the list triggers the warning, it accounts for most of 
> them.
>
> I scrutinized a few hundreds of the rest: none were actual bugs (although 
> it's hard to tell sometimes), most are legit like `float value = 0.0;` but I 
> also found some oddities 
> 
>  from generated headers.
>
> To me the warnings are useful and if it were my code I'd be willing to fix 
> them. That said, I'd totally understand that many people would find them 
> useless or annoying.
>  What do you think? Shall we still commit this as is?


It would be nice to know how many new findings does this patch introduce 
(number of findings before the patch vs after). If it is not too much, it is 
fine the commit as it is.
I'd suggest to run the check on llvm code repository (using 
`clang-tidy/tool/run-clang-tidy.py`, and only enable 
`cppcoreguidelines-narrowing-conversions`).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488



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


[PATCH] D53617: [AArch64] Support Windows stack probe command-line arguments.

2018-10-25 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rC Clang

https://reviews.llvm.org/D53617



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


[PATCH] D53688: [clangd] Add fallbackFlags initialization extension.

2018-10-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In https://reviews.llvm.org/D53688#1275586, @ilya-biryukov wrote:

> This feels like a configuration option that might be changed in the course of 
> running clangd.
>  Are there any strong reasons to make it work only upon initialization? My 
> guess is that it keeps the code simpler, but if we approached it purely from 
> the UX perspective, changing it while running clangd seems to make sense. 
> WDYT?


It's hard to reason about UX outside of concrete tools - the only use I know of 
(atom-ide-cpp) never needs to change it, and I'm having a hard time imagining 
when you'd want to change this, but still have it global to clangd. (I can 
imagine it being scoped to a subtree a la compile commands, but that's a whole 
different thing..)

And yes, there are significant implementation concerns with making it mutable: 
ultimately we're going to want to have a CDB -> clangd compile command 
invalidation mechanism that can drive reindexing, reloading diagnostics etc. If 
the fallback command is mutable, such a mechanism needs to handle wildcards (or 
accept that this is a case it will get wrong, there are others).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53688



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


[PATCH] D53025: [clang-tidy] implement new check for const return types.

2018-10-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 171103.
ymandel added a comment.

Fix bug in const-token finding and add tests.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53025

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/ConstValueReturnCheck.cpp
  clang-tidy/readability/ConstValueReturnCheck.h
  clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-const-value-return.rst
  test/clang-tidy/readability-const-value-return.cpp

Index: test/clang-tidy/readability-const-value-return.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-const-value-return.cpp
@@ -0,0 +1,226 @@
+// RUN: %check_clang_tidy %s readability-const-value-return %t -- -- -isystem
+
+//  p# = positive test
+//  n# = negative test
+
+#include 
+
+const int p1() {
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const int' is 'const'-qualified hindering compiler optimizations
+// CHECK-FIXES: int p1() {
+  return 1;
+}
+
+const int p15();
+// CHECK-FIXES: int p15();
+
+template 
+const int p31(T v) { return 2; }
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const int' is 'const'-qu
+// CHECK-FIXES: int p31(T v) { return 2; }
+
+// We detect const-ness even without instantiating T.
+template 
+const T p32(T t) { return t; }
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const T' is 'const'-qual
+// CHECK-FIXES: T p32(T t) { return t; }
+
+// However, if the return type is itself a template instantiation, Clang does
+// not consider it const-qualified without knowing `T`.
+template 
+typename std::add_const::type n15(T v) { return v; }
+
+template 
+class Klazz {
+public:
+  Klazz(A) {}
+};
+
+class Clazz {
+ public:
+  Clazz *const p2() {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'Clazz *const' is 'co
+// CHECK-FIXES: Clazz *p2() {
+return this;
+  }
+
+  Clazz *const p3();
+  // CHECK-FIXES: Clazz *p3();
+
+  const int p4() const {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const
+// CHECK-FIXES: int p4() const {
+return 4;
+  }
+
+  const Klazz* const p5() const;
+  // CHECK-FIXES: const Klazz* p5() const;
+
+  const Clazz operator++(int x) {  //  p12
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const Clazz' is 'const
+  // CHECK-FIXES: Clazz operator++(int x) {
+  }
+
+  struct Strukt {
+int i;
+  };
+
+  const Strukt p6() {}
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const Clazz::Strukt' i
+  // CHECK-FIXES: Strukt p6() {}
+
+  // No warning is emitted here, because this is only the declaration.  The
+  // warning will be associated with the definition, below.
+  const Strukt* const p7();
+  // CHECK-FIXES: const Strukt* p7();
+
+  // const-qualifier is the first `const` token, but not the first token.
+  static const int p8() {}
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const'-
+  // CHECK-FIXES: static int p8() {}
+
+  static const Strukt p9() {}
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const Clazz::Strukt' i
+  // CHECK-FIXES: static Strukt p9() {}
+
+  int n0() const { return 0; }
+  const Klazz& n11(const Klazz) const;
+};
+
+Clazz *const Clazz::p3() {
+  // CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'Clazz *const' is 'cons
+  // CHECK-FIXES: Clazz *Clazz::p3() {
+  return this;
+}
+
+const Klazz* const Clazz::p5() const {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Klazz *
+// CHECK-FIXES: const Klazz* Clazz::p5() const {}
+
+const Clazz::Strukt* const Clazz::p7() {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Clazz::Strukt *con
+// CHECK-FIXES: const Clazz::Strukt* Clazz::p7() {}
+
+Clazz *const p10();
+// CHECK-FIXES: Clazz *p10();
+
+Clazz *const p10() {
+  // CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'Clazz *const' is 'cons
+  // CHECK-FIXES: Clazz *p10() {
+  return new Clazz();
+}
+
+const Clazz bar;
+const Clazz *const p11() {
+  // CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Clazz *const' is
+  // CHECK-FIXES: const Clazz *p11() {
+  return &bar;
+}
+
+const Klazz p12() {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Klazz'
+// CHECK-FIXES: Klazz p12() {}
+
+const Klazz* const p13() {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Klazz *
+// CHECK-FIXES: const Klazz* p13() {}
+
+// re-declaration of p15.
+const int p15();
+// CHECK-FIXES: int p15();
+
+const int p15() {
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning:
+// CHECK-FIXES: int p15() {
+  return 0;
+}
+
+// Exercise the lexer.
+
+const /* comment */ /* another comment*/ int p16() { return 0; }
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning:
+// CHECK-FIXES: /* comment */ /* another comment*/ int p16() { return 0; }
+
+/* comment */

[PATCH] D53025: [clang-tidy] implement new check for const return types.

2018-10-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 171105.
ymandel added a comment.

Formatting & comment tweaks.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53025

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/ConstValueReturnCheck.cpp
  clang-tidy/readability/ConstValueReturnCheck.h
  clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-const-value-return.rst
  test/clang-tidy/readability-const-value-return.cpp

Index: test/clang-tidy/readability-const-value-return.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-const-value-return.cpp
@@ -0,0 +1,227 @@
+// RUN: %check_clang_tidy %s readability-const-value-return %t -- -- -isystem
+
+//  p# = positive test
+//  n# = negative test
+
+#include 
+
+const int p1() {
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const int' is 'const'-qualified hindering compiler optimizations
+// CHECK-FIXES: int p1() {
+  return 1;
+}
+
+const int p15();
+// CHECK-FIXES: int p15();
+
+template 
+const int p31(T v) { return 2; }
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const int' is 'const'-qu
+// CHECK-FIXES: int p31(T v) { return 2; }
+
+// We detect const-ness even without instantiating T.
+template 
+const T p32(T t) { return t; }
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const T' is 'const'-qual
+// CHECK-FIXES: T p32(T t) { return t; }
+
+// However, if the return type is itself a template instantiation, Clang does
+// not consider it const-qualified without knowing `T`.
+template 
+typename std::add_const::type n15(T v) { return v; }
+
+template 
+class Klazz {
+public:
+  Klazz(A) {}
+};
+
+class Clazz {
+ public:
+  Clazz *const p2() {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'Clazz *const' is 'co
+// CHECK-FIXES: Clazz *p2() {
+return this;
+  }
+
+  Clazz *const p3();
+  // CHECK-FIXES: Clazz *p3();
+
+  const int p4() const {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const
+// CHECK-FIXES: int p4() const {
+return 4;
+  }
+
+  const Klazz* const p5() const;
+  // CHECK-FIXES: const Klazz* p5() const;
+
+  const Clazz operator++(int x) {  //  p12
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const Clazz' is 'const
+  // CHECK-FIXES: Clazz operator++(int x) {
+  }
+
+  struct Strukt {
+int i;
+  };
+
+  const Strukt p6() {}
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const Clazz::Strukt' i
+  // CHECK-FIXES: Strukt p6() {}
+
+  // No warning is emitted here, because this is only the declaration.  The
+  // warning will be associated with the definition, below.
+  const Strukt* const p7();
+  // CHECK-FIXES: const Strukt* p7();
+
+  // const-qualifier is the first `const` token, but not the first token.
+  static const int p8() {}
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const int' is 'const'-
+  // CHECK-FIXES: static int p8() {}
+
+  static const Strukt p9() {}
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: return type 'const Clazz::Strukt' i
+  // CHECK-FIXES: static Strukt p9() {}
+
+  int n0() const { return 0; }
+  const Klazz& n11(const Klazz) const;
+};
+
+Clazz *const Clazz::p3() {
+  // CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'Clazz *const' is 'cons
+  // CHECK-FIXES: Clazz *Clazz::p3() {
+  return this;
+}
+
+const Klazz* const Clazz::p5() const {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Klazz *
+// CHECK-FIXES: const Klazz* Clazz::p5() const {}
+
+const Clazz::Strukt* const Clazz::p7() {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Clazz::Strukt *con
+// CHECK-FIXES: const Clazz::Strukt* Clazz::p7() {}
+
+Clazz *const p10();
+// CHECK-FIXES: Clazz *p10();
+
+Clazz *const p10() {
+  // CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'Clazz *const' is 'cons
+  // CHECK-FIXES: Clazz *p10() {
+  return new Clazz();
+}
+
+const Clazz bar;
+const Clazz *const p11() {
+  // CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Clazz *const' is
+  // CHECK-FIXES: const Clazz *p11() {
+  return &bar;
+}
+
+const Klazz p12() {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Klazz'
+// CHECK-FIXES: Klazz p12() {}
+
+const Klazz* const p13() {}
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: return type 'const Klazz *
+// CHECK-FIXES: const Klazz* p13() {}
+
+// re-declaration of p15.
+const int p15();
+// CHECK-FIXES: int p15();
+
+const int p15() {
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning:
+// CHECK-FIXES: int p15() {
+  return 0;
+}
+
+// Exercise the lexer.
+
+const /* comment */ /* another comment*/ int p16() { return 0; }
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning:
+// CHECK-FIXES: /* comment */ /* another comment*/ int p16() { return 0; }
+
+/* comment */ const
+// CHECK-

[PATCH] D53025: [clang-tidy] implement new check for const return types.

2018-10-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In https://reviews.llvm.org/D53025#1271367, @JonasToth wrote:

> In https://reviews.llvm.org/D53025#1270784, @ymandel wrote:
>
> > Correction: the code *catches* the trailing return cases, I just couldn't 
> > find a way to *fix* them; specifically, I was not able to get the necessary 
> > source ranges to re-lex the trailing return type.
>
>
> There is `fuchsia/TrailingReturnCheck.cpp` which you look if there is 
> something, I am currently not aware of other checks that handle trailing 
> return types in any way.
>  In principle it is ok to leave these for future improvements, but should be 
> noted as limitation in the docs.


Thanks. Unfortuantely, that code doesn't have what I want.  I've updated the 
.rst doc to mention this shortcoming.   I'm happy to come back in the future 
and add support if I can get it figured out.  However, I'd rather not black on 
this at the moment, if that's ok.

In https://reviews.llvm.org/D53025#1271388, @JonasToth wrote:

> > Also, the template version (whether trailing or normal return) does not 
> > trigger the matchers at all, from which I surmise that clang doesn't 
> > consider the type const qualified when it is not materialized with an 
> > actual type. I've noted as much in the comments, but please correct me if 
> > I've misunderstood.
>
> If the template is not instantiated no information on `const` exists and
>  that might vary between instantiations anyway (if you don't explicitly
>  write `const T`). It would be an interesting test to try and break the
>  check with an explicit `const` template and instantiaions with `const`.
>  (e.g. `template  const T my_function();` and an
>  instantiation like `gsl::span`)


I'm not sure I understand what you're trying to break in the check. If you're 
thinking of whether the code trips up on the lexical issues, I'm pretty sure 
that won't apply here.  Once the const-ness is hidden behind a template, the 
check doesn't try to fix it; so, lexical issues don't come into play.  It boils 
down to the whether the matcher for const-ness is implemented correctly.  But, 
I did add a new test based on this:
`template  const T p32(T t) { return t; }`
which *is* detected and fixed.  Let me know, though, if you want something more 
elaborate.  Also, see below, where I *did* find a bug in a related kind of type 
definition.

>> Finally, as for triggering: I ran this over Google's C++ codebase and found 
>> quite a few hits (10k < X < 100k;  not sure I'm allowed to specify a more 
>> precise value for X, but if you need it,  let me know and I'll ask).  I 
>> sampled 100 of them and confirmed that all were correct.
>> 
>> I also looked at LLVM and found ~130 hits. I sampled 10 and again found them 
>> all correct. I'm happy to post all of the llvm hits if you think that would 
>> be helpful.
> 
> Did you try the transformation and is it correct (does not break code)?
>  Enough to check on LLVM :)

Good call -- found bugs this way in one of the files, which had two errors of 
the sort you were asking about above:
https://reviews.llvm.org/source/test-suite/browse/test-suite/trunk/SingleSource/Benchmarks/Misc-C%2B%2B-EH/spirit.cpp;344155$2204
https://reviews.llvm.org/source/test-suite/browse/test-suite/trunk/SingleSource/Benchmarks/Misc-C%2B%2B-EH/spirit.cpp;344155$3133

I've modified the code that finds the const token to fix this bug.  In the 
process, I simplified it and (I think) found a more general solution to the 
problem.  I also noticed that this same bug exists in the  
AvoidConstParamsInDecls check, so I plan to send a follow up change that fixes 
that check by having it use the newly introduced `getConstQualifyingToken` 
function.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53025



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


[PATCH] D53488: [clang-tidy] Catching narrowing from double to float.

2018-10-25 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet added a comment.

In https://reviews.llvm.org/D53488#1275786, @hokein wrote:

> In https://reviews.llvm.org/D53488#1275750, @gchatelet wrote:
>
> > In https://reviews.llvm.org/D53488#1274205, @JonasToth wrote:
> >
> > > Did you run this code over a real-world code-base and did you find new 
> > > stuff and/or false positives or the like?
> >
> >
> > Yes I did run it over our code base. I didn't find false positive but 98% 
> > of the warnings are from large generated lookup table initializers, e.g. 
> > `const static float kTable[] = {0.0, 2.0, ... };`
> >  Since every number in the list triggers the warning, it accounts for most 
> > of them.
> >
> > I scrutinized a few hundreds of the rest: none were actual bugs (although 
> > it's hard to tell sometimes), most are legit like `float value = 0.0;` but 
> > I also found some oddities 
> > 
> >  from generated headers.
> >
> > To me the warnings are useful and if it were my code I'd be willing to fix 
> > them. That said, I'd totally understand that many people would find them 
> > useless or annoying.
> >  What do you think? Shall we still commit this as is?
>
>
> It would be nice to know how many new findings does this patch introduce 
> (number of findings before the patch vs after). If it is not too much, it is 
> fine the commit as it is.
>  I'd suggest to run the check on llvm code repository (using 
> `clang-tidy/tool/run-clang-tidy.py`, and only enable 
> `cppcoreguidelines-narrowing-conversions`).


I'll get back with some numbers.

In the meantime I found this one which is interesting
https://github.com/intel/ipmctl/blob/master/src/os/efi_shim/lnx_efi_api.c#L45
`spec.tv_nsec` (which is signed long) is converted to double and back to int64. 
There surely can be some loss in the process since `double` can //only// 
express 2^52 integers (2^52ns is about 52 days)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488



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


r345273 - [AArch64] Branch Protection and Return Address Signing B Key Support

2018-10-25 Thread Luke Cheeseman via cfe-commits
Author: lukecheeseman
Date: Thu Oct 25 08:23:49 2018
New Revision: 345273

URL: http://llvm.org/viewvc/llvm-project?rev=345273&view=rev
Log:
[AArch64] Branch Protection and Return Address Signing B Key Support

- Add support for -mbranch-protection=[+]* where
  -  ::= [standard, none, bti, pac-ret[+b-key,+leaf]*]
- The protection emits relevant function attributes
  - sign-return-address=
  - sign-return-address-key=
  - branch-protection


Modified:
cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/include/clang/Frontend/CodeGenOptions.def
cfe/trunk/include/clang/Frontend/CodeGenOptions.h
cfe/trunk/lib/CodeGen/CGDeclCXX.cpp
cfe/trunk/lib/CodeGen/TargetInfo.cpp
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/CodeGen/aarch64-sign-return-address.c
cfe/trunk/test/CodeGenCXX/aarch64-sign-return-address-static-ctor.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=345273&r1=345272&r2=345273&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Thu Oct 25 08:23:49 
2018
@@ -279,6 +279,8 @@ def warn_drv_disabling_vptr_no_rtti_defa
 def warn_drv_object_size_disabled_O0 : Warning<
   "the object size sanitizer has no effect at -O0, but is explicitly enabled: 
%0">,
   InGroup, DefaultWarnNoWerror;
+def err_invalid_branch_protection: Error <
+  "invalid branch protection option '%0' in '%1'">;
 
 def note_drv_command_failed_diag_msg : Note<
   "diagnostic msg: %0">;

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=345273&r1=345272&r2=345273&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Thu Oct 25 08:23:49 2018
@@ -354,6 +354,12 @@ def fdebug_pass_manager : Flag<["-"], "f
 HelpText<"Prints debug information for the new pass manager">;
 def fno_debug_pass_manager : Flag<["-"], "fno-debug-pass-manager">,
 HelpText<"Disables debug printing for the new pass manager">;
+// The driver option takes the key as a parameter to the -msign-return-address=
+// and -mbranch-protection= options, but CC1 has a separate option so we
+// don't have to parse the parameter twice.
+def msign_return_address_key_EQ : Joined<["-"], "msign-return-address-key=">,
+Values<"a_key,b_key">;
+def mbranch_target_enforce : Flag<["-"], "mbranch-target-enforce">;
 
 
//===--===//
 // Dependency Output Options

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=345273&r1=345272&r2=345273&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Thu Oct 25 08:23:49 2018
@@ -2071,9 +2071,11 @@ foreach i = {8-15,18} in
   def fcall_saved_x#i : Flag<["-"], "fcall-saved-x"#i>, 
Group,
 HelpText<"Make the x"#i#" register call-saved (AArch64 only)">;
 
-def msign_return_address : Joined<["-"], "msign-return-address=">,
-  Flags<[CC1Option]>, Group,
-  HelpText<"Select return address signing scope">, Values<"none,all,non-leaf">;
+def msign_return_address_EQ : Joined<["-"], "msign-return-address=">,
+  Flags<[CC1Option]>, Group, Values<"none,all,non-leaf">,
+  HelpText<"Select return address signing scope">;
+def mbranch_protection_EQ : Joined<["-"], "mbranch-protection=">,
+  HelpText<"Enforce targets of indirect branches and function returns">;
 
 def msimd128 : Flag<["-"], "msimd128">, Group;
 def mno_simd128 : Flag<["-"], "mno-simd128">, Group;

Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.def?rev=345273&r1=345272&r2=345273&view=diff
==
--- cfe/trunk/include/clang/Frontend/CodeGenOptions.def (original)
+++ cfe/trunk/include/clang/Frontend/CodeGenOptions.def Thu Oct 25 08:23:49 2018
@@ -343,6 +343,8 @@ CODEGENOPT(ForceEmitVTables, 1, 0)
 CODEGENOPT(Addrsig, 1, 0)
 
 ENUM_CODEGENOPT(SignReturnAddress, SignReturnAddressScope, 2, None)
+ENUM_CODEGENOPT(SignReturnAddressKey, SignReturnAddressKeyValue, 1, AKey)
+CODEGENOPT(BranchTargetEnforcement, 1, 0)
 
 /// Whether to emit unused static constants.
 CODEGENOPT(KeepStaticConsts, 1, 0)

Modified: cfe/trunk/incl

[PATCH] D53705: [OpenCL] Postpone PSV address space diagnostic

2018-10-25 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added reviewers: Anastasia, rjmccall.
Herald added subscribers: cfe-commits, yaxunl.

In OpenCL C++ mode, the "program scope variable must reside ..."
diagnostic is firing early in some cases, potentially confusing the
user.  It is the first diagnostic reported for

  int g(global int *p) {}

but the actual problem is the undeclared identifier `global`.

The main reason to improve error reporting for the example above is
that OpenCL C address space qualifiers such as `global` are not part
of OpenCL C++.  This means the PSV diagnostic will fire when porting
OpenCL C code to OpenCL C++ if an address space qualifier is left in
by accident.

The PSV diagnostic is emitted for the example above because the parser
believes `g` is a variable declaration instead of a function
declaration.  This seems to be inherent to C++ parsing, so postpone
the PSV diagnostic until we have parsed the entire declarator group.
We still get the PSV diagnostic for the example, but it is no longer
the first so it should be easier for the user to see what the actual
problem is.


Repository:
  rC Clang

https://reviews.llvm.org/D53705

Files:
  lib/Sema/SemaDecl.cpp
  test/SemaOpenCL/storageclass-cl20.cl
  test/SemaOpenCL/storageclass.cl
  test/SemaOpenCLCXX/invalid-qualifier.cl

Index: test/SemaOpenCLCXX/invalid-qualifier.cl
===
--- /dev/null
+++ test/SemaOpenCLCXX/invalid-qualifier.cl
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -cl-std=c++ -pedantic -fsyntax-only -verify
+// RUN: not %clang_cc1 %s -triple spir-unknown-unknown -cl-std=c++ -pedantic -fsyntax-only 2>&1 | FileCheck %s
+
+// Use FileCheck to check that "program scope variable must reside ..." is not
+// the first diagnostic reported.
+
+int f1(global int *p) {}
+// expected-error@-1{{use of undeclared identifier 'global'}}
+// expected-error@-2{{expected ';' after top level declarator}}
+// expected-error@-3{{program scope variable must reside in constant address space}}
+// CHECK: use of undeclared identifier 'global'
+// CHECK: program scope variable must reside in constant address space
+
+; // For parser recovery.
+
+int f2(local int *p) {}
+// expected-error@-1{{use of undeclared identifier 'local'}}
+// expected-error@-2{{expected ';' after top level declarator}}
+// expected-error@-3{{program scope variable must reside in constant address space}}
+// CHECK: use of undeclared identifier 'local'
+// CHECK: program scope variable must reside in constant address space
+
+; // For parser recovery.
+
+int g(abcdef int q) {}
+// expected-error@-1{{use of undeclared identifier 'abcdef'}}
+// expected-error@-2{{expected ';' after top level declarator}}
+// expected-error@-3{{program scope variable must reside in constant address space}}
+// CHECK: use of undeclared identifier 'abcdef'
+// CHECK: program scope variable must reside in constant address space
+
+; // For parser recovery.
Index: test/SemaOpenCL/storageclass.cl
===
--- test/SemaOpenCL/storageclass.cl
+++ test/SemaOpenCL/storageclass.cl
@@ -4,11 +4,12 @@
 constant int G2 = 0;
 int G3 = 0;// expected-error{{program scope variable must reside in constant address space}}
 global int G4 = 0; // expected-error{{program scope variable must reside in constant address space}}
+int G5, G6;// expected-error 2 {{program scope variable must reside in constant address space}}
 
 static float g_implicit_static_var = 0; // expected-error {{program scope variable must reside in constant address space}}
 static constant float g_constant_static_var = 0;
 static global float g_global_static_var = 0;   // expected-error {{program scope variable must reside in constant address space}}
-static local float g_local_static_var = 0; // expected-error {{program scope variable must reside in constant address space}}
+static local float g_local_static_var = 0; // expected-error {{'__local' variable cannot have an initializer}}
 static private float g_private_static_var = 0; // expected-error {{program scope variable must reside in constant address space}}
 static generic float g_generic_static_var = 0; // expected-error{{OpenCL C version 1.2 does not support the 'generic' type qualifier}} // expected-error {{program scope variable must reside in constant address space}}
 
Index: test/SemaOpenCL/storageclass-cl20.cl
===
--- test/SemaOpenCL/storageclass-cl20.cl
+++ test/SemaOpenCL/storageclass-cl20.cl
@@ -2,12 +2,12 @@
 
 int G2 = 0;
 global int G3 = 0;
-local int G4 = 0;  // expected-error{{program scope variable must reside in global or constant address space}}
+local int G4 = 0;  // expected-error{{'__local' variable cannot have an initializer}}
 
 static float g_implicit_static_var = 0;
 static constant float g_constant_static_var = 0;
 static 

[PATCH] D53417: [Clang][Sema][PowerPC] Choose a better candidate in overload function call if there is a compatible vector conversion instead of ambiguous call error

2018-10-25 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:3913
+for (auto Type : Types) {
+  if (S.Context.getCanonicalType(Type)->getTypeClass() != Type::Vector)
+return false;

Considering that this is a local lambda called in one place, are we expecting 
cases where the canonical type is not something on which we can call 
getVectorKind()? If not, then we do not need this `if`.


https://reviews.llvm.org/D53417



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


[PATCH] D51429: [AArch64] Return Address Signing B Key Support

2018-10-25 Thread Luke Cheeseman via Phabricator via cfe-commits
LukeCheeseman closed this revision.
LukeCheeseman added a comment.

This was committed under 345273. (Forgot to mention the revision in the commit 
message)


https://reviews.llvm.org/D51429



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


[PATCH] D38061: Set AnonymousTagLocations false for ASTContext if column info is expected not to be used

2018-10-25 Thread Taewook Oh via Phabricator via cfe-commits
twoh added a comment.

@dblaikie I see. The problem we're experiencing is that with Clang's naming 
scheme we end up having different function name between the original source and 
the preprocessed source (as macro expansion changes the column number). This 
doesn't work well for me if I want to use distcc on top of our caching system, 
as the caching scheme expects the output to be same as far as the original 
source has not been changed (regardless of it's compiled directly or first 
preprocessed then compiled), but the distcc preprocesses the source locally 
then sends it to the remote build machine (and we do not turn distcc on for all 
workflow). I wonder if you have any suggestion to resolve this issue? Thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D38061



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


[PATCH] D53687: [clangd] Make in-memory CDB always available as an overlay, refactor.

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

LGTM




Comment at: clangd/ClangdLSPServer.cpp:670
+  /*Output=*/"");
+  if (Old != New)
+CDB->setCompileCommand(File, std::move(New));

sammccall wrote:
> ilya-biryukov wrote:
> > Is this an optimization to not trigger compile command changes?
> > Can we perform it on the CDB level to make sure we hit it in the future if 
> > more code calling `setCompileCommand` is added?
> > Is this an optimization to not trigger compile command changes?
> This is my attempt to preserve the optimization from rL338597, without having 
> to keep the more complex interface to setCompileCommand.
> (And fix a bug in it: if there was an old command and you change it, you 
> should refresh).
> 
> The optimisation seems kind of suspect to me to be honest (if it's worth 
> doing, it's probably worth doing right - i.e. per-file, not globally), but 
> it's easy enough to preserve for now.
> 
> > Can we perform it on the CDB level to make sure we hit it in the future if 
> > more code calling setCompileCommand is added?
> Not quite sure what you mean: ClangdLSPServer needs to check whether there 
> were changes in order to decide whether to invalidate. Having 
> CompilationDatabase *also* aware of changes seems more complex/coupled and no 
> less error-prone.
Reparsing the files if compile commands did not change is (almost) a no-op now, 
so not sure it is worth it either.
SG to keep it for now, though.


> Not quite sure what you mean: ClangdLSPServer needs to check whether there 
> were changes in order to decide whether to invalidate. Having 
> CompilationDatabase *also* aware of changes seems more complex/coupled and no 
> less error-prone.
I initially thought this patch also adds watches for changes to compile 
commands (we discussed those yesterday), but the assumption was wrong, please 
ignore the comment.




Comment at: clangd/GlobalCompilationDatabase.h:79
+/// using an in-memory mapping.
+class OverlayCDB : public GlobalCompilationDatabase {
 public:

sammccall wrote:
> ilya-biryukov wrote:
> > The name does not seem to fully capture what this class does, i.e. allowing 
> > to override compile commands for some files.
> > Maybe use `OverridenCDB` or something similar?
> Hmm, I feel the opposite way about these names - overlaying is exactly 
> selective overriding of some elements, and overriding is more vague.
> 
> I did try to think of some other names, I almost like "mutable" but it's not 
> actually essential, e.g. we don't allow the fallback flags to be mutated.
Well, the comment is there so it's probably fine either way.
My reasoning behind "Overlay" is that it's usually a thing that combines two or 
more "layers", calling one after another, without introducing any extra 
functionality on its own.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53687



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


r345277 - [OPENMP]Fix PR39422: variables are not firstprivatized in task context.

2018-10-25 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Thu Oct 25 08:35:27 2018
New Revision: 345277

URL: http://llvm.org/viewvc/llvm-project?rev=345277&view=rev
Log:
[OPENMP]Fix PR39422: variables are not firstprivatized in task context.

According to the OpenMP standard, In a task generating construct, if no
default clause is present, a variable for which the data-sharing
attribute is not determined by the rules above is firstprivatized.
Compiler tries to implement this, but if the variable is not directly
used in the task context, this variable may not be firstprivatized.
Patch fixes this problem.

Modified:
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/parallel_sections_default_messages.cpp
cfe/trunk/test/OpenMP/task_codegen.cpp

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=345277&r1=345276&r2=345277&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Thu Oct 25 08:35:27 2018
@@ -2251,8 +2251,31 @@ public:
   }
   void VisitStmt(Stmt *S) {
 for (Stmt *C : S->children()) {
-  if (C && !isa(C))
-Visit(C);
+  if (C) {
+if (auto *OED = dyn_cast(C)) {
+  // Check implicitly captured vriables in the task-based directives to
+  // check if they must be firstprivatized.
+  if (!OED->hasAssociatedStmt())
+continue;
+  const Stmt *AS = OED->getAssociatedStmt();
+  if (!AS)
+continue;
+  for (const CapturedStmt::Capture &Cap :
+   cast(AS)->captures()) {
+if (Cap.capturesVariable()) {
+  DeclRefExpr *DRE = buildDeclRefExpr(
+  SemaRef, Cap.getCapturedVar(),
+  Cap.getCapturedVar()->getType().getNonLValueExprType(
+  SemaRef.Context),
+  Cap.getLocation(),
+  /*RefersToCapture=*/true);
+  Visit(DRE);
+}
+  }
+} else {
+  Visit(C);
+}
+  }
 }
   }
 

Modified: cfe/trunk/test/OpenMP/parallel_sections_default_messages.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/parallel_sections_default_messages.cpp?rev=345277&r1=345276&r2=345277&view=diff
==
--- cfe/trunk/test/OpenMP/parallel_sections_default_messages.cpp (original)
+++ cfe/trunk/test/OpenMP/parallel_sections_default_messages.cpp Thu Oct 25 
08:35:27 2018
@@ -34,7 +34,7 @@ int main(int argc, char **argv) {
   {
 #pragma omp parallel sections default(shared)
 {
-  ++argc;
+  ++argc;  // expected-error {{variable 'argc' must have explicitly 
specified data sharing attributes}}
 }
   }
   return 0;

Modified: cfe/trunk/test/OpenMP/task_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/task_codegen.cpp?rev=345277&r1=345276&r2=345277&view=diff
==
--- cfe/trunk/test/OpenMP/task_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/task_codegen.cpp Thu Oct 25 08:35:27 2018
@@ -107,6 +107,7 @@ int main() {
 // CHECK: call i32 @__kmpc_omp_task([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i8* 
[[ORIG_TASK_PTR]])
 #pragma omp task untied
   {
+#pragma omp critical
 a = 1;
   }
 // CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* 
@{{.+}}, i32 [[GTID]], i32 0, i64 40, i64 1,


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


[PATCH] D53688: [clangd] Add fallbackFlags initialization extension.

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

In https://reviews.llvm.org/D53688#1275793, @sammccall wrote:

> It's hard to reason about UX outside of concrete tools - the only use I know 
> of (atom-ide-cpp) never needs to change it, and I'm having a hard time 
> imagining when you'd want to change this, but still have it global to clangd. 
> (I can imagine it being scoped to a subtree a la compile commands, but that's 
> a whole different thing..)
>
> And yes, there are significant implementation concerns with making it 
> mutable: ultimately we're going to want to have a CDB -> clangd compile 
> command invalidation mechanism that can drive reindexing, reloading 
> diagnostics etc. If the fallback command is mutable, such a mechanism needs 
> to handle wildcards (or accept that this is a case it will get wrong, there 
> are others).


Whatever the tool is, the choices for it are to allow changing some 
configuration at the init time or while running. Just realized that we're 
removing the compileCommandsDir for that specific reason, sorry for being out 
of context here.

The atom-ide-cpp use case is somewhat special anyway, since it ends up reading 
a file in a format we already support, albeit having a different name from the 
one clangd would expect (correct me if I'm wrong on this one).
In the long-run it seems better to communicate to the users that they should 
rename the file to make clangd work rather than add this (a bit different and 
more powerful?) extension to clangd.

We're aiming to allow users change their compile flags while running clangd 
anyway (assuming we're gonna get the file watches in at some point), so, again, 
in the long-run I don't see why that would complicate things. But sympathetic 
to keeping the code simpler anyway.

LGTM


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53688



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


[PATCH] D53707: [Fixed Point Arithmetic] Refactor fixed point casts

2018-10-25 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope created this revision.
bjope added reviewers: leonardchan, ebevhan.

- Added names for some emitted values (such as "tobool" for the result of a 
cast to boolean).
- Replaced explicit IRBuilder request for doing sext/zext/trunc by using 
CreateIntCast instead.
- Simplify code for emitting satuation into one if-statement for clamping to 
max, and one if-statement for clamping to min.


Repository:
  rC Clang

https://reviews.llvm.org/D53707

Files:
  lib/CodeGen/CGExprScalar.cpp
  test/Frontend/fixed_point_conversions.c
  test/Frontend/fixed_point_to_bool.c

Index: test/Frontend/fixed_point_to_bool.c
===
--- test/Frontend/fixed_point_to_bool.c
+++ test/Frontend/fixed_point_to_bool.c
@@ -27,26 +27,26 @@
   b = (_Bool)0.5ur;
   b = (_Bool)0.0ur;
 
-  // CHECK-NEXT: [[ACCUM:%[0-9]+]] = load i32, i32* %a, align 4
-  // CHECK-NEXT: [[NOTZERO:%[0-9]+]] = icmp ne i32 [[ACCUM]], 0
-  // CHECK-NEXT: %frombool = zext i1 [[NOTZERO]] to i8
-  // CHECK-NEXT: store i8 %frombool, i8* %b, align 1
+  // CHECK-NEXT: [[ACCUM:%[0-9a-z]+]] = load i32, i32* %a, align 4
+  // CHECK-NEXT: [[NOTZERO:%[0-9a-z]+]] = icmp ne i32 [[ACCUM]], 0
+  // CHECK-NEXT: [[FROMBOOL:%[0-9a-z]+]] = zext i1 [[NOTZERO]] to i8
+  // CHECK-NEXT: store i8 [[FROMBOOL]], i8* %b, align 1
   b = a;
 
-  // CHECK-NEXT: [[ACCUM:%[0-9]+]] = load i32, i32* %ua, align 4
-  // CHECK-NEXT: [[NOTZERO:%[0-9]+]] = icmp ne i32 [[ACCUM]], 0
-  // CHECK-NEXT: %frombool1 = zext i1 [[NOTZERO]] to i8
-  // CHECK-NEXT: store i8 %frombool1, i8* %b, align 1
+  // CHECK-NEXT: [[ACCUM:%[0-9a-z]+]] = load i32, i32* %ua, align 4
+  // CHECK-NEXT: [[NOTZERO:%[0-9a-z]+]] = icmp ne i32 [[ACCUM]], 0
+  // CHECK-NEXT: [[FROMBOOL:%[0-9a-z]+]] = zext i1 [[NOTZERO]] to i8
+  // CHECK-NEXT: store i8 [[FROMBOOL]], i8* %b, align 1
   b = ua;
 
-  // CHECK-NEXT: [[ACCUM:%[0-9]+]] = load i32, i32* %a, align 4
-  // CHECK-NEXT: [[NOTZERO:%[0-9]+]] = icmp ne i32 [[ACCUM]], 0
+  // CHECK-NEXT: [[ACCUM:%[0-9a-z]+]] = load i32, i32* %a, align 4
+  // CHECK-NEXT: [[NOTZERO:%[0-9a-z]+]] = icmp ne i32 [[ACCUM]], 0
   // CHECK-NEXT: br i1 [[NOTZERO]], label %if.then, label %if.end
   if (a) {
   }
 
-  // CHECK:  [[ACCUM:%[0-9]+]] = load i32, i32* %ua, align 4
-  // CHECK-NEXT: [[NOTZERO:%[0-9]+]] = icmp ne i32 [[ACCUM]], 0
+  // CHECK:  [[ACCUM:%[0-9a-z]+]] = load i32, i32* %ua, align 4
+  // CHECK-NEXT: [[NOTZERO:%[0-9a-z]+]] = icmp ne i32 [[ACCUM]], 0
   // CHECK-NEXT: br i1 [[NOTZERO]], label %if.then{{[0-9]+}}, label %if.end{{[0-9]+}}
   if (ua) {
   }
Index: test/Frontend/fixed_point_conversions.c
===
--- test/Frontend/fixed_point_conversions.c
+++ test/Frontend/fixed_point_conversions.c
@@ -4,104 +4,104 @@
 void TestFixedPointCastSameType() {
   _Accum a = 2.5k;
   _Accum a2 = a;
-  // DEFAULT:  [[ACCUM:%[0-9]+]] = load i32, i32* %a, align 4
+  // DEFAULT:  [[ACCUM:%[0-9a-z]+]] = load i32, i32* %a, align 4
   // DEFAULT-NEXT: store i32 [[ACCUM]], i32* %a2, align 4
 
   a2 = (_Accum)a;
-  // DEFAULT:  [[ACCUM:%[0-9]+]] = load i32, i32* %a, align 4
+  // DEFAULT:  [[ACCUM:%[0-9a-z]+]] = load i32, i32* %a, align 4
   // DEFAULT-NEXT: store i32 [[ACCUM]], i32* %a2, align 4
 }
 
 void TestFixedPointCastDown() {
   long _Accum la = 2.5lk;
   _Accum a = la;
-  // DEFAULT:  [[LACCUM:%[0-9]+]] = load i64, i64* %la, align 8
-  // DEFAULT-NEXT: [[ACCUM_AS_I64:%[0-9]+]] = ashr i64 [[LACCUM]], 16
-  // DEFAULT-NEXT: [[ACCUM:%[0-9]+]] = trunc i64 [[ACCUM_AS_I64]] to i32
+  // DEFAULT:  [[LACCUM:%[0-9a-z]+]] = load i64, i64* %la, align 8
+  // DEFAULT-NEXT: [[ACCUM_AS_I64:%[0-9a-z]+]] = ashr i64 [[LACCUM]], 16
+  // DEFAULT-NEXT: [[ACCUM:%[0-9a-z]+]] = trunc i64 [[ACCUM_AS_I64]] to i32
   // DEFAULT-NEXT: store i32 [[ACCUM]], i32* %a, align 4
 
   a = (_Accum)la;
-  // DEFAULT:  [[LACCUM:%[0-9]+]] = load i64, i64* %la, align 8
-  // DEFAULT-NEXT: [[ACCUM_AS_I64:%[0-9]+]] = ashr i64 [[LACCUM]], 16
-  // DEFAULT-NEXT: [[ACCUM:%[0-9]+]] = trunc i64 [[ACCUM_AS_I64]] to i32
+  // DEFAULT:  [[LACCUM:%[0-9a-z]+]] = load i64, i64* %la, align 8
+  // DEFAULT-NEXT: [[ACCUM_AS_I64:%[0-9a-z]+]] = ashr i64 [[LACCUM]], 16
+  // DEFAULT-NEXT: [[ACCUM:%[0-9a-z]+]] = trunc i64 [[ACCUM_AS_I64]] to i32
   // DEFAULT-NEXT: store i32 [[ACCUM]], i32* %a, align 4
 
   short _Accum sa = a;
-  // DEFAULT:  [[ACCUM:%[0-9]+]] = load i32, i32* %a, align 4
-  // DEFAULT-NEXT: [[SACCUM_AS_I32:%[0-9]+]] = ashr i32 [[ACCUM]], 8
-  // DEFAULT-NEXT: [[SACCUM:%[0-9]+]] = trunc i32 [[SACCUM_AS_I32]] to i16
+  // DEFAULT:  [[ACCUM:%[0-9a-z]+]] = load i32, i32* %a, align 4
+  // DEFAULT-NEXT: [[SACCUM_AS_I32:%[0-9a-z]+]] = ashr i32 [[ACCUM]], 8
+  // DEFAULT-NEXT: [[SACCUM:%[0-9a-z]+]] = trunc i32 [[SACCUM_AS_I32]] to i16
   // DEFAULT-NEXT: store i16 [[SACCUM]], i16* %sa, align 2
 
   sa = (short _Accum)a;
-  // DEFAULT:  [[ACCUM:%[0-9]+]] = load i32, i32* %a, al

[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 171116.
gtbercea marked an inline comment as done.
gtbercea added a comment.

  Refactor static chunk schedules. Fix tests.


Repository:
  rC Clang

https://reviews.llvm.org/D53448

Files:
  include/clang/AST/StmtOpenMP.h
  lib/AST/StmtOpenMP.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/OpenMP/distribute_parallel_for_codegen.cpp
  test/OpenMP/distribute_parallel_for_simd_codegen.cpp

Index: test/OpenMP/distribute_parallel_for_simd_codegen.cpp
===
--- test/OpenMP/distribute_parallel_for_simd_codegen.cpp
+++ test/OpenMP/distribute_parallel_for_simd_codegen.cpp
@@ -406,18 +406,16 @@
   a[i] = b[i] + c[i];
   // LAMBDA: define{{.+}} void [[OMP_OUTLINED_3]](
   // LAMBDA-DAG: [[OMP_IV:%.omp.iv]] = alloca
+  // LAMBDA-DAG: [[OMP_CAPT_EXPR:%.capture_expr.1]] = alloca
   // LAMBDA-DAG: [[OMP_LB:%.omp.comb.lb]] = alloca
   // LAMBDA-DAG: [[OMP_UB:%.omp.comb.ub]] = alloca
   // LAMBDA-DAG: [[OMP_ST:%.omp.stride]] = alloca
 
-  // unlike the previous tests, in this one we have a outer and inner loop for 'distribute'
   // LAMBDA: call void @__kmpc_for_static_init_4({{.+}}, {{.+}}, i32 91,
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER:.+]]
 
-  // LAMBDA: [[DIST_OUTER_LOOP_HEADER]]:
   // check EUB for distribute
   // LAMBDA-DAG: [[OMP_UB_VAL_1:%.+]] = load{{.+}} [[OMP_UB]],
-  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}},
+  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}} [[OMP_CAPT_EXPR]],
   // LAMBDA-DAG: [[CMP_UB_NUM_IT:%.+]] = icmp sgt {{.+}}  [[OMP_UB_VAL_1]], [[NUM_IT_1]]
   // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT]], label %[[EUB_TRUE:.+]], label %[[EUB_FALSE:.+]]
   // LAMBDA-DAG: [[EUB_TRUE]]:
@@ -436,18 +434,10 @@
 
   // check exit condition
   // LAMBDA-DAG: [[OMP_IV_VAL_1:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_UB]],
-  // LAMBDA: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], [[OMP_UB_VAL_3]]
-  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_OUTER_LOOP_BODY:.+]], label %[[DIST_OUTER_LOOP_END:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_BODY]]:
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER:.+]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_HEADER]]:
-  // LAMBDA-DAG: [[OMP_IV_VAL_2:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_4:%.+]] = load {{.+}} [[OMP_UB]],
-  // LAMBDA: [[CMP_IV_UB_2:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_2]], [[OMP_UB_VAL_4]]
-  // LAMBDA: br{{.+}} [[CMP_IV_UB_2]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
+  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA-DAG: [[OMP_UB_VAL_3_PLUS_ONE:%.+]] = add {{.+}} [[OMP_UB_VAL_3]], 1
+  // LAMBDA: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], [[OMP_UB_VAL_3_PLUS_ONE]]
+  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
 
   // check that PrevLB and PrevUB are passed to the 'for'
   // LAMBDA: [[DIST_INNER_LOOP_BODY]]:
@@ -466,25 +456,39 @@
   // LAMBDA-DAG: [[OMP_ST_VAL_1:%.+]] = load {{.+}}, {{.+}}* [[OMP_ST]],
   // LAMBDA: [[OMP_IV_INC:%.+]] = add{{.+}} [[OMP_IV_VAL_3]], [[OMP_ST_VAL_1]]
   // LAMBDA: store{{.+}} [[OMP_IV_INC]], {{.+}}* [[OMP_IV]],
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_END]]:
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_INC:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_INC]]:
-  // check NextLB and NextUB
   // LAMBDA-DAG: [[OMP_LB_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_LB_NEXT:%.+]] = add{{.+}} [[OMP_LB_VAL_2]], [[OMP_ST_VAL_2]]
   // LAMBDA: store{{.+}} [[OMP_LB_NEXT]], {{.+}}* [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_UB_VAL_5:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_3:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_UB_NEXT:%.+]] = add{{.+}} [[OMP_UB_VAL_5]], [[OMP_ST_VAL_3]]
   // LAMBDA: store{{.+}} [[OMP_UB_NEXT]], {{.+}}* [[OMP_UB]],
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER]]
 
-  // outer loop exit
-  // LAMBDA: [[DIST_OUTER_LOOP_END]]:
+  // Update UB
+  // LAMBDA-DAG: [[OMP_UB_VAL_6:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
+  // LAMBDA: [[OMP_EXPR_VAL:%.+]] = load{{.+}}, {{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA-DAG: [[CMP_UB_NUM_IT_1:%.+]] = icmp sgt {{.+}}[[OMP_UB_VAL_6]], [[OMP_EXPR_VAL]]
+  // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT_1]], label %[[EUB_TRUE_1:.+]], label %[[EUB_FALSE_1:.+]]
+ 

[PATCH] D53708: [ASTImporter] Add importer specific lookup

2018-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, Szelethus, dkrupp, rnkovacs, mgorny.
Herald added a reviewer: a.sidorin.

There are certain cases when normal C/C++ lookup (localUncachedLookup)
does not find AST nodes. E.g.:

Example 1:

  template 
  struct X {
friend void foo(); // this is never found in the DC of the TU.
  };

Example 2:

  // The fwd decl to Foo is not found in the lookupPtr of the DC of the
  // translation unit decl.
  struct A { struct Foo *p; };

In these cases we create a new node instead of returning with the old one.
To fix it we create a new lookup table which holds every node and we are
not interested in any C++ specific visibility considerations.
Simply, we must know if there is an existing Decl in a given DC.


Repository:
  rC Clang

https://reviews.llvm.org/D53708

Files:
  include/clang/AST/ASTImporter.h
  include/clang/AST/ASTImporterLookupTable.h
  include/clang/CrossTU/CrossTranslationUnit.h
  lib/AST/ASTImporter.cpp
  lib/AST/ASTImporterLookupTable.cpp
  lib/AST/CMakeLists.txt
  lib/CrossTU/CrossTranslationUnit.cpp
  lib/Frontend/ASTMerge.cpp
  tools/clang-import-test/clang-import-test.cpp
  unittests/AST/ASTImporterTest.cpp

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -14,6 +14,7 @@
 #include "MatchVerifier.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTImporter.h"
+#include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
@@ -306,24 +307,26 @@
   Unit->enableSourceFileDiagnostics();
 }
 
-void lazyInitImporter(ASTUnit *ToAST) {
+void lazyInitImporter(ASTImporterLookupTable &LookupTable, ASTUnit *ToAST) {
   assert(ToAST);
   if (!Importer) {
 Importer.reset(new ASTImporter(
-ToAST->getASTContext(), ToAST->getFileManager(),
+&LookupTable, ToAST->getASTContext(), ToAST->getFileManager(),
 Unit->getASTContext(), Unit->getFileManager(), false));
   }
   assert(&ToAST->getASTContext() == &Importer->getToContext());
   createVirtualFileIfNeeded(ToAST, FileName, Code);
 }
 
-Decl *import(ASTUnit *ToAST, Decl *FromDecl) {
-  lazyInitImporter(ToAST);
+Decl *import(ASTImporterLookupTable &LookupTable, ASTUnit *ToAST,
+ Decl *FromDecl) {
+  lazyInitImporter(LookupTable, ToAST);
   return Importer->Import(FromDecl);
- }
+}
 
-QualType import(ASTUnit *ToAST, QualType FromType) {
-  lazyInitImporter(ToAST);
+QualType import(ASTImporterLookupTable &LookupTable, ASTUnit *ToAST,
+QualType FromType) {
+  lazyInitImporter(LookupTable, ToAST);
   return Importer->Import(FromType);
 }
   };
@@ -337,13 +340,24 @@
   // vector is expanding, with the list we won't have these issues.
   std::list FromTUs;
 
-  void lazyInitToAST(Language ToLang) {
+  // Initialize the lookup table if not initialized already.
+  void lazyInitLookupTable(TranslationUnitDecl *ToTU) {
+assert(ToTU);
+if (LookupTablePtr)
+  return;
+LookupTablePtr = llvm::make_unique(*ToTU);
+  }
+
+  void lazyInitToAST(Language ToLang, StringRef ToSrcCode, StringRef FileName) {
 if (ToAST)
   return;
 ArgVector ToArgs = getArgVectorForLanguage(ToLang);
+// Source code must be a valid live buffer through the tests lifetime.
+ToCode = ToSrcCode;
 // Build the AST from an empty file.
-ToAST = tooling::buildASTFromCodeWithArgs(/*Code=*/"", ToArgs, "empty.cc");
+ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, FileName);
 ToAST->enableSourceFileDiagnostics();
+lazyInitLookupTable(ToAST->getASTContext().getTranslationUnitDecl());
   }
 
   TU *findFromTU(Decl *From) {
@@ -357,6 +371,10 @@
 return &*It;
   }
 
+protected:
+
+  std::unique_ptr LookupTablePtr;
+
 public:
   // We may have several From context but only one To context.
   std::unique_ptr ToAST;
@@ -373,26 +391,23 @@
 FromTUs.emplace_back(FromSrcCode, InputFileName, FromArgs);
 TU &FromTU = FromTUs.back();
 
-ToCode = ToSrcCode;
 assert(!ToAST);
-ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
-ToAST->enableSourceFileDiagnostics();
+lazyInitToAST(ToLang, ToSrcCode, OutputFileName);
 
 ASTContext &FromCtx = FromTU.Unit->getASTContext();
 
-createVirtualFileIfNeeded(ToAST.get(), InputFileName, FromTU.Code);
-
 IdentifierInfo *ImportedII = &FromCtx.Idents.get(Identifier);
 assert(ImportedII && "Declaration with the given identifier "
  "should be specified in test!");
 DeclarationName ImportDeclName(ImportedII);
-SmallVector FoundDecls;
+SmallVector FoundDecls;
 FromCtx.getTranslationUnitDecl()->local

[PATCH] D53586: Implement Function Multiversioning for Non-ELF Systems.

2018-10-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 171118.
erichkeane added a comment.

ACTUALLY add the test this time :/  sorry about that!


https://reviews.llvm.org/D53586

Files:
  include/clang/AST/Decl.h
  include/clang/Basic/Attr.td
  include/clang/Basic/TargetInfo.h
  lib/AST/Decl.cpp
  lib/Basic/Targets/X86.h
  lib/CodeGen/CodeGenFunction.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  test/CodeGen/attr-cpuspecific.c
  test/CodeGen/attr-target-mv-func-ptrs.c
  test/CodeGen/attr-target-mv-va-args.c
  test/CodeGen/attr-target-mv.c
  test/CodeGenCXX/attr-target-mv-diff-ns.cpp
  test/CodeGenCXX/attr-target-mv-func-ptrs.cpp
  test/CodeGenCXX/attr-target-mv-inalloca.cpp
  test/CodeGenCXX/attr-target-mv-member-funcs.cpp
  test/CodeGenCXX/attr-target-mv-out-of-line-defs.cpp
  test/CodeGenCXX/attr-target-mv-overloads.cpp
  test/Sema/attr-target-mv-bad-target.c

Index: test/Sema/attr-target-mv-bad-target.c
===
--- test/Sema/attr-target-mv-bad-target.c
+++ test/Sema/attr-target-mv-bad-target.c
@@ -1,4 +1,3 @@
-// RUN: %clang_cc1 -triple x86_64-windows-pc  -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple arm-none-eabi  -fsyntax-only -verify %s
 
 int __attribute__((target("sse4.2"))) redecl1(void) { return 1; }
Index: test/CodeGenCXX/attr-target-mv-overloads.cpp
===
--- test/CodeGenCXX/attr-target-mv-overloads.cpp
+++ test/CodeGenCXX/attr-target-mv-overloads.cpp
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix=LINUX
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-windows-pc -emit-llvm %s -o - | FileCheck %s --check-prefix=WINDOWS
 
 int __attribute__((target("sse4.2"))) foo_overload(int) { return 0; }
 int __attribute__((target("arch=sandybridge"))) foo_overload(int);
@@ -13,38 +14,69 @@
   return foo_overload() + foo_overload(1);
 }
 
-// CHECK: @_Z12foo_overloadv.ifunc = ifunc i32 (), i32 ()* ()* @_Z12foo_overloadv.resolver
-// CHECK: @_Z12foo_overloadi.ifunc = ifunc i32 (i32), i32 (i32)* ()* @_Z12foo_overloadi.resolver
-
-
-// CHECK: define i32 @_Z12foo_overloadi.sse4.2(i32)
-// CHECK: ret i32 0
-// CHECK: define i32 @_Z12foo_overloadi.arch_ivybridge(i32)
-// CHECK: ret i32 1
-// CHECK: define i32 @_Z12foo_overloadi(i32)
-// CHECK: ret i32 2
-// CHECK: define i32 @_Z12foo_overloadv.sse4.2()
-// CHECK: ret i32 0
-// CHECK: define i32 @_Z12foo_overloadv.arch_ivybridge()
-// CHECK: ret i32 1
-// CHECK: define i32 @_Z12foo_overloadv()
-// CHECK: ret i32 2
-
-// CHECK: define i32 @_Z4bar2v()
-// CHECK: call i32 @_Z12foo_overloadv.ifunc()
-// CHECK: call i32 @_Z12foo_overloadi.ifunc(i32 1)
-
-// CHECK: define i32 ()* @_Z12foo_overloadv.resolver() comdat
-// CHECK: ret i32 ()* @_Z12foo_overloadv.arch_sandybridge
-// CHECK: ret i32 ()* @_Z12foo_overloadv.arch_ivybridge
-// CHECK: ret i32 ()* @_Z12foo_overloadv.sse4.2
-// CHECK: ret i32 ()* @_Z12foo_overloadv
-
-// CHECK: define i32 (i32)* @_Z12foo_overloadi.resolver() comdat
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi.arch_sandybridge
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi.arch_ivybridge
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi.sse4.2
-// CHECK: ret i32 (i32)* @_Z12foo_overloadi
-
-// CHECK: declare i32 @_Z12foo_overloadv.arch_sandybridge()
-// CHECK: declare i32 @_Z12foo_overloadi.arch_sandybridge(i32)
+// LINUX: @_Z12foo_overloadv.ifunc = ifunc i32 (), i32 ()* ()* @_Z12foo_overloadv.resolver
+// LINUX: @_Z12foo_overloadi.ifunc = ifunc i32 (i32), i32 (i32)* ()* @_Z12foo_overloadi.resolver
+
+// LINUX: define i32 @_Z12foo_overloadi.sse4.2(i32)
+// LINUX: ret i32 0
+// LINUX: define i32 @_Z12foo_overloadi.arch_ivybridge(i32)
+// LINUX: ret i32 1
+// LINUX: define i32 @_Z12foo_overloadi(i32)
+// LINUX: ret i32 2
+// LINUX: define i32 @_Z12foo_overloadv.sse4.2()
+// LINUX: ret i32 0
+// LINUX: define i32 @_Z12foo_overloadv.arch_ivybridge()
+// LINUX: ret i32 1
+// LINUX: define i32 @_Z12foo_overloadv()
+// LINUX: ret i32 2
+
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.sse4.2"(i32)
+// WINDOWS: ret i32 0
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.arch_ivybridge"(i32)
+// WINDOWS: ret i32 1
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z"(i32)
+// WINDOWS: ret i32 2
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.sse4.2"()
+// WINDOWS: ret i32 0
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.arch_ivybridge"()
+// WINDOWS: ret i32 1
+// WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ"()
+// WINDOWS: ret i32 2
+
+// LINUX: define i32 @_Z4bar2v()
+// LINUX: call i32 @_Z12foo_overloadv.ifunc()
+// LINUX: call i32 @_Z12foo_overloadi.ifunc(i32 1)
+
+// WINDOWS: define dso_local i32 @"?bar2@@YAHXZ"()
+// WINDOWS: call i32 @"?foo_overload@@YAHXZ.resolver"()
+// WINDOWS: call 

[PATCH] D53488: [clang-tidy] Catching narrowing from double to float.

2018-10-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

That one looks interesting :)

Am 25.10.18 um 17:13 schrieb Guillaume Chatelet via Phabricator:

> gchatelet added a comment.
> 
> In https://reviews.llvm.org/D53488#1275786, @hokein wrote:
> 
>> In https://reviews.llvm.org/D53488#1275750, @gchatelet wrote:
>> 
>>> In https://reviews.llvm.org/D53488#1274205, @JonasToth wrote:
>>> 
 Did you run this code over a real-world code-base and did you find new 
 stuff and/or false positives or the like?
>>> 
>>> Yes I did run it over our code base. I didn't find false positive but 98% 
>>> of the warnings are from large generated lookup table initializers, e.g. 
>>> `const static float kTable[] = {0.0, 2.0, ... };`
>>> 
>>>   Since every number in the list triggers the warning, it accounts for most 
>>> of them.
>>> 
>>> I scrutinized a few hundreds of the rest: none were actual bugs (although 
>>> it's hard to tell sometimes), most are legit like `float value = 0.0;` but 
>>> I also found some oddities 
>>> https://github.com/ARM-software/astc-encoder/blob/master/Source/vectypes.h#L13999
>>>  from generated headers.
>>> 
>>> To me the warnings are useful and if it were my code I'd be willing to fix 
>>> them. That said, I'd totally understand that many people would find them 
>>> useless or annoying.
>>> 
>>>   What do you think? Shall we still commit this as is?
>> 
>> It would be nice to know how many new findings does this patch introduce 
>> (number of findings before the patch vs after). If it is not too much, it is 
>> fine the commit as it is.
>> 
>>   I'd suggest to run the check on llvm code repository (using 
>> `clang-tidy/tool/run-clang-tidy.py`, and only enable 
>> `cppcoreguidelines-narrowing-conversions`).
> 
> I'll get back with some numbers.
> 
> In the meantime I found this one which is interesting
>  https://github.com/intel/ipmctl/blob/master/src/os/efi_shim/lnx_efi_api.c#L45
>  `spec.tv_nsec` (which is signed long) is converted to double and back to 
> int64. There surely can be some loss in the process since `double` can 
> //only// express 2^52 integers (2^52ns is about 52 days)
> 
> Repository:
> 
>   rCTE Clang Tools Extra
> 
> https://reviews.llvm.org/D53488


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488



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


[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

What about collapsed loops?




Comment at: lib/CodeGen/CGStmtOpenMP.cpp:3390
 // UB = min(UB, GlobalUB);
-EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
+EmitIgnoredExpr(StaticChunked ||
+(!StaticChunked &&

Restore the original code here, the logic can be simplified



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:3396
 // IV = LB;
-EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
+EmitIgnoredExpr(StaticChunked ||
+(!StaticChunked &&

The same



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:3434-3454
+if (StaticChunked)
+  EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
+   [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
+ CodeGenLoop(CGF, S, LoopExit);
+   },
+   [&S](CodeGenFunction &CGF) {
+ 
CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());

Please, simplify this


Repository:
  rC Clang

https://reviews.llvm.org/D53448



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


[PATCH] D51866: [analyzer][UninitializedObjectChecker] New flag to ignore guarded uninitialized fields

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus planned changes to this revision.
Szelethus added a comment.

Hmm, I'll investigate the `assert` issue @NoQ mentioned before moving forward.




Comment at: 
lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp:502
+
+  auto AssertM = callExpr(callee(functionDecl(hasName("assert";
+  auto GuardM =

NoQ wrote:
> In a lot of standard libraries `assert()` is implemented as a macro. You 
> might want to catch the corresponding builtin or look at macro names (not 
> sure if we have a matcher for the latter but it should be easy to add).
Hmm, maybe go for `[[noreturn]]` functions?


https://reviews.llvm.org/D51866



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


[PATCH] D53025: [clang-tidy] implement new check for const return types.

2018-10-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

> I'm not sure I understand what you're trying to break in the check. If you're 
> thinking of whether the code trips up on the lexical issues, I'm pretty sure 
> that won't apply here.  Once the const-ness is hidden behind a template, the 
> check doesn't try to fix it; so, lexical issues don't come into play.  It 
> boils down to the whether the matcher for const-ness is implemented 
> correctly.  But, I did add a new test based on this:
>  `template  const T p32(T t) { return t; }`
>  which *is* detected and fixed.  Let me know, though, if you want something 
> more elaborate.  Also, see below, where I *did* find a bug in a related kind 
> of type definition.

Yup, just tried to hammer with man possible `const`-applications.

> I've modified the code that finds the const token to fix this bug.  In the 
> process, I simplified it and (I think) found a more general solution to the 
> problem.  I also noticed that this same bug exists in the  
> AvoidConstParamsInDecls check, so I plan to send a follow up change that 
> fixes that check by having it use the newly introduced 
> `getConstQualifyingToken` function.

Perfect!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53025



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


[PATCH] D52615: Handle -fsanitize-address-poison-class-member-array-new-cookie in the driver and propagate it to cc1

2018-10-25 Thread Filipe Cabecinhas via Phabricator via cfe-commits
filcab added a comment.

In https://reviews.llvm.org/D52615#1272725, @rjmccall wrote:

> In https://reviews.llvm.org/D52615#1266320, @filcab wrote:
>
> > In https://reviews.llvm.org/D52615#1254567, @rsmith wrote:
> >
> > > This seems like an unreasonably long flag name. Can you try to find a 
> > > shorter name for it?
> >
> >
> > `-fsanitize-poison-extra-operator-new`?
> >  Not as explicit, but maybe ok if documented?
>
>
> `-fsanitize-address-poison-array-cookie`?


I strongly dislike this one because "poison array cookie", in general, is 
always enabled (it's actually triggered by a runtime flag). This flag is about 
poisoning it in more cases (cases where the standard doesn't completely 
disallow accesses to the cookie, so we have to have a flag and can't enable it 
all the time).

Thank you,
Filipe

P.S: Some additional discussion is at https://reviews.llvm.org/D41664, from 
when this flag was first implemented.


Repository:
  rC Clang

https://reviews.llvm.org/D52615



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


[PATCH] D53607: [AST] Only store the needed data in IfStmt.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno updated this revision to Diff 171121.
riccibruno edited the summary of this revision.
riccibruno added a comment.

Reworked so that the order of the children is kept the same.


Repository:
  rC Clang

https://reviews.llvm.org/D53607

Files:
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Stmt.cpp
  lib/Analysis/BodyFarm.cpp
  lib/Sema/SemaStmt.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/Import/if-stmt/test.cpp
  test/Misc/ast-dump-invalid.cpp

Index: test/Misc/ast-dump-invalid.cpp
===
--- test/Misc/ast-dump-invalid.cpp
+++ test/Misc/ast-dump-invalid.cpp
@@ -33,8 +33,6 @@
 // CHECK-NEXT:   |-ParmVarDecl
 // CHECK-NEXT:   `-CompoundStmt
 // CHECK-NEXT: `-IfStmt {{.*}} 
-// CHECK-NEXT:   |-<<>>
-// CHECK-NEXT:   |-<<>>
 // CHECK-NEXT:   |-OpaqueValueExpr {{.*}} <> 'bool'
 // CHECK-NEXT:   |-ReturnStmt {{.*}} 
 // CHECK-NEXT:   | `-IntegerLiteral {{.*}}  'int' 4
@@ -50,15 +48,15 @@
 { return 45; }
 }
 // CHECK: NamespaceDecl {{.*}} <{{.*}}> {{.*}} TestInvalidFunctionDecl
-// CHECK-NEXT: |-CXXRecordDecl {{.*}}  line:46:8 struct Str definition
+// CHECK-NEXT: |-CXXRecordDecl {{.*}}  line:44:8 struct Str definition
 // CHECK:  | |-CXXRecordDecl {{.*}}  col:8 implicit struct Str
-// CHECK-NEXT: | `-CXXMethodDecl {{.*}}  col:11 invalid foo1 'double (double, int)'
+// CHECK-NEXT: | `-CXXMethodDecl {{.*}}  col:11 invalid foo1 'double (double, int)'
 // CHECK-NEXT: |   |-ParmVarDecl {{.*}}  col:22 'double'
 // CHECK-NEXT: |   `-ParmVarDecl {{.*}} > col:36 invalid 'int'
-// CHECK-NEXT: `-CXXMethodDecl {{.*}} parent {{.*}}  line:49:13 invalid foo1 'double (double, int)'
+// CHECK-NEXT: `-CXXMethodDecl {{.*}} parent {{.*}}  line:47:13 invalid foo1 'double (double, int)'
 // CHECK-NEXT:   |-ParmVarDecl {{.*}}  col:24 'double'
 // CHECK-NEXT:   |-ParmVarDecl {{.*}} > col:38 invalid 'int'
-// CHECK-NEXT:   `-CompoundStmt {{.*}} 
+// CHECK-NEXT:   `-CompoundStmt {{.*}} 
 // CHECK-NEXT: `-ReturnStmt {{.*}} 
 // CHECK-NEXT:   `-ImplicitCastExpr {{.*}}  'double' 
 // CHECK-NEXT: `-IntegerLiteral {{.*}}  'int' 45
Index: test/Import/if-stmt/test.cpp
===
--- test/Import/if-stmt/test.cpp
+++ test/Import/if-stmt/test.cpp
@@ -1,41 +1,30 @@
 // RUN: clang-import-test -dump-ast -import %S/Inputs/F.cpp -expression %s | FileCheck %s
 
 // CHECK: IfStmt
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: CXXBoolLiteralExpr
 // CHECK-NEXT: ReturnStmt
-// CHECK-NEXT: <>
 
 // CHECK: IfStmt
-// CHECK-NEXT: <>
 // CHECK-NEXT: DeclStmt
 // CHECK-NEXT: VarDecl
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: ImplicitCastExpr
 // CHECK-NEXT: ImplicitCastExpr
 // CHECK-NEXT: DeclRefExpr
 // CHECK-NEXT: ReturnStmt
-// CHECK-NEXT: <>
 
 // CHECK: IfStmt
 // CHECK-NEXT: DeclStmt
 // CHECK-NEXT: VarDecl
-// CHECK-NEXT: <>
 // CHECK-NEXT: CXXBoolLiteralExpr
 // CHECK-NEXT: ReturnStmt
-// CHECK-NEXT: <>
 
 // CHECK: IfStmt
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: CXXBoolLiteralExpr
 // CHECK-NEXT: ReturnStmt
 // CHECK-NEXT: ReturnStmt
 
 // CHECK: IfStmt
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: CXXBoolLiteralExpr
 // CHECK-NEXT: CompoundStmt
 // CHECK-NEXT: ReturnStmt
Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -128,14 +128,29 @@
 
 void ASTStmtWriter::VisitIfStmt(IfStmt *S) {
   VisitStmt(S);
+
+  bool HasElse = !!S->getElse();
+  bool HasVar = !!S->getConditionVariableDeclStmt();
+  bool HasInit = !!S->getInit();
+
   Record.push_back(S->isConstexpr());
-  Record.AddStmt(S->getInit());
-  Record.AddDeclRef(S->getConditionVariable());
+  Record.push_back(HasElse);
+  Record.push_back(HasVar);
+  Record.push_back(HasInit);
+
   Record.AddStmt(S->getCond());
   Record.AddStmt(S->getThen());
-  Record.AddStmt(S->getElse());
+  if (HasElse)
+Record.AddStmt(S->getElse());
+  if (HasVar)
+Record.AddDeclRef(S->getConditionVariable());
+  if (HasInit)
+Record.AddStmt(S->getInit());
+
   Record.AddSourceLocation(S->getIfLoc());
-  Record.AddSourceLocation(S->getElseLoc());
+  if (HasElse)
+Record.AddSourceLocation(S->getElseLoc());
+
   Code = serialization::STMT_IF;
 }
 
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -215,14 +215,24 @@
 
 void ASTStmtReader::VisitIfStmt(IfStmt *S) {
   VisitStmt(S);
+
   S->setConstexpr(Record.readInt());
-  S->setInit(Record.readSubStmt());
-  S->setConditionVariable(Record.getContext(), ReadDeclAs());
+  bool HasElse = Record.readInt();
+  bool HasVar = Record.readInt();
+  bool HasInit = Record.readInt();
+
   S->setCond(Record.readSubExpr());
   S->set

[PATCH] D53713: Add extension to always default-initialize nullptr_t.

2018-10-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added reviewers: rsmith, aaron.ballman.

Core issue 1013 suggests that having an uninitialied std::nullptr_t be
UB is a bit foolish, since there is only a single valid value. This DR
reports that DR616 fixes it, which does so by making lvalue-to-rvalue
conversions from nullptr_t be equal to nullptr.

  

However, just implementing that results in warnings/etc in many places.
In order to fix all situations where nullptr_t would seem uninitialized,
this patch instead (as an otherwise transparent extension) default
initializes uninitialized VarDecls of nullptr_t.


Repository:
  rC Clang

https://reviews.llvm.org/D53713

Files:
  lib/Sema/SemaInit.cpp
  test/SemaCXX/nullptr_t-init.cpp


Index: test/SemaCXX/nullptr_t-init.cpp
===
--- /dev/null
+++ test/SemaCXX/nullptr_t-init.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -ffreestanding 
-Wuninitialized %s
+// expected-no-diagnostics
+typedef decltype(nullptr) nullptr_t;
+
+// Ensure no 'uninitialized when used here' warnings (Wuninitialized), for 
+// nullptr_t always-initialized extension.
+nullptr_t default_init() {
+  nullptr_t a;
+  return a;
+}
Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -4877,6 +4877,13 @@
 return;
   }
 
+  // As an extension, and to fix Core issue 1013, zero initialize nullptr_t.
+  // Since there is only 1 valid value of nullptr_t, we can just use that.
+  if (DestType->isNullPtrType()) {
+Sequence.AddZeroInitializationStep(Entity.getType());
+return;
+  }
+
   // - otherwise, no initialization is performed.
 
   //   If a program calls for the default initialization of an object of


Index: test/SemaCXX/nullptr_t-init.cpp
===
--- /dev/null
+++ test/SemaCXX/nullptr_t-init.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -ffreestanding -Wuninitialized %s
+// expected-no-diagnostics
+typedef decltype(nullptr) nullptr_t;
+
+// Ensure no 'uninitialized when used here' warnings (Wuninitialized), for 
+// nullptr_t always-initialized extension.
+nullptr_t default_init() {
+  nullptr_t a;
+  return a;
+}
Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -4877,6 +4877,13 @@
 return;
   }
 
+  // As an extension, and to fix Core issue 1013, zero initialize nullptr_t.
+  // Since there is only 1 valid value of nullptr_t, we can just use that.
+  if (DestType->isNullPtrType()) {
+Sequence.AddZeroInitializationStep(Entity.getType());
+return;
+  }
+
   // - otherwise, no initialization is performed.
 
   //   If a program calls for the default initialization of an object of
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53692: [analyzer] Evaluate all non-checker config options before analysis

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

What are the feelings on moving some functions to the header file? That's the 
one thing I'm unsure about regarding this patch. I could've moved them to 
`CompilerInvocation.cpp`, but I since I plan on making `ConfigTable` private, 
`CompilerInvocation` needs to be a friend of `AnalyzerOptions`. Not that it's 
the end of the world, and similar classes (e.g.: `LangOptions`) work similarly.

The reason why I didn't do it straight away is that

- it's nice that `AnalyzerOptions` handles configs on it's own.
- if someone would like add a new config option and also add constraints (like 
it has to be an existing file) to that, facing the longer compilation times 
will be a burden anyways (because the .def file has to be modified), so I 
thought the maintenance cost of `parseConfig` won't be THAT bad,

but I'd concede to the fact that these aren't the greatest of concerns, though.


https://reviews.llvm.org/D53692



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


[PATCH] D53609: [AST] Don't store data for GNU range case statement if not needed.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno updated this revision to Diff 171124.
riccibruno added a comment.

Reworked so that the order of the children is kept the same.


Repository:
  rC Clang

https://reviews.llvm.org/D53609

Files:
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Stmt.cpp
  lib/Sema/SemaStmt.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/Import/switch-stmt/test.cpp
  test/Misc/ast-dump-color.cpp

Index: test/Misc/ast-dump-color.cpp
===
--- test/Misc/ast-dump-color.cpp
+++ test/Misc/ast-dump-color.cpp
@@ -51,13 +51,11 @@
 //CHECK: {{^}}[[Blue]]| |   `-[[RESET]][[MAGENTA]]CompoundStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:14[[RESET]], [[Yellow]]line:15:3[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | |-[[RESET]][[MAGENTA]]CaseStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:11:3[[RESET]], [[Yellow]]line:12:27[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | | |-[[RESET]][[MAGENTA]]IntegerLiteral[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:11:8[[RESET]]> [[Green]]'int'[[RESET]][[Cyan]][[RESET]][[Cyan]][[RESET]][[CYAN]] 1[[RESET]]{{$}}
-//CHECK: {{^}}[[Blue]]| | | |-[[RESET]][[Blue]]<<>>[[RESET]]{{$}}
 //CHECK: {{^}}[[Blue]]| | | `-[[RESET]][[MAGENTA]]AttributedStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:12:5[[RESET]], [[Yellow]]col:27[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | |   |-[[RESET]][[BLUE]]FallThroughAttr[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:7[[RESET]], [[Yellow]]col:14[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | |   `-[[RESET]][[MAGENTA]]NullStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:27[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[MAGENTA]]CaseStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:13:3[[RESET]], [[Yellow]]line:14:5[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| |   |-[[RESET]][[MAGENTA]]IntegerLiteral[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:13:8[[RESET]]> [[Green]]'int'[[RESET]][[Cyan]][[RESET]][[Cyan]][[RESET]][[CYAN]] 2[[RESET]]{{$}}
-//CHECK: {{^}}[[Blue]]| |   |-[[RESET]][[Blue]]<<>>[[RESET]]{{$}}
 //CHECK: {{^}}[[Blue]]| |   `-[[RESET]][[MAGENTA]]NullStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:14:5[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| `-[[RESET]][[Blue]]FullComment[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:8:4[[RESET]], [[Yellow]]col:11[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]|   `-[[RESET]][[Blue]]ParagraphComment[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:4[[RESET]], [[Yellow]]col:11[[RESET]]>{{$}}
Index: test/Import/switch-stmt/test.cpp
===
--- test/Import/switch-stmt/test.cpp
+++ test/Import/switch-stmt/test.cpp
@@ -7,10 +7,8 @@
 // CHECK-NEXT: CompoundStmt
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
-// CHECK-NEXT: <>
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
-// CHECK-NEXT: <>
 // CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
@@ -22,11 +20,9 @@
 // CHECK-NEXT: CompoundStmt
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
-// CHECK-NEXT: <>
 // CHECK-NEXT: BreakStmt
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
-// CHECK-NEXT: <>
 // CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -96,10 +96,13 @@
 
 void ASTStmtWriter::VisitCaseStmt(CaseStmt *S) {
   VisitSwitchCase(S);
+  Record.push_back(S->caseStmtIsGNURange());
   Record.AddStmt(S->getLHS());
-  Record.AddStmt(S->getRHS());
   Record.AddStmt(S->getSubStmt());
-  Record.AddSourceLocation(S->getEllipsisLoc());
+  if (S->caseStmtIsGNURange()) {
+Record.AddStmt(S->getRHS());
+Record.AddSourceLocation(S->getEllipsisLoc());
+  }
   Code = serialization::STMT_CASE;
 }
 
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -177,10 +177,13 @@
 
 void ASTStmtReader::VisitCaseStmt(CaseStmt *S) {
   VisitSwitchCase(S);
+  bool CaseStmtIsGNURange = Record.readInt();
   S->setLHS(Record.readSubExpr());
-  S->setRHS(Record.readSubExpr());
   S->setSubStmt(Record.readSubStmt());
-  S->setEllipsisLoc(ReadSourceLocation());
+  if (CaseStmtIsGNURange) {
+S->setRHS(Record.readSubExpr());
+S->setEllipsisLoc(ReadSourceLocation());
+  }
 }
 
 void ASTStmtReader::VisitDefaultStmt(DefaultStmt *S) {
@@ -2277,7 +2280,9 @@
   break;
 
 case STMT_CASE:
-  S = new (Context) CaseStmt(Empty);
+  S = CaseStmt::CreateEmpty(
+  Context,
+  /*CaseStmtIsGNURange*/ Record[ASTStmtReader::NumStmtFields + 3]);
   

[PATCH] D53713: Add extension to always default-initialize nullptr_t.

2018-10-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Woops, apparently a couple of tests fail on this that I somehow missed the 1st 
time.  Looking into it.


Repository:
  rC Clang

https://reviews.llvm.org/D53713



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


[PATCH] D53610: [AST] Check that GNU range case statements are correctly imported.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno updated this revision to Diff 171125.
riccibruno added a comment.

rebased


Repository:
  rC Clang

https://reviews.llvm.org/D53610

Files:
  test/Import/switch-stmt/Inputs/F.cpp
  test/Import/switch-stmt/test.cpp


Index: test/Import/switch-stmt/test.cpp
===
--- test/Import/switch-stmt/test.cpp
+++ test/Import/switch-stmt/test.cpp
@@ -10,6 +10,13 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: DeclStmt
@@ -24,6 +31,10 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: <>
Index: test/Import/switch-stmt/Inputs/F.cpp
===
--- test/Import/switch-stmt/Inputs/F.cpp
+++ test/Import/switch-stmt/Inputs/F.cpp
@@ -3,12 +3,17 @@
   case 1:
   case 2:
 break;
+  case 3 ... 4:
+  case 5 ... 5:
+break;
   }
   switch (int varname; 1) {
   case 1:
 break;
   case 2:
 break;
+  case 3 ... 5:
+break;
   }
   switch (1)
   default:


Index: test/Import/switch-stmt/test.cpp
===
--- test/Import/switch-stmt/test.cpp
+++ test/Import/switch-stmt/test.cpp
@@ -10,6 +10,13 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: DeclStmt
@@ -24,6 +31,10 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: <>
Index: test/Import/switch-stmt/Inputs/F.cpp
===
--- test/Import/switch-stmt/Inputs/F.cpp
+++ test/Import/switch-stmt/Inputs/F.cpp
@@ -3,12 +3,17 @@
   case 1:
   case 2:
 break;
+  case 3 ... 4:
+  case 5 ... 5:
+break;
   }
   switch (int varname; 1) {
   case 1:
 break;
   case 2:
 break;
+  case 3 ... 5:
+break;
   }
   switch (1)
   default:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52034: [Clang] Add options -Xclang -coverage-filter and -Xclang -coverage-exclude to filter the files to instrument with gcov

2018-10-25 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added a comment.

In https://reviews.llvm.org/D52034#1268277, @calixte wrote:

> @vsk, gcc guys are ok for -fprofile-filter-files and  
> -fprofile-exclude-files, are you ok with that ?


That sounds fine to me.

> Should these options prefixed by -Xclang or not ?

I don't think they should be. These options should be easy to surface to users.


Repository:
  rC Clang

https://reviews.llvm.org/D52034



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


[PATCH] D52034: [Clang] Add options -Xclang -coverage-filter and -Xclang -coverage-exclude to filter the files to instrument with gcov

2018-10-25 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added a comment.

In https://reviews.llvm.org/D52034#1246379, @calixte wrote:

> I reported a bug for gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87442


Thank you!

> @vsk I'd like to add documentation in Docs/UsersManual.rst, but I've no idea 
> on what's a good place for this (I look for option 
> -coverage-no-function-names-in-data, but I didn't get anything). So could you 
> give a me a clue please ?

That's the right file to edit. Please create a section for gcov-based 
profiling. I won't ask that you describe the entire gcov pipeline, but it would 
really help to have a description of the driver flags you're adding & some 
examples of how to use them.


Repository:
  rC Clang

https://reviews.llvm.org/D52034



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


[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-25 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 171127.
gtbercea added a comment.

  Simplify code.


Repository:
  rC Clang

https://reviews.llvm.org/D53448

Files:
  include/clang/AST/StmtOpenMP.h
  lib/AST/StmtOpenMP.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/OpenMP/distribute_parallel_for_codegen.cpp
  test/OpenMP/distribute_parallel_for_simd_codegen.cpp

Index: test/OpenMP/distribute_parallel_for_simd_codegen.cpp
===
--- test/OpenMP/distribute_parallel_for_simd_codegen.cpp
+++ test/OpenMP/distribute_parallel_for_simd_codegen.cpp
@@ -406,18 +406,16 @@
   a[i] = b[i] + c[i];
   // LAMBDA: define{{.+}} void [[OMP_OUTLINED_3]](
   // LAMBDA-DAG: [[OMP_IV:%.omp.iv]] = alloca
+  // LAMBDA-DAG: [[OMP_CAPT_EXPR:%.capture_expr.1]] = alloca
   // LAMBDA-DAG: [[OMP_LB:%.omp.comb.lb]] = alloca
   // LAMBDA-DAG: [[OMP_UB:%.omp.comb.ub]] = alloca
   // LAMBDA-DAG: [[OMP_ST:%.omp.stride]] = alloca
 
-  // unlike the previous tests, in this one we have a outer and inner loop for 'distribute'
   // LAMBDA: call void @__kmpc_for_static_init_4({{.+}}, {{.+}}, i32 91,
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER:.+]]
 
-  // LAMBDA: [[DIST_OUTER_LOOP_HEADER]]:
   // check EUB for distribute
   // LAMBDA-DAG: [[OMP_UB_VAL_1:%.+]] = load{{.+}} [[OMP_UB]],
-  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}},
+  // LAMBDA: [[NUM_IT_1:%.+]] = load{{.+}} [[OMP_CAPT_EXPR]],
   // LAMBDA-DAG: [[CMP_UB_NUM_IT:%.+]] = icmp sgt {{.+}}  [[OMP_UB_VAL_1]], [[NUM_IT_1]]
   // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT]], label %[[EUB_TRUE:.+]], label %[[EUB_FALSE:.+]]
   // LAMBDA-DAG: [[EUB_TRUE]]:
@@ -436,18 +434,10 @@
 
   // check exit condition
   // LAMBDA-DAG: [[OMP_IV_VAL_1:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_UB]],
-  // LAMBDA: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], [[OMP_UB_VAL_3]]
-  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_OUTER_LOOP_BODY:.+]], label %[[DIST_OUTER_LOOP_END:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_BODY]]:
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER:.+]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_HEADER]]:
-  // LAMBDA-DAG: [[OMP_IV_VAL_2:%.+]] = load {{.+}} [[OMP_IV]],
-  // LAMBDA-DAG: [[OMP_UB_VAL_4:%.+]] = load {{.+}} [[OMP_UB]],
-  // LAMBDA: [[CMP_IV_UB_2:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_2]], [[OMP_UB_VAL_4]]
-  // LAMBDA: br{{.+}} [[CMP_IV_UB_2]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
+  // LAMBDA-DAG: [[OMP_UB_VAL_3:%.+]] = load {{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA-DAG: [[OMP_UB_VAL_3_PLUS_ONE:%.+]] = add {{.+}} [[OMP_UB_VAL_3]], 1
+  // LAMBDA: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], [[OMP_UB_VAL_3_PLUS_ONE]]
+  // LAMBDA: br {{.+}} [[CMP_IV_UB]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
 
   // check that PrevLB and PrevUB are passed to the 'for'
   // LAMBDA: [[DIST_INNER_LOOP_BODY]]:
@@ -466,25 +456,39 @@
   // LAMBDA-DAG: [[OMP_ST_VAL_1:%.+]] = load {{.+}}, {{.+}}* [[OMP_ST]],
   // LAMBDA: [[OMP_IV_INC:%.+]] = add{{.+}} [[OMP_IV_VAL_3]], [[OMP_ST_VAL_1]]
   // LAMBDA: store{{.+}} [[OMP_IV_INC]], {{.+}}* [[OMP_IV]],
-  // LAMBDA: br label %[[DIST_INNER_LOOP_HEADER]]
-
-  // LAMBDA: [[DIST_INNER_LOOP_END]]:
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_INC:.+]]
-
-  // LAMBDA: [[DIST_OUTER_LOOP_INC]]:
-  // check NextLB and NextUB
   // LAMBDA-DAG: [[OMP_LB_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_LB_NEXT:%.+]] = add{{.+}} [[OMP_LB_VAL_2]], [[OMP_ST_VAL_2]]
   // LAMBDA: store{{.+}} [[OMP_LB_NEXT]], {{.+}}* [[OMP_LB]],
   // LAMBDA-DAG: [[OMP_UB_VAL_5:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
   // LAMBDA-DAG: [[OMP_ST_VAL_3:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
   // LAMBDA-DAG: [[OMP_UB_NEXT:%.+]] = add{{.+}} [[OMP_UB_VAL_5]], [[OMP_ST_VAL_3]]
   // LAMBDA: store{{.+}} [[OMP_UB_NEXT]], {{.+}}* [[OMP_UB]],
-  // LAMBDA: br label %[[DIST_OUTER_LOOP_HEADER]]
 
-  // outer loop exit
-  // LAMBDA: [[DIST_OUTER_LOOP_END]]:
+  // Update UB
+  // LAMBDA-DAG: [[OMP_UB_VAL_6:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
+  // LAMBDA: [[OMP_EXPR_VAL:%.+]] = load{{.+}}, {{.+}} [[OMP_CAPT_EXPR]],
+  // LAMBDA-DAG: [[CMP_UB_NUM_IT_1:%.+]] = icmp sgt {{.+}}[[OMP_UB_VAL_6]], [[OMP_EXPR_VAL]]
+  // LAMBDA: br {{.+}} [[CMP_UB_NUM_IT_1]], label %[[EUB_TRUE_1:.+]], label %[[EUB_FALSE_1:.+]]
+  // LAMBDA-DAG: [[EUB_TRUE_1]]:
+  // LAMBDA: [[NUM_IT_3:%.+]] =

[PATCH] D53714: [AST] Only store the needed data in SwitchStmt.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rjmccall.
riccibruno added a project: clang.
Herald added a subscriber: cfe-commits.

Don't store the data for the init statement and condition variable
if not needed. This cuts the size of `SwitchStmt` by up to 2 pointers.
The order of the children is kept the same.

Also use the newly available space in the bit-fields of `Stmt`
to store the bit representing whether all enum have been covered
instead of using a `PointerIntPair`.


Repository:
  rC Clang

https://reviews.llvm.org/D53714

Files:
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Stmt.cpp
  lib/Sema/SemaStmt.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/Import/switch-stmt/test.cpp
  test/Misc/ast-dump-color.cpp

Index: test/Misc/ast-dump-color.cpp
===
--- test/Misc/ast-dump-color.cpp
+++ test/Misc/ast-dump-color.cpp
@@ -46,7 +46,6 @@
 //CHECK: {{^}}[[Blue]]|-[[RESET]][[GREEN]]FunctionDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:9:1[[RESET]], [[Yellow]]line:16:1[[RESET]]> [[Yellow]]line:9:6[[RESET]][[CYAN]] TestAttributedStmt[[RESET]] [[Green]]'void ()'[[RESET]]{{$}}
 //CHECK: {{^}}[[Blue]]| |-[[RESET]][[MAGENTA:.\[0;1;35m]]CompoundStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:27[[RESET]], [[Yellow]]line:16:1[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[MAGENTA]]SwitchStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:10:3[[RESET]], [[Yellow]]line:15:3[[RESET]]>{{$}}
-//CHECK: {{^}}[[Blue]]| |   |-[[RESET]][[Blue:.\[0;34m]]<<>>[[RESET]]{{$}}
 //CHECK: {{^}}[[Blue]]| |   |-[[RESET]][[MAGENTA]]IntegerLiteral[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:10:11[[RESET]]> [[Green]]'int'[[RESET]][[Cyan:.\[0;36m]][[RESET]][[Cyan]][[RESET]][[CYAN]] 1[[RESET]]{{$}}
 //CHECK: {{^}}[[Blue]]| |   `-[[RESET]][[MAGENTA]]CompoundStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:14[[RESET]], [[Yellow]]line:15:3[[RESET]]>{{$}}
 //CHECK: {{^}}[[Blue]]| | |-[[RESET]][[MAGENTA]]CaseStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:11:3[[RESET]], [[Yellow]]line:12:27[[RESET]]>{{$}}
Index: test/Import/switch-stmt/test.cpp
===
--- test/Import/switch-stmt/test.cpp
+++ test/Import/switch-stmt/test.cpp
@@ -1,8 +1,6 @@
 // RUN: clang-import-test -dump-ast -import %S/Inputs/F.cpp -expression %s | FileCheck %s
 
 // CHECK: SwitchStmt
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: CompoundStmt
 // CHECK-NEXT: CaseStmt
@@ -22,7 +20,6 @@
 // CHECK-NEXT: DeclStmt
 // CHECK-NEXT: VarDecl
 // CHECK-SAME: varname
-// CHECK-NEXT: <>
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: CompoundStmt
 // CHECK-NEXT: CaseStmt
@@ -37,15 +34,11 @@
 // CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: DefaultStmt
 // CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: NullStmt
 
Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -159,12 +159,22 @@
 
 void ASTStmtWriter::VisitSwitchStmt(SwitchStmt *S) {
   VisitStmt(S);
-  Record.AddStmt(S->getInit());
-  Record.AddDeclRef(S->getConditionVariable());
+
+  bool HasInit = !!S->getInit();
+  bool HasVar = !!S->getConditionVariableDeclStmt();
+  Record.push_back(HasInit);
+  Record.push_back(HasVar);
+  Record.push_back(S->isAllEnumCasesCovered());
+
   Record.AddStmt(S->getCond());
   Record.AddStmt(S->getBody());
+  if (HasInit)
+Record.AddStmt(S->getInit());
+  if (HasVar)
+Record.AddDeclRef(S->getConditionVariable());
+
   Record.AddSourceLocation(S->getSwitchLoc());
-  Record.push_back(S->isAllEnumCasesCovered());
+
   for (SwitchCase *SC = S->getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase())
 Record.push_back(Writer.RecordSwitchCaseID(SC));
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -240,13 +240,21 @@
 
 void ASTStmtReader::VisitSwitchStmt(SwitchStmt *S) {
   VisitStmt(S);
-  S->setInit(Record.readSubStmt());
-  S->setConditionVariable(Record.getContext(), ReadDeclAs());
+
+  bool HasInit = Record.readInt();
+  bool HasVar = Record.readInt();
+  bool AllEnumCasesCovered = Record.readInt();
+  if (AllEnumCasesCovered)
+S->setAllEnumCasesCovered();
+
   S->setCond(Record.readSubExpr());
   S->setBody(Record.readSubStmt());
+  if (HasInit)
+S->setInit(Record.readSubStmt());
+  if (HasVar)
+S->setConditionVariable(Record.getContext(), ReadDeclAs());
+
   S->setS

[PATCH] D53715: [AST] Only store the needed data in WhileStmt.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rjmccall.
riccibruno added a project: clang.
Herald added a subscriber: cfe-commits.

Don't store the data for the condition variable if not needed.
This cuts the size of `WhileStmt` by up to a pointer.
The order of the children is kept the same.


Repository:
  rC Clang

https://reviews.llvm.org/D53715

Files:
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Stmt.cpp
  lib/Sema/SemaStmt.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/Import/while-stmt/test.cpp

Index: test/Import/while-stmt/test.cpp
===
--- test/Import/while-stmt/test.cpp
+++ test/Import/while-stmt/test.cpp
@@ -1,12 +1,10 @@
 // RUN: clang-import-test -dump-ast -import %S/Inputs/F.cpp -expression %s | FileCheck %s
 
 // CHECK: WhileStmt
-// CHECK-NEXT: <>
 // CHECK-NEXT: CXXBoolLiteralExpr
 // CHECK-NEXT: NullStmt
 
 // CHECK: WhileStmt
-// CHECK-NEXT: <>
 // CHECK-NEXT: CXXBoolLiteralExpr
 // CHECK-NEXT: CompoundStmt
 
Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -183,9 +183,15 @@
 
 void ASTStmtWriter::VisitWhileStmt(WhileStmt *S) {
   VisitStmt(S);
-  Record.AddDeclRef(S->getConditionVariable());
+
+  bool HasVar = !!S->getConditionVariableDeclStmt();
+  Record.push_back(HasVar);
+
   Record.AddStmt(S->getCond());
   Record.AddStmt(S->getBody());
+  if (HasVar)
+Record.AddDeclRef(S->getConditionVariable());
+
   Record.AddSourceLocation(S->getWhileLoc());
   Code = serialization::STMT_WHILE;
 }
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -270,10 +270,14 @@
 
 void ASTStmtReader::VisitWhileStmt(WhileStmt *S) {
   VisitStmt(S);
-  S->setConditionVariable(Record.getContext(), ReadDeclAs());
+
+  bool HasVar = Record.readInt();
 
   S->setCond(Record.readSubExpr());
   S->setBody(Record.readSubStmt());
+  if (HasVar)
+S->setConditionVariable(Record.getContext(), ReadDeclAs());
+
   S->setWhileLoc(ReadSourceLocation());
 }
 
@@ -2323,7 +2327,9 @@
   break;
 
 case STMT_WHILE:
-  S = new (Context) WhileStmt(Empty);
+  S = WhileStmt::CreateEmpty(
+  Context,
+  /* HasVar=*/Record[ASTStmtReader::NumStmtFields + 0]);
   break;
 
 case STMT_DO:
Index: lib/Sema/SemaStmt.cpp
===
--- lib/Sema/SemaStmt.cpp
+++ lib/Sema/SemaStmt.cpp
@@ -1305,8 +1305,8 @@
   if (isa(Body))
 getCurCompoundScope().setHasEmptyLoopBodies();
 
-  return new (Context)
-  WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
+  return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
+   WhileLoc);
 }
 
 StmtResult
Index: lib/AST/Stmt.cpp
===
--- lib/AST/Stmt.cpp
+++ lib/AST/Stmt.cpp
@@ -978,32 +978,60 @@
   DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
 }
 
-WhileStmt::WhileStmt(const ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,
- SourceLocation WL)
-  : Stmt(WhileStmtClass) {
-  setConditionVariable(C, Var);
-  SubExprs[COND] = cond;
-  SubExprs[BODY] = body;
-  WhileStmtBits.WhileLoc = WL;
+WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
+ Stmt *Body, SourceLocation WL)
+: Stmt(WhileStmtClass) {
+  bool HasVar = !!Var;
+  WhileStmtBits.HasVar = HasVar;
+
+  setCond(Cond);
+  setBody(Body);
+  if (HasVar)
+setConditionVariable(Ctx, Var);
+
+  setWhileLoc(WL);
 }
 
-VarDecl *WhileStmt::getConditionVariable() const {
-  if (!SubExprs[VAR])
-return nullptr;
+WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
+: Stmt(WhileStmtClass, Empty) {
+  WhileStmtBits.HasVar = HasVar;
+}
+
+WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
+ Stmt *Body, SourceLocation WL) {
+  bool HasVar = !!Var;
+  void *Mem =
+  Ctx.Allocate(totalSizeToAlloc(NumMandatoryStmtPtr + HasVar),
+   alignof(WhileStmt));
+  return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL);
+}
 
-  auto *DS = cast(SubExprs[VAR]);
+WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
+  void *Mem =
+  Ctx.Allocate(totalSizeToAlloc(NumMandatoryStmtPtr + HasVar),
+   alignof(WhileStmt));
+  return new (Mem) WhileStmt(EmptyShell(), HasVar);
+}
+
+VarDecl *WhileStmt::getConditionVariable() {
+  auto *DS = getConditionVariableDeclStmt();
+  if (!DS)
+return nullptr;
   return cast(DS->getSingleDecl());
 }
 
-void WhileStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
+void WhileStmt::setCo

[PATCH] D38061: Set AnonymousTagLocations false for ASTContext if column info is expected not to be used

2018-10-25 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In https://reviews.llvm.org/D38061#1275845, @twoh wrote:

> @dblaikie I see. The problem we're experiencing is that with Clang's naming 
> scheme we end up having different function name between the original source 
> and the preprocessed source (as macro expansion changes the column number).


I imagine that's not achievable, though - as soon as you have a multi-line 
macro at least, it seems like it'd be difficult to preserve (I guess you could 
put loc directives between every line in the macro to ensure every line was 
attributed to the line the macro was written on, maybe?)

> This doesn't work well for me if I want to use distcc on top of our caching 
> system, as the caching scheme expects the output to be same as far as the 
> original source has not been changed (regardless of it's compiled directly or 
> first preprocessed then compiled), but the distcc preprocesses the source 
> locally then sends it to the remote build machine (and we do not turn distcc 
> on for all workflow). I wonder if you have any suggestion to resolve this 
> issue? Thanks!

Best thing to do, I think, if possible, is teach the distributed build system 
not to fully preprocess but to use something like Clang's -frewrite-includes - 
this handles includes, but leaves macro definitions and uses in-place. This 
would preserve Clang's warning semantics (where macros can help inform Clang's 
diagnostic choices, improving diagnostic quality (lowering false positives, 
etc)) and other things like debug info.


Repository:
  rC Clang

https://reviews.llvm.org/D38061



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


[PATCH] D53076: [analyzer] Enhance ConditionBRVisitor to write out more information

2018-10-25 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov requested changes to this revision.
george.karpenkov added a comment.
This revision now requires changes to proceed.

Thanks a lot, this is almost ready!
I think it should be good to go after this round of nitpicks.




Comment at: 
include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:168
 
-  virtual void EndPath(ProgramStateRef state) {}
-

From a brief inspection this indeed seems dead code. However, this removal 
should be moved into a separate revision (sorry!)



Comment at: include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:680
-ConstraintMgr->EndPath(St);
-  }
 };

Same: should be moved into a separate revision, same as the other removal.



Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:1853
+
+const auto *Cond = cast(PS->getStmt());
+auto Piece = VisitTrueTest(Cond, tag == tags.first, BRC, BR, N);

How do we know that it's always an `Expr`?



Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:1854
+const auto *Cond = cast(PS->getStmt());
+auto Piece = VisitTrueTest(Cond, tag == tags.first, BRC, BR, N);
+if (!Piece)

`/*tookTrue=*/tag == tag.first`



Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:1970
 
+bool ConditionBRVisitor::insertOrUpdateConstraintMessage(const Stmt *Cond,
+ StringRef Message) {

1. What about the refactoring I have previously suggested twice?
2. I know you have started with that -- and sorry for spurious changes -- but I 
also think your original name of `constraintsChanged` is better.



Comment at: lib/StaticAnalyzer/Core/ExprEngine.cpp:2261
   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
-  StateMgr.EndPath(Pred->getState());
 

Should be moved together with other two removals.



Comment at: lib/StaticAnalyzer/Core/ProgramState.cpp:29
 
+/// Increments the number of times this state is referenced.
 void ProgramStateRetain(const ProgramState *state) {

While this minor formatting is correct, it's better to remove it to simplify 
future archaeology.


https://reviews.llvm.org/D53076



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


[PATCH] D53713: Add extension to always default-initialize nullptr_t.

2018-10-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 171128.
erichkeane added a comment.

Update the 2 failing tests.  Would love some help looking at the Analysis fix, 
it seems to no longer have to 'assume' stuff due to the this now being defined 
behavior.

Additionally, the other test is just an AST change, but seems to be exactly 
what I'm suggesting as an extension here.


https://reviews.llvm.org/D53713

Files:
  lib/Sema/SemaInit.cpp
  test/Analysis/nullptr.cpp
  test/SemaCXX/ast-print-crash.cpp
  test/SemaCXX/nullptr_t-init.cpp


Index: test/SemaCXX/nullptr_t-init.cpp
===
--- /dev/null
+++ test/SemaCXX/nullptr_t-init.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -ffreestanding 
-Wuninitialized %s
+// expected-no-diagnostics
+typedef decltype(nullptr) nullptr_t;
+
+// Ensure no 'uninitialized when used here' warnings (Wuninitialized), for 
+// nullptr_t always-initialized extension.
+nullptr_t default_init() {
+  nullptr_t a;
+  return a;
+}
Index: test/SemaCXX/ast-print-crash.cpp
===
--- test/SemaCXX/ast-print-crash.cpp
+++ test/SemaCXX/ast-print-crash.cpp
@@ -7,6 +7,6 @@
 
 // CHECK:  struct {
 // CHECK-NEXT: } dont_crash_on_syntax_error;
-// CHECK-NEXT: decltype(nullptr) p;
+// CHECK-NEXT: decltype(nullptr) p(/*implicit*/(decltype(nullptr))0);
 struct {
 } dont_crash_on_syntax_error /* missing ; */ decltype(nullptr) p;
Index: test/Analysis/nullptr.cpp
===
--- test/Analysis/nullptr.cpp
+++ test/Analysis/nullptr.cpp
@@ -125,21 +125,16 @@
 };
 
 void shouldNotCrash() {
-  decltype(nullptr) p; // expected-note{{'p' declared without an initial 
value}}
-  if (getSymbol()) // expected-note   {{Assuming the condition is false}}
-   // expected-note@-1{{Taking false branch}}
-   // expected-note@-2{{Assuming the condition is false}}
-   // expected-note@-3{{Taking false branch}}
-   // expected-note@-4{{Assuming the condition is true}}
-   // expected-note@-5{{Taking true branch}}
-invokeF(p); // expected-warning{{1st function call argument is an 
uninitialized value}}
-// expected-note@-1{{1st function call argument is an 
uninitialized value}}
+  decltype(nullptr) p; // expected-note{{'p' initialized to a null pointer 
value}}
   if (getSymbol()) // expected-note   {{Assuming the condition is false}}
// expected-note@-1{{Taking false branch}}
// expected-note@-2{{Assuming the condition is true}}
// expected-note@-3{{Taking true branch}}
-invokeF(nullptr); // expected-note   {{Calling 'invokeF'}}
-  // expected-note@-1{{Passing null pointer value via 1st 
parameter 'x'}}
+invokeF(p); // expected-note{{Passing null pointer value via 1st parameter 
'x'}}
+// expected-note@-1{{Calling 'invokeF'}}
+  if (getSymbol()) // expected-note   {{Assuming the condition is false}}
+   // expected-note@-1{{Taking false branch}}
+invokeF(nullptr);
   if (getSymbol()) {  // expected-note  {{Assuming the condition is true}}
   // expected-note@-1{{Taking true branch}}
 X *xx = Type().x; // expected-note   {{Null pointer value stored to field 
'x'}}
Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -4877,6 +4877,13 @@
 return;
   }
 
+  // As an extension, and to fix Core issue 1013, zero initialize nullptr_t.
+  // Since there is only 1 valid value of nullptr_t, we can just use that.
+  if (DestType->isNullPtrType()) {
+Sequence.AddZeroInitializationStep(Entity.getType());
+return;
+  }
+
   // - otherwise, no initialization is performed.
 
   //   If a program calls for the default initialization of an object of


Index: test/SemaCXX/nullptr_t-init.cpp
===
--- /dev/null
+++ test/SemaCXX/nullptr_t-init.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -ffreestanding -Wuninitialized %s
+// expected-no-diagnostics
+typedef decltype(nullptr) nullptr_t;
+
+// Ensure no 'uninitialized when used here' warnings (Wuninitialized), for 
+// nullptr_t always-initialized extension.
+nullptr_t default_init() {
+  nullptr_t a;
+  return a;
+}
Index: test/SemaCXX/ast-print-crash.cpp
===
--- test/SemaCXX/ast-print-crash.cpp
+++ test/SemaCXX/ast-print-crash.cpp
@@ -7,6 +7,6 @@
 
 // CHECK:  struct {
 // CHECK-NEXT: } dont_crash_on_syntax_error;
-// CHECK-NEXT: decltype(nullptr) p;
+// CHECK-NEXT: decltype(nullptr) p(/*implicit*/(decltype(nullptr))0);
 struct {
 } dont_crash_on_syntax_error /* missing ; */ decltype(nu

[PATCH] D53651: [clangd] Use thread pool for background indexing.

2018-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Moving forward with priorities then.




Comment at: clangd/index/Background.cpp:89
   }
-  QueueCV.notify_all();
+  QueueCV.notify_one();
 }

sammccall wrote:
> I always forget the details of how these work :-\
> Is it possible for the "one" notification to be consumed by a waiter on 
> blockUntilIdleForTest?
> 
> In general I'm not sure whether the `notify_one` optimization is worth the 
> correctness risk as the code evolves.
Ah, you are right, a thread waiting for done might catch that one as well, but 
I think it only applies to that one. Is there a possibility of 
`blockUntilIdleForTest` and `enqueue` being called from different threads?

There is still the argument of code evolution, but I don't think we should ever 
end up in a state in which an enqueue and a wait that will not consume that 
enqueue should occur concurrently.



Comment at: clangd/index/Background.h:80
+  // Must be last, spawned thread reads instance vars.
+  llvm::SmallVector ThreadPool;
 };

sammccall wrote:
> ilya-biryukov wrote:
> > Why not `std::vector`? Memory allocs won't ever be a bottleneck here.
> ilya was saying nice things about `llvm::ThreadPool` recently - worth a look?
going for llvm::ThreadPool


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53651



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


[PATCH] D53524: [ThinLTO] Enable LTOUnit only when it is needed

2018-10-25 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc added a comment.

In https://reviews.llvm.org/D53524#1274505, @tejohnson wrote:

> In https://reviews.llvm.org/D53524#1271387, @tejohnson wrote:
>
> > In https://reviews.llvm.org/D53524#1271357, @pcc wrote:
> >
> > > The reason why LTO unit is always enabled is so that you can link 
> > > translation units compiled with `-fsanitize=cfi` and/or 
> > > `-fwhole-program-vtables` against translation units compiled without 
> > > CFI/WPD. With this change we will see miscompiles in the translation 
> > > units compiled with CFI/WPD if they use vtables in the translation units 
> > > compiled without CFI/WPD. If we really need this option I think it should 
> > > be an opt out.
> >
> >
> > Is there an important use case for support thing mixing and matching? The 
> > issue is that it comes at a cost to all ThinLTO compiles for codes with 
> > vtables by requiring them all to process IR during the thin link.
>
>
> Ping on the question of why this mode needs to be default. If it was a matter 
> of a few percent overhead that would be one thing, but we're talking a *huge* 
> overhead (as noted off-patch for my app I'm seeing >20x thin link time 
> currently, and with improvements to the hashing to always get successful 
> splitting we could potentially get down to closer to 2x - still a big 
> overhead). This kind of overhead should be opt-in. The average ThinLTO user 
> is not going to realize they are paying a big overhead because CFI is always 
> pre-enabled.


Well, the intent was always that the overhead would be minimal, which is why 
things are set up the way that they are. But it doesn't sound like anyone is 
going to have the time to fully address the performance problems that you've 
seen any time soon, so maybe it would be fine to introduce the -flto-unit flag. 
I guess we can always change the flag so that it has no effect if/when the 
performance problem is addressed.

>> Can we detect that TUs compiled with -flto-unit are being mixed with those 
>> not built without -flto-unit at the thin link time and issue an error?
> 
> This would be doable pretty easily. E.g. add a flag at the index level that 
> the module would have been split but wasn't. Users who get the error and want 
> to support always-enabled CFI could opt in via -flto-unit.

Yes. I don't think we should make a change like this unless there is something 
like that in place, though. The documentation (LTOVisibility.rst) needs to be 
updated too.


Repository:
  rC Clang

https://reviews.llvm.org/D53524



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


[PATCH] D53716: [AST] Only store data for the NRVO candidate in ReturnStmt if needed.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rjmccall.
riccibruno added a project: clang.
Herald added subscribers: cfe-commits, javed.absar.

Only store the NRVO candidate if needed in `ReturnStmt`.
A good chuck of all of the `ReturnStmt` have no NRVO candidate.
For all of them this saves one pointer.

This has no impact on `children()`.


Repository:
  rC Clang

https://reviews.llvm.org/D53716

Files:
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Stmt.cpp
  lib/Analysis/BodyFarm.cpp
  lib/CodeGen/CGObjC.cpp
  lib/Sema/SemaStmt.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp

Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -249,9 +249,15 @@
 
 void ASTStmtWriter::VisitReturnStmt(ReturnStmt *S) {
   VisitStmt(S);
+
+  bool HasNRVOCandidate = !!S->getNRVOCandidate();
+  Record.push_back(HasNRVOCandidate);
+
   Record.AddStmt(S->getRetValue());
+  if (HasNRVOCandidate)
+Record.AddDeclRef(S->getNRVOCandidate());
+
   Record.AddSourceLocation(S->getReturnLoc());
-  Record.AddDeclRef(S->getNRVOCandidate());
   Code = serialization::STMT_RETURN;
 }
 
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -328,9 +328,14 @@
 
 void ASTStmtReader::VisitReturnStmt(ReturnStmt *S) {
   VisitStmt(S);
+
+  bool HasNRVOCandidate = Record.readInt();
+
   S->setRetValue(Record.readSubExpr());
+  if (HasNRVOCandidate)
+S->setNRVOCandidate(ReadDeclAs());
+
   S->setReturnLoc(ReadSourceLocation());
-  S->setNRVOCandidate(ReadDeclAs());
 }
 
 void ASTStmtReader::VisitDeclStmt(DeclStmt *S) {
@@ -2357,7 +2362,8 @@
   break;
 
 case STMT_RETURN:
-  S = new (Context) ReturnStmt(Empty);
+  S = ReturnStmt::CreateEmpty(
+  Context, /* HasNRVOCandidate=*/Record[ASTStmtReader::NumStmtFields]);
   break;
 
 case STMT_DECL:
Index: lib/Sema/SemaStmt.cpp
===
--- lib/Sema/SemaStmt.cpp
+++ lib/Sema/SemaStmt.cpp
@@ -3220,7 +3220,8 @@
 return StmtError();
   RetValExp = ER.get();
 }
-return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
+return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
+  /* NRVOCandidate=*/nullptr);
   }
 
   if (HasDeducedReturnType) {
@@ -3346,8 +3347,8 @@
   return StmtError();
 RetValExp = ER.get();
   }
-  ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
-NRVOCandidate);
+  auto *Result =
+  ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
 
   // If we need to check for the named return value optimization,
   // or if we need to infer the return type,
@@ -3576,7 +3577,8 @@
 return StmtError();
   RetValExp = ER.get();
 }
-return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
+return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
+  /* NRVOCandidate=*/nullptr);
   }
 
   // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
@@ -3671,7 +3673,7 @@
   }
 }
 
-Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
+Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, nullptr);
   } else if (!RetValExp && !HasDependentReturnType) {
 FunctionDecl *FD = getCurFunctionDecl();
 
@@ -3693,7 +3695,8 @@
 else
   Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
 
-Result = new (Context) ReturnStmt(ReturnLoc);
+Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
+/* NRVOCandidate=*/nullptr);
   } else {
 assert(RetValExp || HasDependentReturnType);
 const VarDecl *NRVOCandidate = nullptr;
@@ -3746,7 +3749,7 @@
 return StmtError();
   RetValExp = ER.get();
 }
-Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
+Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
   }
 
   // If we need to check for the named return value optimization, save the
Index: lib/CodeGen/CGObjC.cpp
===
--- lib/CodeGen/CGObjC.cpp
+++ lib/CodeGen/CGObjC.cpp
@@ -883,9 +883,10 @@
   // If there's a non-trivial 'get' expression, we just have to emit that.
   if (!hasTrivialGetExpr(propImpl)) {
 if (!AtomicHelperFn) {
-  ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
- /*nrvo*/ nullptr);
-  EmitReturnStmt(ret);
+  auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
+ propImpl->getGetterCXXConstructor(),
+

[PATCH] D53207: Fix bug 26547 - alignof should return ABI alignment, not preferred alignment

2018-10-25 Thread Nicole Mazzuca via Phabricator via cfe-commits
ubsan added a comment.

I don't actually know how to send this upstream, since it's been accepted... 
How should I proceed?


Repository:
  rC Clang

https://reviews.llvm.org/D53207



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


[PATCH] D53276: [analyzer][NFC] Fix some incorrect uses of -analyzer-config options

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171130.
Szelethus added a comment.

`RetainCountChecker` now gets it's option when registering, like every other 
checker.

`RetainCountChecker` stored a reference to `AnalyzerOptions`, evaluated an 
option during construction, and one later down the line. This hid an 
interesting problem when I made `IncludeAllocationLine` a checker-specific 
option: since checkers get their names //after// their construction, it looked 
for `-analyzer-config :IncludeAllocationLine=` instead of 
`-analyzer-config osx.cocoa.RetainCount:IncludeAllocationLine=`.

Another issue that helped this issue hide so well is that this option has no 
test associated with it, but that's an unrelated observation.


https://reviews.llvm.org/D53276

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/StaticAnalyzer/Checkers/AllocationDiagnostics.cpp
  lib/StaticAnalyzer/Checkers/AllocationDiagnostics.h
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/RegionStore.cpp
  lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/cstring-plist.c
  test/Analysis/localization-aggressive.m

Index: test/Analysis/localization-aggressive.m
===
--- test/Analysis/localization-aggressive.m
+++ test/Analysis/localization-aggressive.m
@@ -1,6 +1,10 @@
 // RUN: %clang_cc1 -fblocks -x objective-c-header -emit-pch -o %t.pch %S/Inputs/localization-pch.h
 
-// RUN: %clang_analyze_cc1 -fblocks -analyzer-store=region  -analyzer-checker=optin.osx.cocoa.localizability.NonLocalizedStringChecker -analyzer-checker=optin.osx.cocoa.localizability.EmptyLocalizationContextChecker -include-pch %t.pch -verify  -analyzer-config AggressiveReport=true %s
+// RUN: %clang_analyze_cc1 -fblocks -analyzer-store=region \
+// RUN:   -analyzer-config optin.osx.cocoa.localizability.NonLocalizedStringChecker:AggressiveReport=true \
+// RUN:   -analyzer-checker=optin.osx.cocoa.localizability.NonLocalizedStringChecker \
+// RUN:   -analyzer-checker=optin.osx.cocoa.localizability.EmptyLocalizationContextChecker \
+// RUN:   -include-pch %t.pch -verify  %s
 
 // These declarations were reduced using Delta-Debugging from Foundation.h
 // on Mac OS X.
Index: test/Analysis/cstring-plist.c
===
--- test/Analysis/cstring-plist.c
+++ test/Analysis/cstring-plist.c
@@ -1,5 +1,8 @@
 // RUN: rm -f %t
-// RUN: %clang_analyze_cc1 -fblocks -analyzer-checker=core,unix.Malloc,unix.cstring.NullArg -analyzer-disable-checker=alpha.unix.cstring.OutOfBounds -analyzer-output=plist -analyzer-config path-diagnostics-alternate=false -o %t %s
+// RUN: %clang_analyze_cc1 -fblocks \
+// RUN:   -analyzer-checker=core,unix.Malloc,unix.cstring.NullArg \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.OutOfBounds \
+// RUN:   -analyzer-output=plist -o %t %s
 // RUN: FileCheck -input-file %t %s
 
 typedef __typeof(sizeof(int)) size_t;
Index: test/Analysis/analyzer-config.cpp
===
--- test/Analysis/analyzer-config.cpp
+++ test/Analysis/analyzer-config.cpp
@@ -41,7 +41,6 @@
 // CHECK-NEXT: inline-lambdas = true
 // CHECK-NEXT: ipa = dynamic-bifurcate
 // CHECK-NEXT: ipa-always-inline-size = 3
-// CHECK-NEXT: leak-diagnostics-reference-allocation = false
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
 // CHECK-NEXT: max-times-inline-large = 32
@@ -52,4 +51,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 32
+// CHECK-NEXT: num-entries = 31
Index: test/Analysis/analyzer-config.c
===
--- test/Analysis/analyzer-config.c
+++ test/Analysis/analyzer-config.c
@@ -26,7 +26,6 @@
 // CHECK-NEXT: inline-lambdas = true
 // CHECK-NEXT: ipa = dynamic-bifurcate
 // CHECK-NEXT: ipa-always-inline-size = 3
-// CHECK-NEXT: leak-diagnostics-reference-allocation = false
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
 // CHECK-NEXT: max-times-inline-large = 32
@@ -37,4 +36,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 25
+// CHECK-NEXT: num-entries = 24
Index: lib/StaticAnalyzer/Frontend/ModelInjector.cpp
===
--- lib/StaticAnalyzer/Frontend/ModelInjector.cpp
+++ lib/StaticAnalyzer/Frontend/ModelInjector.cpp
@@ -48,7 +48,7 @@
   FileID mainFileID = SM.getMainFileID();
 
   AnalyzerOptionsRef analyzerOpts = CI.getAnalyz

r345284 - [analyzer] Move canReasonAbout from Z3ConstraintManager to SMTConstraintManager

2018-10-25 Thread Mikhail R. Gadelha via cfe-commits
Author: mramalho
Date: Thu Oct 25 10:27:42 2018
New Revision: 345284

URL: http://llvm.org/viewvc/llvm-project?rev=345284&view=rev
Log:
[analyzer] Move canReasonAbout from Z3ConstraintManager to SMTConstraintManager

Summary:
This patch moves the last method in `Z3ConstraintManager` to 
`SMTConstraintManager`: `canReasonAbout()`.

The `canReasonAbout()` method checks if a given `SVal` can be encoded in SMT. 
I've added a new method to the SMT API to return true if a solver can encode 
floating-point arithmetics and it was enough to make `canReasonAbout()` solver 
independent.

As an annoying side-effect, `Z3ConstraintManager` is pretty empty now and only 
(1) creates the Z3 solver object by calling `CreateZ3Solver()` and (2) 
instantiates `SMTConstraintManager`. Maybe we can get rid of this class 
altogether in the future: a `CreateSMTConstraintManager()` method that does (1) 
and (2) and returns the constraint manager object?

Reviewers: george.karpenkov, NoQ

Reviewed By: george.karpenkov

Subscribers: mehdi_amini, xazax.hun, szepet, a.sidorin, dexonsmith, Szelethus, 
donat.nagy, dkrupp

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

Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h
cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h?rev=345284&r1=345283&r2=345284&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
 (original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
 Thu Oct 25 10:27:42 2018
@@ -218,6 +218,52 @@ public:
 OS << nl;
   }
 
+  bool canReasonAbout(SVal X) const override {
+const TargetInfo &TI = getBasicVals().getContext().getTargetInfo();
+
+Optional SymVal = X.getAs();
+if (!SymVal)
+  return true;
+
+const SymExpr *Sym = SymVal->getSymbol();
+QualType Ty = Sym->getType();
+
+// Complex types are not modeled
+if (Ty->isComplexType() || Ty->isComplexIntegerType())
+  return false;
+
+// Non-IEEE 754 floating-point types are not modeled
+if ((Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
+ (&TI.getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended() ||
+  &TI.getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble(
+  return false;
+
+if (Ty->isRealFloatingType())
+  return Solver->isFPSupported();
+
+if (isa(Sym))
+  return true;
+
+SValBuilder &SVB = getSValBuilder();
+
+if (const SymbolCast *SC = dyn_cast(Sym))
+  return canReasonAbout(SVB.makeSymbolVal(SC->getOperand()));
+
+if (const BinarySymExpr *BSE = dyn_cast(Sym)) {
+  if (const SymIntExpr *SIE = dyn_cast(BSE))
+return canReasonAbout(SVB.makeSymbolVal(SIE->getLHS()));
+
+  if (const IntSymExpr *ISE = dyn_cast(BSE))
+return canReasonAbout(SVB.makeSymbolVal(ISE->getRHS()));
+
+  if (const SymSymExpr *SSE = dyn_cast(BSE))
+return canReasonAbout(SVB.makeSymbolVal(SSE->getLHS())) &&
+   canReasonAbout(SVB.makeSymbolVal(SSE->getRHS()));
+}
+
+llvm_unreachable("Unsupported expression to reason about!");
+  }
+
   /// Dumps SMT formula
   LLVM_DUMP_METHOD void dump() const { Solver->dump(); }
 

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h?rev=345284&r1=345283&r2=345284&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h Thu 
Oct 25 10:27:42 2018
@@ -285,6 +285,9 @@ public:
   /// Reset the solver and remove all constraints.
   virtual void reset() = 0;
 
+  /// Checks if the solver supports floating-points.
+  virtual bool isFPSupported() = 0;
+
   virtual void print(raw_ostream &OS) const = 0;
 };
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp?rev=345284&r1=345283&r2=345284&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp Thu Oct 25 
10:27:42 2018
@@ -860,6 +860,8 @@ public:
 return Z3Model(Context, Z3_solver_get_model(Context.Context, Solver));
   }
 
+  bool isFPSupported() override { return true; }
+
   /// Reset th

r345283 - [analyzer] Fixed bitvector from model always being unsigned

2018-10-25 Thread Mikhail R. Gadelha via cfe-commits
Author: mramalho
Date: Thu Oct 25 10:27:36 2018
New Revision: 345283

URL: http://llvm.org/viewvc/llvm-project?rev=345283&view=rev
Log:
[analyzer] Fixed bitvector from model always being unsigned

Summary:
Getting an `APSInt` from the model always returned an unsigned integer because 
of the unused parameter.

This was not breaking any test case because no code relies on the actual value 
of the integer returned here, but rather it is only used to check if a symbol 
has more than one solution in `getSymVal`.

Reviewers: NoQ, george.karpenkov

Reviewed By: george.karpenkov

Subscribers: xazax.hun, szepet, a.sidorin, Szelethus, donat.nagy, dkrupp

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp?rev=345283&r1=345282&r2=345283&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp Thu Oct 25 
10:27:36 2018
@@ -733,9 +733,11 @@ public:
 
   llvm::APSInt getBitvector(const SMTExprRef &Exp, unsigned BitWidth,
 bool isUnsigned) override {
-return llvm::APSInt(llvm::APInt(
-BitWidth, Z3_get_numeral_string(Context.Context, toZ3Expr(*Exp).AST),
-10));
+return llvm::APSInt(
+llvm::APInt(BitWidth,
+Z3_get_numeral_string(Context.Context, toZ3Expr(*Exp).AST),
+10),
+isUnsigned);
   }
 
   bool getBoolean(const SMTExprRef &Exp) override {


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


[PATCH] D53276: [analyzer][NFC] Fix some incorrect uses of -analyzer-config options

2018-10-25 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov requested changes to this revision.
george.karpenkov added a comment.
This revision now requires changes to proceed.

Minor nitpicks, otherwise makes sense!




Comment at: include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:746
+  /// exploring a top level function (for each exploded graph). 0 means no 
limit.
+  unsigned getRegionStoreSmallStructLimit();
+

The comment seems completely distinct from the function name.



Comment at: include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:748
+
+  StringRef getModelPath();
 };

Comment?


https://reviews.llvm.org/D53276



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


[PATCH] D53717: [AST] Only store the needed data in ForStmt.

2018-10-25 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rjmccall.
riccibruno added a project: clang.
Herald added a subscriber: cfe-commits.
riccibruno added a dependency: D53716: [AST] Only store data for the NRVO 
candidate in ReturnStmt if needed..

Don't store the init statement and condition variable if not needed.
This cuts the size of `ForStmt` by up to 2 pointers, and 1 pointer in
the common case. The condition and increment are stored unconditionally
since for statements without a condition and increment are quite uncommon.
The order of the children is kept the same.


Repository:
  rC Clang

https://reviews.llvm.org/D53717

Files:
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Stmt.cpp
  lib/Sema/SemaStmt.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/Import/for-stmt/test.cpp

Index: test/Import/for-stmt/test.cpp
===
--- test/Import/for-stmt/test.cpp
+++ test/Import/for-stmt/test.cpp
@@ -3,21 +3,17 @@
 // CHECK: ForStmt
 // CHECK-NEXT: <>
 // CHECK-NEXT: <>
-// CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: NullStmt
 
 // CHECK: ForStmt
 // CHECK-NEXT: DeclStmt
 // CHECK-NEXT: VarDecl
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: <>
 // CHECK-NEXT: <>
-// CHECK-NEXT: <>
 // CHECK-NEXT: ContinueStmt
 
 // CHECK: ForStmt
-// CHECK-NEXT: <>
 // CHECK-NEXT: DeclStmt
 // CHECK-NEXT: VarDecl
 // CHECK-NEXT: CXXBoolLiteralExpr
@@ -32,7 +28,6 @@
 // CHECK-NEXT: DeclStmt
 // CHECK-NEXT: VarDecl
 // CHECK-NEXT: IntegerLiteral
-// CHECK-NEXT: <>
 
 // CHECK-NEXT: BinaryOperator
 // CHECK-NEXT: ImplicitCastExpr
Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -208,11 +208,20 @@
 
 void ASTStmtWriter::VisitForStmt(ForStmt *S) {
   VisitStmt(S);
-  Record.AddStmt(S->getInit());
+
+  bool HasInit = !!S->getInit();
+  bool HasVar = !!S->getConditionVariableDeclStmt();
+  Record.push_back(HasInit);
+  Record.push_back(HasVar);
+
   Record.AddStmt(S->getCond());
-  Record.AddDeclRef(S->getConditionVariable());
   Record.AddStmt(S->getInc());
   Record.AddStmt(S->getBody());
+  if (HasInit)
+Record.AddStmt(S->getInit());
+  if (HasVar)
+Record.AddDeclRef(S->getConditionVariable());
+
   Record.AddSourceLocation(S->getForLoc());
   Record.AddSourceLocation(S->getLParenLoc());
   Record.AddSourceLocation(S->getRParenLoc());
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -292,11 +292,18 @@
 
 void ASTStmtReader::VisitForStmt(ForStmt *S) {
   VisitStmt(S);
-  S->setInit(Record.readSubStmt());
+
+  bool HasInit = Record.readInt();
+  bool HasVar = Record.readInt();
+
   S->setCond(Record.readSubExpr());
-  S->setConditionVariable(Record.getContext(), ReadDeclAs());
   S->setInc(Record.readSubExpr());
   S->setBody(Record.readSubStmt());
+  if (HasInit)
+S->setInit(Record.readSubStmt());
+  if (HasVar)
+S->setConditionVariable(Record.getContext(), ReadDeclAs());
+
   S->setForLoc(ReadSourceLocation());
   S->setLParenLoc(ReadSourceLocation());
   S->setRParenLoc(ReadSourceLocation());
@@ -2342,7 +2349,10 @@
   break;
 
 case STMT_FOR:
-  S = new (Context) ForStmt(Empty);
+  S = ForStmt::CreateEmpty(
+  Context,
+  /* HasInit=*/Record[ASTStmtReader::NumStmtFields + 0],
+  /* HasVar=*/Record[ASTStmtReader::NumStmtFields + 1]);
   break;
 
 case STMT_GOTO:
Index: lib/Sema/SemaStmt.cpp
===
--- lib/Sema/SemaStmt.cpp
+++ lib/Sema/SemaStmt.cpp
@@ -1780,9 +1780,9 @@
   if (isa(Body))
 getCurCompoundScope().setHasEmptyLoopBodies();
 
-  return new (Context)
-  ForStmt(Context, First, Second.get().second, Second.get().first, Third,
-  Body, ForLoc, LParenLoc, RParenLoc);
+  return ForStmt::Create(Context, First, Second.get().second,
+ Second.get().first, Third, Body, ForLoc, LParenLoc,
+ RParenLoc);
 }
 
 /// In an Objective C collection iteration statement:
Index: lib/AST/Stmt.cpp
===
--- lib/AST/Stmt.cpp
+++ lib/AST/Stmt.cpp
@@ -881,36 +881,70 @@
   return isa(getCond());
 }
 
-ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
- Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
- SourceLocation RP)
-  : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
-{
-  SubExprs[INIT] = Init;
-  setConditionVariable(C, condVar);
-  SubExprs[COND] = Cond;
-  SubExprs[INC] = Inc;
-  SubExprs[BODY] = Body;
-  ForStmtBits.ForLoc = FL;
-}
-
-VarDecl *ForStmt::getConditionVariable() const {
-  if (!SubExpr

[PATCH] D53276: [analyzer][NFC] Fix some incorrect uses of -analyzer-config options

2018-10-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171141.
Szelethus added a comment.

- Added description as @george.karpenkov mentioned.

Thanks! I guess it's up to @NoQ whether he and @dcoughlin are okay with making 
some options checker options.


https://reviews.llvm.org/D53276

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/StaticAnalyzer/Checkers/AllocationDiagnostics.cpp
  lib/StaticAnalyzer/Checkers/AllocationDiagnostics.h
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/RegionStore.cpp
  lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/cstring-plist.c
  test/Analysis/localization-aggressive.m

Index: test/Analysis/localization-aggressive.m
===
--- test/Analysis/localization-aggressive.m
+++ test/Analysis/localization-aggressive.m
@@ -1,6 +1,10 @@
 // RUN: %clang_cc1 -fblocks -x objective-c-header -emit-pch -o %t.pch %S/Inputs/localization-pch.h
 
-// RUN: %clang_analyze_cc1 -fblocks -analyzer-store=region  -analyzer-checker=optin.osx.cocoa.localizability.NonLocalizedStringChecker -analyzer-checker=optin.osx.cocoa.localizability.EmptyLocalizationContextChecker -include-pch %t.pch -verify  -analyzer-config AggressiveReport=true %s
+// RUN: %clang_analyze_cc1 -fblocks -analyzer-store=region \
+// RUN:   -analyzer-config optin.osx.cocoa.localizability.NonLocalizedStringChecker:AggressiveReport=true \
+// RUN:   -analyzer-checker=optin.osx.cocoa.localizability.NonLocalizedStringChecker \
+// RUN:   -analyzer-checker=optin.osx.cocoa.localizability.EmptyLocalizationContextChecker \
+// RUN:   -include-pch %t.pch -verify  %s
 
 // These declarations were reduced using Delta-Debugging from Foundation.h
 // on Mac OS X.
Index: test/Analysis/cstring-plist.c
===
--- test/Analysis/cstring-plist.c
+++ test/Analysis/cstring-plist.c
@@ -1,5 +1,8 @@
 // RUN: rm -f %t
-// RUN: %clang_analyze_cc1 -fblocks -analyzer-checker=core,unix.Malloc,unix.cstring.NullArg -analyzer-disable-checker=alpha.unix.cstring.OutOfBounds -analyzer-output=plist -analyzer-config path-diagnostics-alternate=false -o %t %s
+// RUN: %clang_analyze_cc1 -fblocks \
+// RUN:   -analyzer-checker=core,unix.Malloc,unix.cstring.NullArg \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.OutOfBounds \
+// RUN:   -analyzer-output=plist -o %t %s
 // RUN: FileCheck -input-file %t %s
 
 typedef __typeof(sizeof(int)) size_t;
Index: test/Analysis/analyzer-config.cpp
===
--- test/Analysis/analyzer-config.cpp
+++ test/Analysis/analyzer-config.cpp
@@ -41,7 +41,6 @@
 // CHECK-NEXT: inline-lambdas = true
 // CHECK-NEXT: ipa = dynamic-bifurcate
 // CHECK-NEXT: ipa-always-inline-size = 3
-// CHECK-NEXT: leak-diagnostics-reference-allocation = false
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
 // CHECK-NEXT: max-times-inline-large = 32
@@ -52,4 +51,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 32
+// CHECK-NEXT: num-entries = 31
Index: test/Analysis/analyzer-config.c
===
--- test/Analysis/analyzer-config.c
+++ test/Analysis/analyzer-config.c
@@ -26,7 +26,6 @@
 // CHECK-NEXT: inline-lambdas = true
 // CHECK-NEXT: ipa = dynamic-bifurcate
 // CHECK-NEXT: ipa-always-inline-size = 3
-// CHECK-NEXT: leak-diagnostics-reference-allocation = false
 // CHECK-NEXT: max-inlinable-size = 100
 // CHECK-NEXT: max-nodes = 225000
 // CHECK-NEXT: max-times-inline-large = 32
@@ -37,4 +36,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 25
+// CHECK-NEXT: num-entries = 24
Index: lib/StaticAnalyzer/Frontend/ModelInjector.cpp
===
--- lib/StaticAnalyzer/Frontend/ModelInjector.cpp
+++ lib/StaticAnalyzer/Frontend/ModelInjector.cpp
@@ -48,7 +48,7 @@
   FileID mainFileID = SM.getMainFileID();
 
   AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
-  llvm::StringRef modelPath = analyzerOpts->Config["model-path"];
+  llvm::StringRef modelPath = analyzerOpts->getModelPath();
 
   llvm::SmallString<128> fileName;
 
Index: lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- lib/StaticAnalyzer/Core/RegionStore.cpp
+++ lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -350,7 +350,7 @@
 if (SubEngine *Eng = StateMgr.getOwningEngine()) {
   AnalyzerOptions &Options = E

[PATCH] D40925: Add option -fkeep-static-consts

2018-10-25 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a subscriber: zturner.
rnk added a comment.

My coworker, @zturner, asked if I knew a way to force emit all constants, and I 
mentioned this flag, but we noticed it doesn't work on cases when the constant 
is implicitly static, like this:

  const int foo = 42;

If I add `static` to it, it gets emitted with -fkeep-static-consts, but as is, 
it doesn't get emitted.

Do you think it's worth extending the logic to handle this case? GCC seems to 
that global `foo` regardless of the flag setting.


Repository:
  rC Clang

https://reviews.llvm.org/D40925



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


r345291 - CodeGen: alter CFConstantString class name for swift 5.0

2018-10-25 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Thu Oct 25 10:52:13 2018
New Revision: 345291

URL: http://llvm.org/viewvc/llvm-project?rev=345291&view=rev
Log:
CodeGen: alter CFConstantString class name for swift 5.0

Swift 5.0 has changed the name decoration for swift symbols, using a 'S' sigil
rather than 's' as in 4.2.  Adopt the new convention.

Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/test/CodeGen/cf-runtime-abi.c

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=345291&r1=345290&r2=345291&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Thu Oct 25 10:52:13 2018
@@ -4139,7 +4139,12 @@ CodeGenModule::GetAddrOfConstantCFString
 switch (CFRuntime) {
 default: break;
 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
-case LangOptions::CoreFoundationABI::Swift5_0: LLVM_FALLTHROUGH;
+case LangOptions::CoreFoundationABI::Swift5_0:
+  CFConstantStringClassName =
+  Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
+  : "$S10Foundation19_NSCFConstantStringCN";
+  Ty = IntPtrTy;
+  break;
 case LangOptions::CoreFoundationABI::Swift4_2:
   CFConstantStringClassName =
   Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"

Modified: cfe/trunk/test/CodeGen/cf-runtime-abi.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/cf-runtime-abi.c?rev=345291&r1=345290&r2=345291&view=diff
==
--- cfe/trunk/test/CodeGen/cf-runtime-abi.c (original)
+++ cfe/trunk/test/CodeGen/cf-runtime-abi.c Thu Oct 25 10:52:13 2018
@@ -43,10 +43,10 @@ const __NSConstantString *s = __builtin_
 // CHECK-OBJC: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x 
i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i64 0 }
 // CHECK-OBJC-LLP64: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x 
i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i32 0 }
 
-// CHECK-SWIFT-DARWIN-5_0-64: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i64 ptrtoint (i64* 
@"$s15SwiftFoundation19_NSCFConstantStringCN" to i64), i64 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i64 0 }
-// CHECK-SWIFT-DARWIN-5_0-32: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i32 ptrtoint (i32* 
@"$s15SwiftFoundation19_NSCFConstantStringCN" to i32), i32 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i32 0 }
-// CHECK-SWIFT-5_0-64: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i64 ptrtoint (i64* 
@"$s10Foundation19_NSCFConstantStringCN" to i64), i64 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i64 0 }
-// CHECK-SWIFT-5_0-32: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i32 ptrtoint (i32* 
@"$s10Foundation19_NSCFConstantStringCN" to i32), i32 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i32 0 }
+// CHECK-SWIFT-DARWIN-5_0-64: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i64 ptrtoint (i64* 
@"$S15SwiftFoundation19_NSCFConstantStringCN" to i64), i64 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i64 0 }
+// CHECK-SWIFT-DARWIN-5_0-32: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i32 ptrtoint (i32* 
@"$S15SwiftFoundation19_NSCFConstantStringCN" to i32), i32 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i32 0 }
+// CHECK-SWIFT-5_0-64: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i64 ptrtoint (i64* 
@"$S10Foundation19_NSCFConstantStringCN" to i64), i64 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i64 0 }
+// CHECK-SWIFT-5_0-32: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i32 ptrtoint (i32* 
@"$S10Foundation19_NSCFConstantStringCN" to i32), i32 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i32 0 }
 
 // CHECK-SWIFT-DARWIN-4_2-64: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString_tag { i64 ptrtoint (i64* 
@"$s15SwiftFoundation19_NSCFConstantStringCN" to i64), i64 1, i64 1992, i8* 
getelementptr inbounds ([1 x i8], [1 x i8]* @.str, i32 0, i32 0), i32 0 }
 // CHECK-SWIFT-DARWIN-4_2-32: @_unnamed_cfstring_ = private global 
%struct.__NSConstantString

[PATCH] D53076: [analyzer] Enhance ConditionBRVisitor to write out more information

2018-10-25 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added inline comments.



Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:1853
+
+const auto *Cond = cast(PS->getStmt());
+auto Piece = VisitTrueTest(Cond, tag == tags.first, BRC, BR, N);

george.karpenkov wrote:
> How do we know that it's always an `Expr`?
`VisitTrueTest` operates with `Expr` only, so I just left the type.



Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:1970
 
+bool ConditionBRVisitor::insertOrUpdateConstraintMessage(const Stmt *Cond,
+ StringRef Message) {

george.karpenkov wrote:
> 1. What about the refactoring I have previously suggested twice?
> 2. I know you have started with that -- and sorry for spurious changes -- but 
> I also think your original name of `constraintsChanged` is better.
> We have multiple messages at the same place so we have to update the message. 
> The problem with your code is insert operates with disjunct keys, not values.

I have commented this after the last refactor, sorry for the inconvenience.


https://reviews.llvm.org/D53076



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


  1   2   3   >