[PATCH] D37210: [refactor] add a refactoring action rule that returns symbol occurrences

2017-08-29 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added a comment.
This revision is now accepted and ready to land.

Lgtm


Repository:
  rL LLVM

https://reviews.llvm.org/D37210



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


[PATCH] D32788: Fix std::inplace_merge to be stable for all inputs

2017-08-29 Thread Jan Wilken Dörrie via Phabricator via cfe-commits
jdoerrie added a comment.

Thanks for applying a fix based on my patch! I could have sworn the added tests 
failed locally before applying the algorithm patch, though... oh well.


https://reviews.llvm.org/D32788



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


[PATCH] D37143: [clang-format] Fixed missing enter before bracket in typedef enum and extern

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee updated this revision to Diff 113035.
PriMee added a comment.

Unit tests added. If there is indeed a necessity to separate these two cases 
just inform me :)


https://reviews.llvm.org/D37143

Files:
  lib/Format/TokenAnnotator.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
@@ -1595,7 +1621,25 @@
Style));
 }
 
-TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
+TEST_F(FormatTest, FormatsExternC) { 
+  verifyFormat("extern \"C\" {\nint a;");
+  verifyFormat("extern \"C\" {};");
+  EXPECT_EQ("extern \"C\" {\n"
+"int i = 42;\n"
+"}",
+format("extern \"C\" {\n"
+   "int i = 42;\n"
+   "}"));
+  EXPECT_EQ("extern \"C\"\n" 
+"{\n"
+"int i = 42;\n"
+"}",
+format("extern \"C\"\n" 
+   "{\n"
+   "int i = 42;\n"
+   "}"));
+
+}
 
 TEST_F(FormatTest, FormatsInlineASM) {
   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -986,6 +986,8 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+if (isOnNewLine(*FormatTok))
+  FormatTok->MustBreakBefore = true;
 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
 addUnwrappedLine();
 return;
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 
Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) 
||
(Line.startsWith(tok::kw_struct) && 
Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
@@ -1595,7 +162

[PATCH] D37142: clang-format: [JS] simplify template string wrapping.

2017-08-29 Thread Martin Probst via Phabricator via cfe-commits
mprobst updated this revision to Diff 113036.
mprobst added a comment.

- drop function name wrapping hack


https://reviews.llvm.org/D37142

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

Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -1793,43 +1793,39 @@
   verifyFormat("var x = someFunction(`${})`)  //\n"
".oon();");
   verifyFormat("var x = someFunction(`${}${\n"
-   "   a(  //\n"
-   "   a)\n"
-   " })`);");
+   "a(  //\n"
+   "a)})`);");
 }
 
 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
   verifyFormat("var f = `aa: ${\n"
-   "   a +  //\n"
-   "   \n"
-   " }`;",
+   "a +  //\n"
+   "}`;",
"var f = `aa: ${a +  //\n"
"   }`;");
   verifyFormat("var f = `\n"
"  aa: ${\n"
-   "a +  //\n"
-   "\n"
-   "  }`;",
+   "a +  //\n"
+   "}`;",
"var f  =  `\n"
"  aa: ${   a  +  //\n"
" }`;");
   verifyFormat("var f = `\n"
"  aa: ${\n"
-   "someFunction(\n"
-   "a +  //\n"
-   ")\n"
-   "  }`;",
+   "someFunction(\n"
+   "a +  //\n"
+   ")}`;",
"var f  =  `\n"
"  aa: ${someFunction (\n"
"a  +   //\n"
")}`;");
 
   // It might be preferable to wrap before "someFunction".
   verifyFormat("var f = `\n"
"  aa: ${someFunction({\n"
-   "  : a,\n"
-   "  : b,\n"
-   "})}`;",
+   "  : a,\n"
+   "  : b,\n"
+   "})}`;",
"var f  =  `\n"
"  aa: ${someFunction ({\n"
"  :  a,\n"
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -661,9 +661,7 @@
   // before the corresponding } or ].
   if (PreviousNonComment &&
   (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
-   opensProtoMessageField(*PreviousNonComment, Style) ||
-   (PreviousNonComment->is(TT_TemplateString) &&
-PreviousNonComment->opensScope(
+   opensProtoMessageField(*PreviousNonComment, Style)))
 State.Stack.back().BreakBeforeClosingBrace = true;
 
   if (State.Stack.back().AvoidBinPacking) {
@@ -925,11 +923,6 @@
 
   moveStatePastFakeLParens(State, Newline);
   moveStatePastScopeCloser(State);
-  if (Current.is(TT_TemplateString) && Current.opensScope())
-State.Stack.back().LastSpace =
-(Current.IsMultiline ? Current.LastLineColumnWidth
- : State.Column + Current.ColumnWidth) -
-strlen("${");
   bool CanBreakProtrudingToken = !State.Stack.back().NoLineBreak &&
  !State.Stack.back().NoLineBreakInOperand;
   moveStatePastScopeOpener(State, Newline);
@@ -1101,18 +1094,6 @@
   LastSpace = std::max(LastSpace, State.Stack.back().Indent);
 }
 
-// JavaScript template strings are special as we always want to indent
-// nested expressions relative to the ${}. Otherwise, this can create quite
-// a mess.
-if (Current.is(TT_TemplateString)) {
-  unsigned Column = Current.IsMultiline
-? Current.LastLineColumnWidth
-: State.Column + Current.ColumnWidth;
-  NewIndent = Column;
-  LastSpace = Column;
-  NestedBlockIndent = Column;
-}
-
 bool EndsInComma =
 Current.MatchingParen &&
 Current.MatchingParen->getPreviousNonComment() &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-b

r311988 - clang-format: [JS] simplify template string wrapping.

2017-08-29 Thread Martin Probst via cfe-commits
Author: mprobst
Date: Tue Aug 29 01:30:07 2017
New Revision: 311988

URL: http://llvm.org/viewvc/llvm-project?rev=311988&view=rev
Log:
clang-format: [JS] simplify template string wrapping.

Summary:
Previously, clang-format would try to wrap template string substitutions
by indenting relative to the openening `${`. This helped with
indenting structured strings, such as strings containing HTML, as the
substitutions would be aligned according to the structure of the string.

However it turns out that the overwhelming majority of template string +
substitution usages are for substitutions into non-structured strings,
e.g. URLs or just plain messages. For these situations, clang-format
would often produce very ugly indents, in particular for strings
containing no line breaks:

return `${file}(${
row
  },${
  col
}): `;

This change makes clang-format indent template string substitutions as
if they were string concatenation operations. It wraps +4 on overlong
lines and keeps all operands on the same line:

return `${file}(${
row},${col}): `;

While this breaks some lexical continuity between the `${` and `row}`
here, the overall effects are still a huge improvement, and users can
still manually break the string using `+` if desired.

Reviewers: djasper

Subscribers: klimek, cfe-commits

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

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

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=311988&r1=311987&r2=311988&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Tue Aug 29 01:30:07 2017
@@ -661,9 +661,7 @@ unsigned ContinuationIndenter::addTokenO
   // before the corresponding } or ].
   if (PreviousNonComment &&
   (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
-   opensProtoMessageField(*PreviousNonComment, Style) ||
-   (PreviousNonComment->is(TT_TemplateString) &&
-PreviousNonComment->opensScope(
+   opensProtoMessageField(*PreviousNonComment, Style)))
 State.Stack.back().BreakBeforeClosingBrace = true;
 
   if (State.Stack.back().AvoidBinPacking) {
@@ -925,11 +923,6 @@ unsigned ContinuationIndenter::moveState
 
   moveStatePastFakeLParens(State, Newline);
   moveStatePastScopeCloser(State);
-  if (Current.is(TT_TemplateString) && Current.opensScope())
-State.Stack.back().LastSpace =
-(Current.IsMultiline ? Current.LastLineColumnWidth
- : State.Column + Current.ColumnWidth) -
-strlen("${");
   bool CanBreakProtrudingToken = !State.Stack.back().NoLineBreak &&
  !State.Stack.back().NoLineBreakInOperand;
   moveStatePastScopeOpener(State, Newline);
@@ -1101,18 +1094,6 @@ void ContinuationIndenter::moveStatePast
   LastSpace = std::max(LastSpace, State.Stack.back().Indent);
 }
 
-// JavaScript template strings are special as we always want to indent
-// nested expressions relative to the ${}. Otherwise, this can create quite
-// a mess.
-if (Current.is(TT_TemplateString)) {
-  unsigned Column = Current.IsMultiline
-? Current.LastLineColumnWidth
-: State.Column + Current.ColumnWidth;
-  NewIndent = Column;
-  LastSpace = Column;
-  NestedBlockIndent = Column;
-}
-
 bool EndsInComma =
 Current.MatchingParen &&
 Current.MatchingParen->getPreviousNonComment() &&

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=311988&r1=311987&r2=311988&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Tue Aug 29 01:30:07 2017
@@ -1793,32 +1793,28 @@ TEST_F(FormatTestJS, TemplateStrings) {
   verifyFormat("var x = someFunction(`${})`)  //\n"
".oon();");
   verifyFormat("var x = someFunction(`${}${\n"
-   "   a(  //\n"
-   "   a)\n"
-   " })`);");
+   "a(  //\n"
+   "a)})`);");
 }
 
 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
   verifyFormat("var f = `aa: ${\

[PATCH] D37142: clang-format: [JS] simplify template string wrapping.

2017-08-29 Thread Martin Probst via Phabricator via cfe-commits
mprobst added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:1139
+
+  // On lines containing template strings, propagate NoLineBreak even for dict
+  // and array literals. This is to force wrapping an initial function call if

mprobst wrote:
> djasper wrote:
> > mprobst wrote:
> > > djasper wrote:
> > > > This is not the right way to implement this:
> > > > 
> > > > - This is a static computation that we could do ahead of time. Doing it 
> > > > inside the combinatorial exploration of solutions is a waste.
> > > > - You are doing this always, even in code that doesn't have template 
> > > > strings or isn't even JavaScript.
> > > > - This can lead to unexpected behavior if the template string is in a 
> > > > completely unrelated part of the statement. E.g.
> > > > 
> > > > 
> > > >   someFunction(`test`, { ... });
> > > > 
> > > > will be formatted differently from
> > > > 
> > > >   someFunction('test', { ... });
> > > Ack. Do you have suggestions?
> > > 
> > > I could introduce a `bool  ParenState::NoLineBreakMustPropagate;` that 
> > > controls this behaviour.
> > That, too, would create a significant memory and runtime overhead to 
> > everyone just to fix this rather minor formatting detail.
> > If we were to set MatchingParen correctly to match up "${" to "}", we could 
> > measure the respective length and at a very early state (mustBreak()) 
> > decide that we need a line break between "${" and the corresponding "}". 
> > Now setting that correctly might be hard. Maybe it is ok, to linearly scan 
> > in that case as we would only do that if we actually find a template string 
> > ending in "${" and the distance to the "}" is usually short.
> I cannot decide whether I must break in `mustBreak` - I need to just force 
> wrapping after `${` if I need to wrap somewhere below, but if the code fits 
> on the line, I don't want to wrap. So when I'm visiting `${` I cannot decide 
> that, and when I'm at the object literal expression, the decision for `${` 
> has already been made - right? Or am I missing something?
I've dropped the function wrapping fix and will land like this, apparently 
we'll need to think about this a bit more.


https://reviews.llvm.org/D37142



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


[PATCH] D37142: clang-format: [JS] simplify template string wrapping.

2017-08-29 Thread Martin Probst via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311988: clang-format: [JS] simplify template string 
wrapping. (authored by mprobst).

Repository:
  rL LLVM

https://reviews.llvm.org/D37142

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

Index: cfe/trunk/lib/Format/ContinuationIndenter.cpp
===
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp
@@ -661,9 +661,7 @@
   // before the corresponding } or ].
   if (PreviousNonComment &&
   (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
-   opensProtoMessageField(*PreviousNonComment, Style) ||
-   (PreviousNonComment->is(TT_TemplateString) &&
-PreviousNonComment->opensScope(
+   opensProtoMessageField(*PreviousNonComment, Style)))
 State.Stack.back().BreakBeforeClosingBrace = true;
 
   if (State.Stack.back().AvoidBinPacking) {
@@ -925,11 +923,6 @@
 
   moveStatePastFakeLParens(State, Newline);
   moveStatePastScopeCloser(State);
-  if (Current.is(TT_TemplateString) && Current.opensScope())
-State.Stack.back().LastSpace =
-(Current.IsMultiline ? Current.LastLineColumnWidth
- : State.Column + Current.ColumnWidth) -
-strlen("${");
   bool CanBreakProtrudingToken = !State.Stack.back().NoLineBreak &&
  !State.Stack.back().NoLineBreakInOperand;
   moveStatePastScopeOpener(State, Newline);
@@ -1101,18 +1094,6 @@
   LastSpace = std::max(LastSpace, State.Stack.back().Indent);
 }
 
-// JavaScript template strings are special as we always want to indent
-// nested expressions relative to the ${}. Otherwise, this can create quite
-// a mess.
-if (Current.is(TT_TemplateString)) {
-  unsigned Column = Current.IsMultiline
-? Current.LastLineColumnWidth
-: State.Column + Current.ColumnWidth;
-  NewIndent = Column;
-  LastSpace = Column;
-  NestedBlockIndent = Column;
-}
-
 bool EndsInComma =
 Current.MatchingParen &&
 Current.MatchingParen->getPreviousNonComment() &&
Index: cfe/trunk/unittests/Format/FormatTestJS.cpp
===
--- cfe/trunk/unittests/Format/FormatTestJS.cpp
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp
@@ -1793,43 +1793,39 @@
   verifyFormat("var x = someFunction(`${})`)  //\n"
".oon();");
   verifyFormat("var x = someFunction(`${}${\n"
-   "   a(  //\n"
-   "   a)\n"
-   " })`);");
+   "a(  //\n"
+   "a)})`);");
 }
 
 TEST_F(FormatTestJS, TemplateStringMultiLineExpression) {
   verifyFormat("var f = `aa: ${\n"
-   "   a +  //\n"
-   "   \n"
-   " }`;",
+   "a +  //\n"
+   "}`;",
"var f = `aa: ${a +  //\n"
"   }`;");
   verifyFormat("var f = `\n"
"  aa: ${\n"
-   "a +  //\n"
-   "\n"
-   "  }`;",
+   "a +  //\n"
+   "}`;",
"var f  =  `\n"
"  aa: ${   a  +  //\n"
" }`;");
   verifyFormat("var f = `\n"
"  aa: ${\n"
-   "someFunction(\n"
-   "a +  //\n"
-   ")\n"
-   "  }`;",
+   "someFunction(\n"
+   "a +  //\n"
+   ")}`;",
"var f  =  `\n"
"  aa: ${someFunction (\n"
"a  +   //\n"
")}`;");
 
   // It might be preferable to wrap before "someFunction".
   verifyFormat("var f = `\n"
"  aa: ${someFunction({\n"
-   "  : a,\n"
-   "  : b,\n"
-   "})}`;",
+   "  : a,\n"
+   "  : b,\n"
+   "})}`;",
"var f  =  `\n"
"  aa: ${someFunction ({\n"
 

[PATCH] D37254: [Sema] Disallow assigning record lvalues with nested const-qualified fields.

2017-08-29 Thread Bevin Hansson via Phabricator via cfe-commits
bevinh created this revision.

According to C99 6.3.2.1p1, structs and unions with nested
const-qualified fields (that is, const-qualified fields
declared at some recursive level of the aggregate) are not
modifiable lvalues. However, Clang permits assignments of
these lvalues.

With this patch, we both prohibit the assignment of records
with const-qualified fields and emit a best-effort diagnostic.
This fixes https://bugs.llvm.org/show_bug.cgi?id=31796 .


https://reviews.llvm.org/D37254

Files:
  include/clang/AST/Expr.h
  include/clang/AST/Type.h
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/AST/ExprClassification.cpp
  lib/AST/Type.cpp
  lib/Sema/SemaExpr.cpp
  test/Sema/assign.c

Index: test/Sema/assign.c
===
--- test/Sema/assign.c
+++ test/Sema/assign.c
@@ -16,3 +16,45 @@
   b[4] = 1; // expected-error {{read-only variable is not assignable}}
   b2[4] = 1; // expected-error {{read-only variable is not assignable}}
 }
+
+typedef struct I {
+  const int a; // expected-note 10{{non-static data member 'a' declared const here}}
+} I;
+typedef struct J {
+  struct I i;
+} J;
+typedef struct K {
+  struct J *j;
+} K;
+
+void testI(struct I i1, struct I i2) {
+  i1 = i2; // expected-error {{cannot assign to variable 'i1' with const-qualified data member 'a'}}
+}
+void testJ1(struct J j1, struct J j2) {
+  j1 = j2; // expected-error {{cannot assign to variable 'j1' with nested const-qualified data member 'a'}}
+}
+void testJ2(struct J j, struct I i) {
+  j.i = i; // expected-error {{cannot assign to non-static data member 'i' with const-qualified data member 'a'}}
+}
+void testK1(struct K k, struct J j) {
+  *(k.j) = j; // expected-error {{cannot assign to lvalue with nested const-qualified data member 'a'}}
+}
+void testK2(struct K k, struct I i) {
+  k.j->i = i; // expected-error {{cannot assign to non-static data member 'i' with const-qualified data member 'a'}}
+}
+
+void testI_(I i1, I i2) {
+  i1 = i2; // expected-error {{cannot assign to variable 'i1' with const-qualified data member 'a'}}
+}
+void testJ1_(J j1, J j2) {
+  j1 = j2; // expected-error {{cannot assign to variable 'j1' with nested const-qualified data member 'a'}}
+}
+void testJ2_(J j, I i) {
+  j.i = i; // expected-error {{cannot assign to non-static data member 'i' with const-qualified data member 'a'}}
+}
+void testK1_(K k, J j) {
+  *(k.j) = j; // expected-error {{cannot assign to lvalue with nested const-qualified data member 'a'}}
+}
+void testK2_(K k, I i) {
+  k.j->i = i; // expected-error {{cannot assign to non-static data member 'i' with const-qualified data member 'a'}}
+}
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -10176,22 +10176,23 @@
   return !Ty.isConstQualified();
 }
 
+// Update err_typecheck_assign_const and note_typecheck_assign_const
+// when this enum is changed.
+enum {
+  ConstFunction,
+  ConstVariable,
+  ConstMember,
+  ConstMethod,
+  NestedConstMember,
+  ConstUnknown,  // Keep as last element
+};
+
 /// Emit the "read-only variable not assignable" error and print notes to give
 /// more information about why the variable is not assignable, such as pointing
 /// to the declaration of a const variable, showing that a method is const, or
 /// that the function is returning a const reference.
 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
 SourceLocation Loc) {
-  // Update err_typecheck_assign_const and note_typecheck_assign_const
-  // when this enum is changed.
-  enum {
-ConstFunction,
-ConstVariable,
-ConstMember,
-ConstMethod,
-ConstUnknown,  // Keep as last element
-  };
-
   SourceRange ExprRange = E->getSourceRange();
 
   // Only emit one error on the first const found.  All other consts will emit
@@ -10301,6 +10302,66 @@
   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
 }
 
+enum OriginalExprKind {
+  OEK_Variable,
+  OEK_Member,
+  OEK_LValue
+};
+
+static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
+ const RecordType *Ty,
+ SourceLocation Loc, SourceRange Range,
+ OriginalExprKind OEK,
+ bool &DiagnosticEmitted,
+ bool IsNested = false) {
+  // We walk the record hierarchy breadth-first to ensure that we print
+  // diagnostics in field nesting order.
+  // First, check every field for constness.
+  for (const FieldDecl *Field : Ty->getDecl()->fields()) {
+if (Field->getType().isConstQualified()) {
+  if (!DiagnosticEmitted) {
+S.Diag(Loc, diag::err_typecheck_assign_const)
+<< Range << NestedConstMember << OEK << VD
+<< IsNested << Field;
+DiagnosticEmitted = true;

[PATCH] D35955: clang-format: Add preprocessor directive indentation

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

@euhlmann: are you planning to commit this?


https://reviews.llvm.org/D35955



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


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-08-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

In https://reviews.llvm.org/D34512#854729, @dcoughlin wrote:

> Except for some drive-by nits, this is a high-level review.
>
> I have some high-level questions about the design of the library:
>
> 1. **How do you intend to handle the case when there are multiple function 
> definitions with the same USR?** Whose responsibility it is to deal with 
> this: the client (for example, the static analyzer) or the index/database 
> (libCrossTU)? This seems to me to be a fundamental part of the design for 
> this feature that is missing. If you expect the client to handle this 
> scenario (for example, to pick a definition) I would expect the library API 
> to return more than a single potential result for a query. If you expect the 
> the library to pick a definition then at a minimum you should document how 
> this will be done. If the library will treat this as an error then you should 
> communicate this to the client so it can attempt to recover from it.


Right now we rely on the script that is using the analyzer such as 
scan-build-py or codechecker to remove the duplicate USRs from the index before 
starting the analysis. Having an `ErrorOr` return type so the user can handle 
the case when multiple definitions or none of them is found could be useful. It 
is not feasible to return multiple definitions, however. The importing alters 
the ASTContext, so the only way to choose between the definitions would be via 
a callback that is triggered before the import is done. What do you think?

> 
> 
> 2. **Whose responsibility is it to handle errors that the library runs 
> into?** Right now several errors appear to reported to the end user as 
> diagnostics. It seems to me that the decision of how (or whether) to report 
> these errors to the end user should be up to a particular client. Are these 
> errors even actionable on the part of end users? My sense it that with the 
> envisioned workflow users would not know/care about the format of the 
> database file.

The intention was that to report to the user that the index format is invalid, 
since it is a configuration issue that she might be able to handle. But we 
could also return an error code and leave the reporting to the client. The 
reason we introduced the diagnostic is that we assumed that the client can not 
recover from a configuration error and will end up reporting the problem to the 
user.

> 
> 
> 3. **Where should the code that understands the database file format live?** 
> Right now the logic for the parsing of the index format is in libCrossTU and 
> the emission of the index is in the command-line tool. I think it would be 
> easier to maintain if there were a single place that understand the file 
> format. This way consumers and emitters of the index could be easily updated 
> when the format/representation changes. Additionally, I think it is important 
> to document this format.

This is a very good point! I will update the library.




Comment at: include/clang/Basic/DiagnosticCrossTUKinds.td:13
+def err_fnmap_parsing : Error<
+  "error parsing CrossTU index file: '%0' line: %1 'USR filename' format "
+  "expected">;

dcoughlin wrote:
> Is this a user-facing diagnostic? Do we expect users to know what 'CrossTU' 
> means? Or what 'USR' means?
It is. Do you have any alternative suggestion? What about `error parsing index 
file` without mentioning any of the terms you mentioned?



Comment at: include/clang/CrossTU/CrossTranslationUnit.h:60
+  ///
+  /// Note that the AST files should also be in the \p CrossTUDir.
+  const FunctionDecl *getCrossTUDefinition(const FunctionDecl *FD,

dcoughlin wrote:
> Can this document what happens when the function declaration cannot be found? 
> And what happens when multiple function declarations are found?
Sure. Good point.



Comment at: lib/CrossTU/CrossTranslationUnit.cpp:48
+   StringRef LookupFnName) 
{
+  if (!DC)
+return nullptr;

dcoughlin wrote:
> Should this assert that DC is not null? What is the reason to accept null 
> here?
Indeed, an assert should be better. 



Comment at: lib/CrossTU/CrossTranslationUnit.cpp:81
+  if (!ExternalFnMapFile) {
+Context.getDiagnostics().Report(diag::err_fe_error_opening)
+<< ExternalFunctionMap << "required by the CrossTU functionality";

dcoughlin wrote:
> What is the rationale behind emitting this as a diagnostic? In general for a 
> library I would expect that errors would be communicated to the client, which 
> then would have responsibility for handling them, reporting them to the user, 
> or aborting.
Since this is likely to be a configuration error we were thinking that only the 
user can handle it. But I could transform this to an error code if you would 
prefer that solution. 



Comment at: lib/Cross

r311990 - [libclang]: Honor LIBCLANG_NOTHREADS for clang_parseTranslationUnit*

2017-08-29 Thread Erik Verbruggen via cfe-commits
Author: erikjv
Date: Tue Aug 29 02:08:02 2017
New Revision: 311990

URL: http://llvm.org/viewvc/llvm-project?rev=311990&view=rev
Log:
[libclang]: Honor LIBCLANG_NOTHREADS for clang_parseTranslationUnit*

Looks like this one was forgotten for clang_parseTranslationUnit*, as
LIBCLANG_NOTHREADS is checked for/in:

clang_saveTranslationUnit()
clang_reparseTranslationUnit()
clang_codeCompleteAt()
clang_indexTranslationUnit()
clang_indexSourceFile()

Patch by Nikolai Kosjar!

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


Modified:
cfe/trunk/tools/libclang/CIndex.cpp

Modified: cfe/trunk/tools/libclang/CIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CIndex.cpp?rev=311990&r1=311989&r2=311990&view=diff
==
--- cfe/trunk/tools/libclang/CIndex.cpp (original)
+++ cfe/trunk/tools/libclang/CIndex.cpp Tue Aug 29 02:08:02 2017
@@ -3504,6 +3504,12 @@ enum CXErrorCode clang_parseTranslationU
 CIdx, source_filename, command_line_args, num_command_line_args,
 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
   };
+
+  if (getenv("LIBCLANG_NOTHREADS")) {
+ParseTranslationUnitImpl();
+return result;
+  }
+
   llvm::CrashRecoveryContext CRC;
 
   if (!RunSafely(CRC, ParseTranslationUnitImpl)) {


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


[PATCH] D36821: [libclang]: Honor LIBCLANG_NOTHREADS for clang_parseTranslationUnit*

2017-08-29 Thread Erik Verbruggen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311990: [libclang]: Honor LIBCLANG_NOTHREADS for 
clang_parseTranslationUnit* (authored by erikjv).

Changed prior to commit:
  https://reviews.llvm.org/D36821?vs=111472&id=113041#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D36821

Files:
  cfe/trunk/tools/libclang/CIndex.cpp


Index: cfe/trunk/tools/libclang/CIndex.cpp
===
--- cfe/trunk/tools/libclang/CIndex.cpp
+++ cfe/trunk/tools/libclang/CIndex.cpp
@@ -3504,6 +3504,12 @@
 CIdx, source_filename, command_line_args, num_command_line_args,
 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
   };
+
+  if (getenv("LIBCLANG_NOTHREADS")) {
+ParseTranslationUnitImpl();
+return result;
+  }
+
   llvm::CrashRecoveryContext CRC;
 
   if (!RunSafely(CRC, ParseTranslationUnitImpl)) {


Index: cfe/trunk/tools/libclang/CIndex.cpp
===
--- cfe/trunk/tools/libclang/CIndex.cpp
+++ cfe/trunk/tools/libclang/CIndex.cpp
@@ -3504,6 +3504,12 @@
 CIdx, source_filename, command_line_args, num_command_line_args,
 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
   };
+
+  if (getenv("LIBCLANG_NOTHREADS")) {
+ParseTranslationUnitImpl();
+return result;
+  }
+
   llvm::CrashRecoveryContext CRC;
 
   if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37255: [analyzer] Fix bugreporter::getDerefExpr() again - a smaller targeted fix.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
Herald added a subscriber: xazax.hun.

In order to be able to revert the risky refactoring in 
https://reviews.llvm.org/D37023 without bringing back the regression, i made a 
smaller (but uglier) isolated fix for the crash. Then 
https://reviews.llvm.org/D37023 will be applied on top of it.


https://reviews.llvm.org/D37255

Files:
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  test/Analysis/null-deref-path-notes.m

Index: test/Analysis/null-deref-path-notes.m
===
--- test/Analysis/null-deref-path-notes.m
+++ test/Analysis/null-deref-path-notes.m
@@ -50,6 +50,23 @@
   *p = 1; // expected-warning{{Dereference of null pointer}} expected-note{{Dereference of null pointer}}
 }
 
+@interface WithArrayPtr
+- (void) useArray;
+@end
+
+@implementation WithArrayPtr {
+@public int *p;
+}
+- (void)useArray {
+  p[1] = 2; // expected-warning{{Array access (via ivar 'p') results in a null pointer dereference}}
+// expected-note@-1{{Array access (via ivar 'p') results in a null pointer dereference}}
+}
+@end
+
+void testWithArrayPtr(WithArrayPtr *w) {
+  w->p = 0; // expected-note{{Null pointer value stored to 'p'}}
+  [w useArray]; // expected-note{{Calling 'useArray'}}
+}
 
 // CHECK:  diagnostics
 // CHECK-NEXT:  
@@ -801,4 +818,227 @@
 // CHECK-NEXT:file0
 // CHECK-NEXT:   
 // CHECK-NEXT:   
+// CHECK-NEXT:   
+// CHECK-NEXT:path
+// CHECK-NEXT:
+// CHECK-NEXT: 
+// CHECK-NEXT:  kindevent
+// CHECK-NEXT:  location
+// CHECK-NEXT:  
+// CHECK-NEXT:   line67
+// CHECK-NEXT:   col3
+// CHECK-NEXT:   file0
+// CHECK-NEXT:  
+// CHECK-NEXT:  ranges
+// CHECK-NEXT:  
+// CHECK-NEXT:
+// CHECK-NEXT: 
+// CHECK-NEXT:  line67
+// CHECK-NEXT:  col3
+// CHECK-NEXT:  file0
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  line67
+// CHECK-NEXT:  col10
+// CHECK-NEXT:  file0
+// CHECK-NEXT: 
+// CHECK-NEXT:
+// CHECK-NEXT:  
+// CHECK-NEXT:  depth0
+// CHECK-NEXT:  extended_message
+// CHECK-NEXT:  Null pointer value stored to 'p'
+// CHECK-NEXT:  message
+// CHECK-NEXT:  Null pointer value stored to 'p'
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  kindcontrol
+// CHECK-NEXT:  edges
+// CHECK-NEXT:   
+// CHECK-NEXT:
+// CHECK-NEXT: start
+// CHECK-NEXT:  
+// CHECK-NEXT:   
+// CHECK-NEXT:line67
+// CHECK-NEXT:col3
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:   
+// CHECK-NEXT:line67
+// CHECK-NEXT:col3
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:  
+// CHECK-NEXT: end
+// CHECK-NEXT:  
+// CHECK-NEXT:   
+// CHECK-NEXT:line68
+// CHECK-NEXT:col3
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:   
+// CHECK-NEXT:line68
+// CHECK-NEXT:col3
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:  
+// CHECK-NEXT:
+// CHECK-NEXT:   
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  kindevent
+// CHECK-NEXT:  location
+// CHECK-NEXT:  
+// CHECK-NEXT:   line68
+// CHECK-NEXT:   col3
+// CHECK-NEXT:   file0
+// CHECK-NEXT:  
+// CHECK-NEXT:  ranges
+// CHECK-NEXT:  
+// CHECK-NEXT:
+// CHECK-NEXT: 
+// CHECK-NEXT:  line68
+// CHECK-NEXT:  col3
+// CHECK-NEXT:  file0
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  line68
+// CHECK-NEXT:  col14
+// CHECK-NEXT:  file0
+// CHECK-NEXT: 
+// CHECK-NEXT:
+// CHECK-NEXT:  
+// CHECK-NEXT:  depth0
+// CHECK-NEXT:  extended_message
+// CHECK-NEXT:  Calling 'useArray'
+// CHECK-NEXT:  message
+// CHECK-NEXT:  Calling 'useArray'
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  kindevent
+// CHECK-NEXT:  location
+// CHECK-NEXT:  
+// CHECK-NEXT:   line60
+// CHECK-NEXT:   col1
+// CHECK-NEXT:   file0
+// CHECK-NEXT:  
+// CHECK-NEXT:  depth1
+// CHECK-NEXT:  extended_message
+// CHECK-NEXT:  Entered call from 'testWithArrayPtr'
+// CHECK-NEXT:  message
+// CHECK-NEXT:  Entered call from 'testWithArrayPtr'
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  kindcontrol
+// CHECK-NEXT:  edges
+// CHECK-NEXT:   
+// CHECK-NEXT:
+// CHECK-NEXT: start
+// CHECK-NEXT:  
+// CHECK-NEXT:   
+// CHECK-NEXT:line60
+// CHECK-NEXT:col1
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:   
+// CHECK-NEXT:line60
+// CHECK-NEXT:col1
+// CHECK-NEXT: 

r311991 - [modules] Add test for using declaration in classes.

2017-08-29 Thread Raphael Isemann via cfe-commits
Author: teemperor
Date: Tue Aug 29 02:27:41 2017
New Revision: 311991

URL: http://llvm.org/viewvc/llvm-project?rev=311991&view=rev
Log:
[modules] Add test for using declaration in classes.

Summary:
This adds a test that checks if the using declaration in classes still works as 
intended with modules.

The motivation for this is that we tried to add a shortcut to `removeDecl` that 
would skip the removal of declarations from the lookup table if they are 
hidden. This optimization passed the clang test suite but actually broke the 
using declaration in combination with -fmodules-local-submodule-visibility. In 
this mode we hide all decls from other modules such as by chance the parent 
method, in which case don't remove the parent method from the lookup table and 
get ambiguous lookup errors. After this patch we now correctly see if this 
behavior is broken by a patch like this in the test suite.

Reviewers: v.g.vassilev

Reviewed By: v.g.vassilev

Subscribers: cfe-commits

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

Added:
cfe/trunk/test/Modules/using-decl-inheritance.cpp

Added: cfe/trunk/test/Modules/using-decl-inheritance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/using-decl-inheritance.cpp?rev=311991&view=auto
==
--- cfe/trunk/test/Modules/using-decl-inheritance.cpp (added)
+++ cfe/trunk/test/Modules/using-decl-inheritance.cpp Tue Aug 29 02:27:41 2017
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility 
-fmodules-cache-path=%t %s -verify
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify
+
+// expected-no-diagnostics
+
+#pragma clang module build A
+  module A { }
+#pragma clang module contents
+#pragma clang module begin A
+struct A {
+   virtual void Foo(double x) const;
+};
+#pragma clang module end
+#pragma clang module endbuild
+
+#pragma clang module build B
+  module B { }
+#pragma clang module contents
+#pragma clang module begin B
+#pragma clang module import A
+struct B : A {
+   using A::Foo;
+   virtual void Foo(double x) const;
+};
+#pragma clang module end
+#pragma clang module endbuild
+
+#pragma clang module import B
+
+int main() {
+  B b;
+  b.Foo(1.0);
+}
+


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


[PATCH] D37180: [modules] Add test for using declaration in classes.

2017-08-29 Thread Raphael Isemann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311991: [modules] Add test for using declaration in classes. 
(authored by teemperor).

Changed prior to commit:
  https://reviews.llvm.org/D37180?vs=112788&id=113044#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37180

Files:
  cfe/trunk/test/Modules/using-decl-inheritance.cpp


Index: cfe/trunk/test/Modules/using-decl-inheritance.cpp
===
--- cfe/trunk/test/Modules/using-decl-inheritance.cpp
+++ cfe/trunk/test/Modules/using-decl-inheritance.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility 
-fmodules-cache-path=%t %s -verify
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify
+
+// expected-no-diagnostics
+
+#pragma clang module build A
+  module A { }
+#pragma clang module contents
+#pragma clang module begin A
+struct A {
+   virtual void Foo(double x) const;
+};
+#pragma clang module end
+#pragma clang module endbuild
+
+#pragma clang module build B
+  module B { }
+#pragma clang module contents
+#pragma clang module begin B
+#pragma clang module import A
+struct B : A {
+   using A::Foo;
+   virtual void Foo(double x) const;
+};
+#pragma clang module end
+#pragma clang module endbuild
+
+#pragma clang module import B
+
+int main() {
+  B b;
+  b.Foo(1.0);
+}
+


Index: cfe/trunk/test/Modules/using-decl-inheritance.cpp
===
--- cfe/trunk/test/Modules/using-decl-inheritance.cpp
+++ cfe/trunk/test/Modules/using-decl-inheritance.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility -fmodules-cache-path=%t %s -verify
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify
+
+// expected-no-diagnostics
+
+#pragma clang module build A
+  module A { }
+#pragma clang module contents
+#pragma clang module begin A
+struct A {
+   virtual void Foo(double x) const;
+};
+#pragma clang module end
+#pragma clang module endbuild
+
+#pragma clang module build B
+  module B { }
+#pragma clang module contents
+#pragma clang module begin B
+#pragma clang module import A
+struct B : A {
+   using A::Foo;
+   virtual void Foo(double x) const;
+};
+#pragma clang module end
+#pragma clang module endbuild
+
+#pragma clang module import B
+
+int main() {
+  B b;
+  b.Foo(1.0);
+}
+
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37143: [clang-format] Fixed missing enter before bracket in typedef enum and extern

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

Thank you! I prefer this patch to be split in two. I am still not convinced 
about the `extern` part: some clients might prefer the other style.


https://reviews.llvm.org/D37143



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


[PATCH] D37182: [libcxx] Special visibility macros for the experimental library

2017-08-29 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added reviewers: mclow.lists, compnerd.
smeenai resigned from this revision.
smeenai added a comment.

It's really cool that you're getting the filesystem library to work on Windows 
:)

This looks reasonable to me; it's the only way I can think of to get the 
experimental library working on Windows if we're keeping it static. It's a 
large change, but most of it is mechanical. Given its size, however, I also 
want to let at least one of Eric and Marshall take a look.

The other question, of course, is why the experimental library needs to be 
static. If it were built shared, the annotations would just work on Windows in 
theory (though I'm sure there are other issues there).




Comment at: include/experimental/__config:57
 
+#if defined(_LIBCPP_OBJECT_FORMAT_COFF)
+# define _LIBCPPX_TYPE_VIS

I think it would make more sense to make these macros empty on all platforms, 
not just Windows. It's true that they'll only cause link errors on Windows 
(since you'll attempt to dllimport functions from a static library), but on ELF 
and Mach-O, the visibility annotations would cause these functions to be 
exported from whatever library c++experimental gets linked into, which is 
probably not desirable either.

The exception (if you'll pardon the pun) is `_LIBCPPX_EXCEPTION_ABI`, which 
will still need to expand to at least `__type_visibility__((default))` for 
non-COFF in order for throwing and catching those types to work correctly.


https://reviews.llvm.org/D37182



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


[PATCH] D36678: [OpenCL] Do not use vararg in emitted functions for enqueue_kernel

2017-08-29 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: test/CodeGenOpenCL/cl20-device-side-enqueue.cl:116
+  // B32: store i32 4, i32* %[[TMP3]], align 4
+  // B32: call i32 @__enqueue_kernel_vaargs(%opencl.queue_t{{.*}}* [[DEF_Q]], 
i32 [[FLAGS]], %struct.ndrange_t* [[NDR]]{{(.[0-9]+)?}}, i8 addrspace(4)* 
addrspacecast (i8 addrspace(1)* bitcast ({ i8**, i32, i32, i8*, 
%struct.__block_descriptor addrspace(2)* } addrspace(1)* 
@__block_literal_global{{(.[0-9]+)?}} to i8 addrspace(1)*) to i8 
addrspace(4)*), i32 3, i32* %[[TMP1]])
+  // B64: %[[TMP:.*]] = alloca [3 x i64]

yaxunl wrote:
> Anastasia wrote:
> > You are not checking the arrays in the other calls too?
> The logic is the same and the same lamba is called for emitting the IR. Is it 
> necessary to do the same check for all the cases?
Ideally yes, we are doing this for other features too... there is only one 
element in other cases... should be easier.


https://reviews.llvm.org/D36678



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


[PATCH] D37150: [clangd] Command line arg to specify compile_commands.json path

2017-08-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

BTW, if you're only looking for providing extra compilation flags for some 
files, you could use an extension to LSP that is already in clangd source tree. 
(See tests from https://reviews.llvm.org/D34947 for more details).
But your change is also useful, as it allows to override the whole compilation 
database. Would be interested in this change to land regardless of whether the 
extra flags thing suits you well.


https://reviews.llvm.org/D37150



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


[PATCH] D37231: Add half load and store builtins

2017-08-29 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: include/clang/Basic/Builtins.def:1427
+// OpenCL half load/store builtin
+BUILTIN(__builtin_store_half, "vdh*", "n")
+BUILTIN(__builtin_store_halff, "vfh*", "n")

I think this should be a language builtin (see above) but perhaps we might need 
to extend the language version here. Because I believe we only have OpenCL v2.0 
currently.

Also this should only be available if `cl_khr_fp16` is supported and enabled? I 
think we are doing similar with some subgroups functions (e.g. 
`get_kernel_sub_group_count_for_ndrange`) that are only supported by 
`cl_khr_subgroup` but those have custom diagnostic though. May be we could 
leave this check out since `half` is not available if `cl_khr_fp16` is not 
enabled anyways.



Comment at: test/CodeGenOpenCL/no-half.cl:3
+
+#pragma OPENCL EXTENSION cl_khr_fp64:enable
+

It seems strange that `cl_khr_fp16` is not enabled too.


Repository:
  rL LLVM

https://reviews.llvm.org/D37231



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


[PATCH] D36410: [OpenCL] Handle taking address of block captures

2017-08-29 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Ok, I will update it to be implicitly generic then. Just to be sure, @bader do 
you agree on this too?


https://reviews.llvm.org/D36410



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


[PATCH] D37260: [clang-format] Fixed extern C brace wrapping

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee created this revision.
Herald added a subscriber: klimek.

Bug: https://bugs.llvm.org/show_bug.cgi?id=34016 - **"extern C part"**

**Problem:**

Due to the lack of "brace wrapping extern" flag, clang format does parse the 
block after **extern** keyword moving the opening bracket to the header line 
**always**!

**Patch description:**

Added if statement handling the case when our **"extern block"** has the 
opening bracket in "non-header" line. Then forcing break before bracket.

**After fix:**

**CONFIG:**

  BreakBeforeBraces: Custom
  BraceWrapping: { 
  AfterClass: true, AfterControlStatement: true, AfterEnum: true, 
AfterFunction: true, AfterNamespace: false, AfterStruct: true, AfterUnion: 
true, BeforeCatch: true, BeforeElse: true 
  }

**BEFORE:**

  extern "C" 
  {
  #include 
  }

**AFTER:**

  extern "C" 
  {
  #include 
  }

**Remains the same!**

There is no brace wrapping flag that let us control opening brace's position. 
In case of other keywords (class, function, control statement etc.) we have 
opportunity to decide how should it look like. Here, we can't do it similarly. 
What we want is leaving braces **unformatted** (leave them as in the input), 
but what's more we still want to call **parseBlock** function. The only option 
is to set **MustBreakBefore** flag manually (only when needed, when the left 
brace is on non-header line, parseBlock does move it by default).


https://reviews.llvm.org/D37260

Files:
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1595,7 +1595,24 @@
Style));
 }
 
-TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
+TEST_F(FormatTest, FormatsExternC) { 
+  verifyFormat("extern \"C\" {\nint a;");
+  verifyFormat("extern \"C\" {};");
+  EXPECT_EQ("extern \"C\" {\n"
+"int i = 42;\n"
+"}",
+format("extern \"C\" {\n"
+   "int i = 42;\n"
+   "}"));
+  EXPECT_EQ("extern \"C\"\n" 
+"{\n"
+"int i = 42;\n"
+"}",
+format("extern \"C\"\n" 
+   "{\n"
+   "int i = 42;\n"
+   "}"));
+}
 
 TEST_F(FormatTest, FormatsInlineASM) {
   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -986,6 +986,8 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+if (isOnNewLine(*FormatTok))
+  FormatTok->MustBreakBefore = true;
 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
 addUnwrappedLine();
 return;


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1595,7 +1595,24 @@
Style));
 }
 
-TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
+TEST_F(FormatTest, FormatsExternC) { 
+  verifyFormat("extern \"C\" {\nint a;");
+  verifyFormat("extern \"C\" {};");
+  EXPECT_EQ("extern \"C\" {\n"
+"int i = 42;\n"
+"}",
+format("extern \"C\" {\n"
+   "int i = 42;\n"
+   "}"));
+  EXPECT_EQ("extern \"C\"\n" 
+"{\n"
+"int i = 42;\n"
+"}",
+format("extern \"C\"\n" 
+   "{\n"
+   "int i = 42;\n"
+   "}"));
+}
 
 TEST_F(FormatTest, FormatsInlineASM) {
   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -986,6 +986,8 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+if (isOnNewLine(*FormatTok))
+  FormatTok->MustBreakBefore = true;
 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
 addUnwrappedLine();
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee updated this revision to Diff 113062.
PriMee added a comment.

Done. 
**Extern C** part moved to: https://reviews.llvm.org/D37260


https://reviews.llvm.org/D37143

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 
Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) 
||
(Line.startsWith(tok::kw_struct) && 
Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
(Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2017-08-29 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel marked 4 inline comments as done.
koldaniel added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:597-598
+
+  if(!BR.getContext().getLangOpts().C11)
+return;
+

NoQ wrote:
> Note that you cannot easily figure out if the code is intended to get 
> compiled only under C11 and above - maybe it's accidentally compiled under 
> C11 for this user, but is otherwise intended to keep working under older 
> standards.
It is a possible scenario, how should I check if the checks should warn (safe 
functions are available) if not by using this method?



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:670-675
+  auto FormatString =
+dyn_cast(CE->getArg(ArgIndex)->IgnoreParenImpCasts());
+  if(FormatString &&
+ FormatString->getString().find("%s") == StringRef::npos &&
+ FormatString->getString().find("%[") == StringRef::npos)
+return;

NoQ wrote:
> You'd probably also want to quit early if the format string is not a literal.
If the format string is not a literal (i.e. a variable), currently we cannot 
determine if there were any restrictions regarding the size or not, so we want 
this check to warn.


Repository:
  rL LLVM

https://reviews.llvm.org/D35068



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


[PATCH] D37182: [libcxx] Special visibility macros for the experimental library

2017-08-29 Thread Hamza Sood via Phabricator via cfe-commits
hamzasood added a comment.

In https://reviews.llvm.org/D37182#855262, @smeenai wrote:

> The other question, of course, is why the experimental library needs to be 
> static. If it were built shared, the annotations would just work on Windows 
> in theory (though I'm sure there are other issues there).


Even if libc++experimental is no longer forced to be static, it'd probably be 
too restrictive to force libc++ and libc++experimental to be the same library 
type. E.g. someone might want a dynamic libc++ but a static libc++experimental. 
If that's possible (even if not by default), different visibility macros will 
be needed.




Comment at: include/experimental/__config:57
 
+#if defined(_LIBCPP_OBJECT_FORMAT_COFF)
+# define _LIBCPPX_TYPE_VIS

smeenai wrote:
> I think it would make more sense to make these macros empty on all platforms, 
> not just Windows. It's true that they'll only cause link errors on Windows 
> (since you'll attempt to dllimport functions from a static library), but on 
> ELF and Mach-O, the visibility annotations would cause these functions to be 
> exported from whatever library c++experimental gets linked into, which is 
> probably not desirable either.
> 
> The exception (if you'll pardon the pun) is `_LIBCPPX_EXCEPTION_ABI`, which 
> will still need to expand to at least `__type_visibility__((default))` for 
> non-COFF in order for throwing and catching those types to work correctly.
I might be mistaken, but I think the regular libc++ library still uses 
visibility annotations when it's being built as a static library on non-Windows 
platforms. So I figured it'd be best to match that behaviour.


https://reviews.llvm.org/D37182



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


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Looks good. Thank you.


https://reviews.llvm.org/D37143



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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added a comment.

Are you changing the line endings here? Phabricator tells me that basically all 
the lines change. If so, please don't ;).




Comment at: lib/Format/TokenAnnotator.cpp:345
+
+FormatToken *PreviousNoneOfConstVolatileReference = Parent;
+while (PreviousNoneOfConstVolatileReference &&

I'd prefer to move this into a separate function or a lambda, i.e.:

  bool isCppStructuredBinding(const FormatToken *Tok) {
if (!Style.isCpp() || !Tok->is(tok::l_square))
  return false;
while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp, 
tok::ampamp))
  Tok = Tok->getPreviousNonComment()) {
return Tok && Tok->is(tok::kw_auto);
  }


https://reviews.llvm.org/D37132



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


[PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2017-08-29 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel updated this revision to Diff 113065.
koldaniel added a comment.

Updated checker name, minor modifications


https://reviews.llvm.org/D35068

Files:
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp


Index: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
===
--- lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -100,7 +100,7 @@
   void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
-  void checkUnsafeBufferHandling(const CallExpr *CE, const FunctionDecl *FD);
+  void checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE, const 
FunctionDecl *FD);
   void checkDeprecatedBufferHandling(const CallExpr *CE, const FunctionDecl 
*FD);
   void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
@@ -144,20 +144,20 @@
 .Case("mkstemps", &WalkAST::checkCall_mkstemp)
 .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
 .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
-.Case("sprintf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vsprintf", &WalkAST::checkUnsafeBufferHandling)
-.Case("scanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("wscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("fscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("fwscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vwscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vfscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vfwscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("sscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("swscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vsscanf", &WalkAST::checkUnsafeBufferHandling)
-.Case("vswscanf", &WalkAST::checkUnsafeBufferHandling)
+.Case("sprintf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vsprintf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("scanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("wscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("fscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("fwscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vwscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vfscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vfwscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("sscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("swscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vsscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vswscanf", &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
 .Case("swprintf", &WalkAST::checkDeprecatedBufferHandling)
 .Case("snprintf", &WalkAST::checkDeprecatedBufferHandling)
 .Case("vswprintf", &WalkAST::checkDeprecatedBufferHandling)
@@ -604,7 +604,7 @@
   llvm::raw_svector_ostream out2(buf2);
   out1 << "Potential insecure memory buffer bounds restriction in call '"
<< Name << "'";
-  out2 << "Using '" << Name << "' is depracated as it does not "
+  out2 << "Using '" << Name << "' is deprecated as it does not "
  "provide bounding of the memory buffer or security "
  "checks introduced in the C11 standard. Replace "
  "with analogous functions introduced in C11 standard that 
"
@@ -619,6 +619,7 @@
  out2.str(),
  CELoc, CE->getCallee()->getSourceRange());
 }
+
 
//===--===//
 // Check: Use of 'sprintf', 'vsprintf', 'scanf', 'wscanf', 'fscanf',
 //'fwscanf', 'vscanf', 'vwscanf', 'vfscanf', 'vfwscanf', 'sscanf',
@@ -628,8 +629,7 @@
 // CWE-119: Improper Restriction of Operations within
 // the Bounds of a Memory Buffer
 
//===--===//
-
-void WalkAST::checkUnsafeBufferHandling(const CallExpr *CE, const FunctionDecl 
*FD) { //TODO:TESTS
+void WalkAST::checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE, const 
FunctionDecl *FD) {
   if (!filter.check_UnsafeBufferHandling)
 return;
   checkDeprecatedBufferHandling(CE, FD);


Index: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
===
--- lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -100,7 +100,7 @@
   void checkCall_mkstemp(const CallExpr *CE, cons

[PATCH] D37136: [clang-format] Do not format likely xml

2017-08-29 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Just a few minor comments, otherwise looks good.




Comment at: lib/Format/Format.cpp:1542
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");

Rename to isLikelyXml.



Comment at: lib/Format/Format.cpp:1552
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&

Just add a separate if statement. Or merge with previous one, but I think three 
separate if statements is actually easiest to read.



Comment at: lib/Format/Format.cpp:1902
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))

Same here.


https://reviews.llvm.org/D37136



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


[PATCH] D37200: [AST] Traverse CXXOperatorCallExpr in LexicallyOrderedRecursiveASTVisitor

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

Lgtm with two requests below




Comment at: include/clang/AST/RecursiveASTVisitor.h:354
+protected:
+  bool TraverseStmtBase(Stmt *S, DataRecursionQueue *Queue) {
+return TRAVERSE_STMT_BASE(Stmt, Stmt, S, Queue);

I don't think you need this function now 



Comment at: include/clang/AST/RecursiveASTVisitor.h:2089
   }
-
 DEF_TRAVERSE_STMT(GCCAsmStmt, {

Please avoid deleting this line


https://reviews.llvm.org/D37200



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


[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: include/clang/Tooling/ASTDiff/ASTPatch.h:1
+//===- ASTDiff.h - Structural patching based on ASTDiff ---*- C++ -*- 
-===//
+//

Please update the file name in the comment



Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:656
+  if (N.ASTNode.get())
+Range = TemplateArgumentLocations.at(&N - &Nodes[0]);
+  else {

You might as well return early here and avoid else entirely 


https://reviews.llvm.org/D37005



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


[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:73
 public:
+  /// Empty (invalid) SyntaxTree.
+  SyntaxTree();

Why do you need to create an empty tree? What about using llvm::Optional 
instead?



Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:82
+  SyntaxTree(SyntaxTree &&Other);
+  SyntaxTree &operator=(SyntaxTree &&Other);
+  explicit SyntaxTree(const SyntaxTree &Other);

It's fine to have = default in the header


https://reviews.llvm.org/D37005



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


[PATCH] D36410: [OpenCL] Handle taking address of block captures

2017-08-29 Thread Alexey Bader via Phabricator via cfe-commits
bader added a comment.

In https://reviews.llvm.org/D36410#855282, @Anastasia wrote:

> Ok, I will update it to be implicitly generic then. Just to be sure, @bader 
> do you agree on this too?




> An alternative approached could be (in case we want to allow this code) to 
> **assume captures are located in the generic AS implicitly**. However, in 
> this case programmers should be advised that erroneous AS casts can occur 
> further that can't be diagnosed by the frontend (i.e. if capture address is 
> used further in the operations of a different address space to where the 
> captures physical location is).

I don't have a strong opinion on this topic, but I'm worried about relying on 
implicit assumptions, which might make code less portable.

How the alternative approach is this suppose to work for enqueue_kernel? Do we 
assume that the captured variables passed by generic pointer and compiler will 
assign the correct address space based on the explicit casts in the block?
There are some restrictions on kernel parameters: 6.9.a. Arguments to kernel 
functions declared in a program that are pointers must be declared with the 
global, constant or local qualifier.

> I feel forbidding user taking address of captured variable is too restrictive 
> and make blocks less useful.

I have no information how widely blocks are used by the OpenCL community and 
how important this feature is.


https://reviews.llvm.org/D36410



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


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee added a comment.

I am glad to hear that. Would be great if someone could commit it. Thank You :)


https://reviews.llvm.org/D37143



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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113073.
curdeius added a comment.

Fix line endings.


https://reviews.llvm.org/D37132

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -30,11 +30,7 @@
 
 class FormatTest : public ::testing::Test {
 protected:
-  enum StatusCheck {
-SC_ExpectComplete,
-SC_ExpectIncomplete,
-SC_DoNotCheck
-  };
+  enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
 
   std::string format(llvm::StringRef Code,
  const FormatStyle &Style = getLLVMStyle(),
@@ -280,7 +276,8 @@
 format("namespace {\n"
"int i;\n"
"\n"
-   "}", LLVMWithNoNamespaceFix));
+   "}",
+   LLVMWithNoNamespaceFix));
   EXPECT_EQ("namespace {\n"
 "int i;\n"
 "}",
@@ -961,20 +958,26 @@
"#endif\n"
"}",
Style));
-  EXPECT_EQ("switch (a) {\n" "case 0:\n"
-"  return; // long long long long long long long long long long long long comment\n"
-"  // line\n" "}",
+  EXPECT_EQ("switch (a) {\n"
+"case 0:\n"
+"  return; // long long long long long long long long long long "
+"long long comment\n"
+"  // line\n"
+"}",
 format("switch (a) {\n"
-   "case 0: return; // long long long long long long long long long long long long comment line\n"
+   "case 0: return; // long long long long long long long long "
+   "long long long long comment line\n"
"}",
Style));
   EXPECT_EQ("switch (a) {\n"
 "case 0:\n"
-"  return; /* long long long long long long long long long long long long comment\n"
+"  return; /* long long long long long long long long long long "
+"long long comment\n"
 " line */\n"
 "}",
 format("switch (a) {\n"
-   "case 0: return; /* long long long long long long long long long long long long comment line */\n"
+   "case 0: return; /* long long long long long long long long "
+   "long long long long comment line */\n"
"}",
Style));
   verifyFormat("switch (a) {\n"
@@ -1395,8 +1398,7 @@
   // This code is more common than we thought; if we
   // layout this correctly the semicolon will go into
   // its own line, which is undesirable.
-  verifyFormat("namespace {};",
-   LLVMWithNoNamespaceFix);
+  verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
   verifyFormat("namespace {\n"
"class A {};\n"
"};",
@@ -1465,8 +1467,8 @@
   Style.CompactNamespaces = true;
 
   verifyFormat("namespace A { namespace B {\n"
-			   "}} // namespace A::B",
-			   Style);
+   "}} // namespace A::B",
+   Style);
 
   EXPECT_EQ("namespace out { namespace in {\n"
 "}} // namespace out::in",
@@ -2332,7 +2334,8 @@
"\\\n"
"  public: \\\n"
"void baz(); \\\n"
-   "  };", DontAlign));
+   "  };",
+   DontAlign));
 }
 
 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
@@ -2614,16 +2617,19 @@
   Style.MacroBlockEnd = "^[A-Z_]+_END$";
   verifyFormat("FOO_BEGIN\n"
"  FOO_ENTRY\n"
-   "FOO_END", Style);
+   "FOO_END",
+   Style);
   verifyFormat("FOO_BEGIN\n"
"  NESTED_FOO_BEGIN\n"
"NESTED_FOO_ENTRY\n"
"  NESTED_FOO_END\n"
-   "FOO_END", Style);
+   "FOO_END",
+   Style);
   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
"  int x;\n"
"  x = 1;\n"
-   "FOO_END(Baz)", Style);
+   "FOO_END(Baz)",
+   Style);
 }
 
 //===--===//
@@ -3101,22 +3107,22 @@
   verifyFormat(
   "SomeClass::Constructor() :\n"
   "a(aa), aaa() {}",
-	  Style);
+  Style);
 
   verifyFormat(
   "SomeClass::Constructor() :\n"
   "a(aa), a(aa),\n"
   "a(aa) {}",
-	  Style);
+  Style);
   verifyFormat(
   "SomeClass::Constructor() :\n"
   "aa(aa),\n"
   "aaa() {}",
-	  Style);
+  Style);
   verifyFormat("Constructor(a

[PATCH] D36998: [AST] Traverse templates in LexicallyOrderedRecursiveASTVisitor

2017-08-29 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes added a comment.

This is currently broken, if a user provides a TraverseClassTemplateDecl, then 
the same method in this class will not be called, I think I will add a flag 
(probably not user visible) in RecursiveASTVisitor.h to switch the order for 
templates


https://reviews.llvm.org/D36998



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


[PATCH] D37140: [clang-format] Fixed one-line if statement

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee updated this revision to Diff 113074.
PriMee added a comment.

Unit tests added.


https://reviews.llvm.org/D37140

Files:
  lib/Format/UnwrappedLineFormatter.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -486,9 +486,9 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
-  verifyFormat("if (true) {\n"
+  verifyFormat("if (true) {\n" 
"  f();\n"
-   "} else {\n"
+   "} else {\n" 
"  f();\n"
"}",
AllowSimpleBracedStatements);
@@ -498,7 +498,67 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
-  verifyFormat("for (;;) {\n"
+  verifyFormat("for (;;) {\n" 
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+
+  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true;
+  AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
+  AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
+  AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = true;
+
+  verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("while (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
+  verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n" 
+   "{ //\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n" 
+   "{\n"
+   "  f();\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n"
+   "{\n"
+   "  f();\n"
+   "} else\n" 
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+
+  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
+  verifyFormat("if (true)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n" 
+   "{\n"
+   "  f();\n"
+   "} else\n" 
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+
+  AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
+  verifyFormat("while (true)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("for (;;)\n" 
+   "{\n"
"  f();\n"
"}",
AllowSimpleBracedStatements);
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -283,13 +283,28 @@
 TheLine->First != TheLine->Last) {
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 }
+if (TheLine->Last->is(tok::l_brace) &&
+TheLine->First != TheLine->Last &&
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 
+  return Style.AllowShortBlocksOnASingleLine ? tryMergeSimpleBlock(I, E, Limit) : 0;
+}
+if (I[1]->First->is(tok::l_brace) && 
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 
+  return Style.BraceWrapping.AfterControlStatement ? tryMergeSimpleBlock(I, E, Limit) : 0;
+}
+if (TheLine->First->is(tok::l_brace) &&
+   (TheLine->First == TheLine->Last) &&
+   (I != AnnotatedLines.begin()) &&
+   (I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for))) { 
+  return Style.AllowShortBlocksOnASingleLine ? tryMergeSimpleBlock(I-1, E, Limit) : 0;
+}
 if (TheLine->Last->is(tok::l_brace)) {
   return !Style.BraceWrapping.AfterFunction
  ? tryMergeSimpleBlock(I, E, Limit)
  : 0;
 }
 if (I[1]->First->is(TT_FunctionLBrace) &&
-Style.BraceWrapping.AfterFunction) {
+Style.BraceWrapping.AfterFunction) { 
   if (I[1]->Last->is(TT_LineComment))
 return 0;
 
@@ -426,7 +441,7 @@
   SmallVectorImpl::const_iterator E,
   unsigned Limit) {
 AnnotatedLine &Line = **I;
-
+
 // Don't merge ObjC @ keywords and methods.
 // FIXME: If an option to allow short exception handli

[PATCH] D37231: Add half load and store builtins

2017-08-29 Thread Jan Vesely via Phabricator via cfe-commits
jvesely added inline comments.



Comment at: include/clang/Basic/Builtins.def:1427
+// OpenCL half load/store builtin
+BUILTIN(__builtin_store_half, "vdh*", "n")
+BUILTIN(__builtin_store_halff, "vfh*", "n")

Anastasia wrote:
> I think this should be a language builtin (see above) but perhaps we might 
> need to extend the language version here. Because I believe we only have 
> OpenCL v2.0 currently.
> 
> Also this should only be available if `cl_khr_fp16` is supported and enabled? 
> I think we are doing similar with some subgroups functions (e.g. 
> `get_kernel_sub_group_count_for_ndrange`) that are only supported by 
> `cl_khr_subgroup` but those have custom diagnostic though. May be we could 
> leave this check out since `half` is not available if `cl_khr_fp16` is not 
> enabled anyways.
This is specifically meant to be used when `cl_khr_fp16` is **not** available.
CLC allows using half as storage format and  half pointers without the 
extension,
vstore_half/vload_half are used to load/store half values. (CL1.2 CH 6.1.1.1)

These builtins are not necessary if `cl_khr_fp16` is available (we can use 
regular loads/stores).

I'll take stab at making these CLC only, but similarly to device specific 
builtins it looked useful beyond that, since these builtins provide access to 
half type storage.


Repository:
  rL LLVM

https://reviews.llvm.org/D37231



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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113077.
curdeius added a comment.

Fix line endings again.


https://reviews.llvm.org/D37132

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11217,6 +11217,31 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto & [a, b, c] = f();",
+format("auto   &[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto && [a, b, c] = f();",
+format("auto   &&[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile && [a, b] = f();",
+format("auto  const  volatile  &&[a, b] = f();"));
+  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+
+  format::FormatStyle Spaces = format::getLLVMStyle();
+  Spaces.SpacesInSquareBrackets = true;
+  verifyFormat("auto [ a, b ] = f();", Spaces);
+  verifyFormat("auto && [ a, b ] = f();", Spaces);
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -47,7 +47,7 @@
 if (NonTemplateLess.count(CurrentToken->Previous))
   return false;
 
-const FormatToken& Previous = *CurrentToken->Previous;
+const FormatToken &Previous = *CurrentToken->Previous;
 if (Previous.Previous) {
   if (Previous.Previous->Tok.isLiteral())
 return false;
@@ -152,11 +152,11 @@
   // export type X = (...);
   Contexts.back().IsExpression = false;
 } else if (Left->Previous &&
-(Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
- tok::kw_if, tok::kw_while, tok::l_paren,
- tok::comma) ||
- Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
- Left->Previous->is(TT_BinaryOperator))) {
+   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
+tok::kw_if, tok::kw_while, tok::l_paren,
+tok::comma) ||
+Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
+Left->Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
   Contexts.back().IsExpression = true;
 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
@@ -325,8 +325,7 @@
 // In C++, this can happen either in array of templates (foo[10])
 // or when array is a nested template type (unique_ptr[]>).
 bool CppArrayTemplates =
-Style.isCpp() && Parent &&
-Parent->is(TT_TemplateCloser) &&
+Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
  Contexts.back().InTemplateArgument);
 
@@ -342,9 +341,22 @@
  getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
 bool ColonFound = false;
 
+FormatToken *PreviousNoneOfConstVolatileReference = Parent;
+while (PreviousNoneOfConstVolatileReference &&
+   PreviousNoneOfConstVolatileReference->isOneOf(
+   tok::kw_const, tok::kw_volatile, tok::amp, tok::ampamp))
+  PreviousNoneOfConstVolatileReference =
+  PreviousNoneOfConstVolatileReference->getPreviousNonComment();
+
+bool CppStructuredBindings =
+Style.isCpp() && PreviousNoneOfConstVolatileReference &&
+PreviousNoneOfConstVolatileReference->is(tok::kw_auto);
+
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (CppStructuredBindings) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -605,7 +617,8 @@
   break;
 case tok::kw_if:
 case tok::kw_while:
-  if (Tok->is(tok::kw_if) && 

[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes updated this revision to Diff 113078.
johannes added a comment.

fixes


https://reviews.llvm.org/D37005

Files:
  include/clang/Tooling/ASTDiff/ASTDiff.h
  include/clang/Tooling/ASTDiff/ASTPatch.h
  lib/Tooling/ASTDiff/ASTDiff.cpp
  lib/Tooling/ASTDiff/ASTPatch.cpp
  lib/Tooling/ASTDiff/CMakeLists.txt
  test/Tooling/clang-diff-patch.test
  tools/clang-diff/CMakeLists.txt
  tools/clang-diff/ClangDiff.cpp
  unittests/Tooling/ASTDiffTest.cpp
  unittests/Tooling/CMakeLists.txt

Index: unittests/Tooling/CMakeLists.txt
===
--- unittests/Tooling/CMakeLists.txt
+++ unittests/Tooling/CMakeLists.txt
@@ -11,6 +11,7 @@
 endif()
 
 add_clang_unittest(ToolingTests
+  ASTDiffTest.cpp
   ASTSelectionTest.cpp
   CastExprTest.cpp
   CommentHandlerTest.cpp
@@ -43,4 +44,5 @@
   clangTooling
   clangToolingCore
   clangToolingRefactor
+  clangToolingASTDiff
   )
Index: unittests/Tooling/ASTDiffTest.cpp
===
--- /dev/null
+++ unittests/Tooling/ASTDiffTest.cpp
@@ -0,0 +1,85 @@
+//===- unittest/Tooling/ASTDiffTest.cpp ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Tooling/ASTDiff/ASTDiff.h"
+#include "clang/Tooling/ASTDiff/ASTPatch.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace tooling;
+
+static std::string patchResult(std::array Codes) {
+  llvm::Optional Trees[3];
+  std::unique_ptr ASTs[3];
+  for (int I = 0; I < 3; I++) {
+ASTs[I] = buildASTFromCode(Codes[I]);
+if (!ASTs[I]) {
+  llvm::errs() << "Failed to build AST from code:\n" << Codes[I] << "\n";
+  return "";
+}
+Trees[I].emplace(*ASTs[I]);
+  }
+
+  diff::ComparisonOptions Options;
+  std::string TargetDstCode;
+  llvm::raw_string_ostream OS(TargetDstCode);
+  if (!diff::patch(/*ModelSrc=*/*Trees[0], /*ModelDst=*/*Trees[1],
+   /*TargetSrc=*/*Trees[2], Options, OS))
+return "";
+  return OS.str();
+}
+
+// abstract the EXPECT_EQ call so that the code snippets align properly
+// use macros for this to make test failures have proper line numbers
+#define PATCH(Preamble, ModelSrc, ModelDst, Target, Expected)  \
+  EXPECT_EQ(patchResult({{std::string(Preamble) + ModelSrc,\
+  std::string(Preamble) + ModelDst,\
+  std::string(Preamble) + Target}}),   \
+std::string(Preamble) + Expected)
+
+TEST(ASTDiff, TestDeleteArguments) {
+  PATCH(R"(void printf(const char *, ...);)",
+R"(void foo(int x) { printf("%d", x, x); })",
+R"(void foo(int x) { printf("%d", x); })",
+R"(void foo(int x) { printf("different string %d", x, x); })",
+R"(void foo(int x) { printf("different string %d", x); })");
+
+  PATCH(R"(void foo(...);)",
+R"(void test1() { foo ( 1 + 1); })",
+R"(void test1() { foo ( ); })",
+R"(void test2() { foo ( 1 + 1 ); })",
+R"(void test2() { foo (  ); })");
+
+  PATCH(R"(void foo(...);)",
+R"(void test1() { foo (1, 2 + 2); })",
+R"(void test1() { foo (2 + 2); })",
+R"(void test2() { foo (/*L*/ 0 /*R*/ , 2 + 2); })",
+R"(void test2() { foo (/*L*/  2 + 2); })");
+
+  PATCH(R"(void foo(...);)",
+R"(void test1() { foo (1, 2); })",
+R"(void test1() { foo (1); })",
+R"(void test2() { foo (0, /*L*/ 0 /*R*/); })",
+R"(void test2() { foo (0 /*R*/); })");
+}
+
+TEST(ASTDiff, TestDeleteDecls) {
+  PATCH(R"()",
+R"()",
+R"()",
+R"()",
+R"()");
+
+  PATCH(R"()",
+R"(void foo(){})",
+R"()",
+R"(int x; void foo() {;;} int y;)",
+R"(int x;  int y;)");
+}
Index: tools/clang-diff/ClangDiff.cpp
===
--- tools/clang-diff/ClangDiff.cpp
+++ tools/clang-diff/ClangDiff.cpp
@@ -13,6 +13,7 @@
 //===--===//
 
 #include "clang/Tooling/ASTDiff/ASTDiff.h"
+#include "clang/Tooling/ASTDiff/ASTPatch.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
@@ -42,6 +43,12 @@
   cl::desc("Output a side-by-side diff in HTML."),
   cl::init(false), cl::cat(ClangDiffCategory));
 
+static cl::opt
+Patch("patch",
+  cl::desc("Try to apply the edit actions between the two input "
+   "files to the specified target."),
+  cl::desc(""), cl::cat(ClangDiffCategory));
+
 static cl::opt SourcePath(cl::P

[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes added inline comments.



Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:73
 public:
+  /// Empty (invalid) SyntaxTree.
+  SyntaxTree();

arphaman wrote:
> Why do you need to create an empty tree? What about using llvm::Optional 
> instead?
ok, i use optional now instead in the unittest


https://reviews.llvm.org/D37005



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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113079.
curdeius added a comment.

Extract method.


https://reviews.llvm.org/D37132

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11217,6 +11217,31 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto & [a, b, c] = f();",
+format("auto   &[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto && [a, b, c] = f();",
+format("auto   &&[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile && [a, b] = f();",
+format("auto  const  volatile  &&[a, b] = f();"));
+  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+
+  format::FormatStyle Spaces = format::getLLVMStyle();
+  Spaces.SpacesInSquareBrackets = true;
+  verifyFormat("auto [ a, b ] = f();", Spaces);
+  verifyFormat("auto && [ a, b ] = f();", Spaces);
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -310,6 +310,16 @@
 return false;
   }
 
+  bool isCppStructuredBinding(const FormatToken *Tok) {
+if (!Style.isCpp() || !Tok->is(tok::l_square))
+  return false;
+while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
+   tok::ampamp)) {
+  Tok = Tok->getPreviousNonComment();
+}
+return Tok && Tok->is(tok::kw_auto);
+  }
+
   bool parseSquare() {
 if (!CurrentToken)
   return false;
@@ -344,7 +354,9 @@
 
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (isCppStructuredBinding(Left)) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -2256,17 +2268,20 @@
   if (Left.is(tok::l_square))
 return (Left.is(TT_ArrayInitializerLSquare) &&
 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
-   (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
-Right.isNot(tok::r_square));
+   (Left.isOneOf(TT_ArraySubscriptLSquare,
+ TT_StructuredBindingLSquare) &&
+Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
   if (Right.is(tok::r_square))
 return Right.MatchingParen &&
((Style.SpacesInContainerLiterals &&
  Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
 (Style.SpacesInSquareBrackets &&
- Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
+ Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
+  TT_StructuredBindingLSquare)));
   if (Right.is(tok::l_square) &&
   !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_DesignatedInitializerLSquare) &&
+ TT_DesignatedInitializerLSquare,
+ TT_StructuredBindingLSquare) &&
   !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
 return false;
   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
Index: lib/Format/FormatToken.h
===
--- lib/Format/FormatToken.h
+++ lib/Format/FormatToken.h
@@ -84,6 +84,7 @@
   TYPE(RegexLiteral) \
   TYPE(SelectorName) \
   TYPE(StartOfName) \
+  TYPE(StructuredBindingLSquare) \
   TYPE(TemplateCloser) \
   TYPE(TemplateOpener) \
   TYPE(TemplateString) \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r311998 - [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Aug 29 06:32:30 2017
New Revision: 311998

URL: http://llvm.org/viewvc/llvm-project?rev=311998&view=rev
Log:
[clang-format] Fixed typedef enum brace wrapping

Summary:
Bug: https://bugs.llvm.org/show_bug.cgi?id=34016 - **Typedef enum part**

**Problem:**

Clang format does not allow the flag **BraceWrapping.AfterEnum** control the 
case when our **enum** is preceded by **typedef** keyword (what is common in C 
language).

**Patch description:**

Added case to the **"AfterEnum"** flag when our enum does not start a line - is 
preceded by **typedef** keyword.

**After fix:**

**CONFIG:**
```
BreakBeforeBraces: Custom
BraceWrapping: {
AfterClass: true, AfterControlStatement: true, AfterEnum: true, AfterFunction: 
true, AfterNamespace: false, AfterStruct: true, AfterUnion: true, BeforeCatch: 
true, BeforeElse: true
}
```

**BEFORE:**
```
typedef enum
{
a,
b,
c
} SomeEnum;
```

**AFTER:**

```
typedef enum
{
a,
b,
c
} SomeEnum;
```

Contributed by @PriMee!

Reviewers: krasimir, djasper

Reviewed By: djasper

Subscribers: cfe-commits, klimek

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=311998&r1=311997&r2=311998&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Aug 29 06:32:30 2017
@@ -2647,6 +2647,7 @@ bool TokenAnnotator::mustBreakBefore(con
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 
Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) 
||
(Line.startsWith(tok::kw_struct) && 
Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=311998&r1=311997&r2=311998&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Aug 29 06:32:30 2017
@@ -1324,6 +1324,32 @@ TEST_F(FormatTest, FormatsEnumTypes) {
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"


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


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311998: [clang-format] Fixed typedef enum brace wrapping 
(authored by krasimir).

Changed prior to commit:
  https://reviews.llvm.org/D37143?vs=113062&id=113081#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37143

Files:
  cfe/trunk/lib/Format/TokenAnnotator.cpp
  cfe/trunk/unittests/Format/FormatTest.cpp


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 
Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) 
||
(Line.startsWith(tok::kw_struct) && 
Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
(Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee added a comment.

Could you change the "Contributed by" section? Wrong account is assigned. Full 
name would be more satisfying. Thank You in advance :)


Repository:
  rL LLVM

https://reviews.llvm.org/D37143



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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113084.
curdeius added a comment.

Fix: use do-while loop.


https://reviews.llvm.org/D37132

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11217,6 +11217,31 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto & [a, b, c] = f();",
+format("auto   &[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto && [a, b, c] = f();",
+format("auto   &&[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile && [a, b] = f();",
+format("auto  const  volatile  &&[a, b] = f();"));
+  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+
+  format::FormatStyle Spaces = format::getLLVMStyle();
+  Spaces.SpacesInSquareBrackets = true;
+  verifyFormat("auto [ a, b ] = f();", Spaces);
+  verifyFormat("auto && [ a, b ] = f();", Spaces);
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -310,6 +310,16 @@
 return false;
   }
 
+  bool isCppStructuredBinding(const FormatToken *Tok) {
+if (!Style.isCpp() || !Tok->is(tok::l_square))
+  return false;
+do {
+  Tok = Tok->getPreviousNonComment();
+} while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
+ tok::ampamp));
+return Tok && Tok->is(tok::kw_auto);
+  }
+
   bool parseSquare() {
 if (!CurrentToken)
   return false;
@@ -344,7 +354,9 @@
 
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (isCppStructuredBinding(Left)) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -2256,17 +2268,20 @@
   if (Left.is(tok::l_square))
 return (Left.is(TT_ArrayInitializerLSquare) &&
 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
-   (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
-Right.isNot(tok::r_square));
+   (Left.isOneOf(TT_ArraySubscriptLSquare,
+ TT_StructuredBindingLSquare) &&
+Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
   if (Right.is(tok::r_square))
 return Right.MatchingParen &&
((Style.SpacesInContainerLiterals &&
  Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
 (Style.SpacesInSquareBrackets &&
- Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
+ Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
+  TT_StructuredBindingLSquare)));
   if (Right.is(tok::l_square) &&
   !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_DesignatedInitializerLSquare) &&
+ TT_DesignatedInitializerLSquare,
+ TT_StructuredBindingLSquare) &&
   !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
 return false;
   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
Index: lib/Format/FormatToken.h
===
--- lib/Format/FormatToken.h
+++ lib/Format/FormatToken.h
@@ -84,6 +84,7 @@
   TYPE(RegexLiteral) \
   TYPE(SelectorName) \
   TYPE(StartOfName) \
+  TYPE(StructuredBindingLSquare) \
   TYPE(TemplateCloser) \
   TYPE(TemplateOpener) \
   TYPE(TemplateString) \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37136: [clang-format] Do not format likely xml

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 113085.
krasimir marked 3 inline comments as done.
krasimir added a comment.

- Address review comments


https://reviews.llvm.org/D37136

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


Index: unittests/Format/SortIncludesTest.cpp
===
--- unittests/Format/SortIncludesTest.cpp
+++ unittests/Format/SortIncludesTest.cpp
@@ -398,6 +398,17 @@
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -1539,12 +1539,18 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool isLikelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
+  if (isLikelyXml(Code))
+return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
   isMpegTS(Code))
 return Replaces;
@@ -1894,6 +1900,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
+  if (isLikelyXml(Code))
+return tooling::Replacements();
   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
 return tooling::Replacements();
 


Index: unittests/Format/SortIncludesTest.cpp
===
--- unittests/Format/SortIncludesTest.cpp
+++ unittests/Format/SortIncludesTest.cpp
@@ -398,6 +398,17 @@
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -1539,12 +1539,18 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool isLikelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
+  if (isLikelyXml(Code))
+return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
   isMpegTS(Code))
 return Replaces;
@@ -1894,6 +1900,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
+  if (isLikelyXml(Code))
+return tooling::Replacements();
   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
 return tooling::Replacements();
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r311999 - [clang-format] Do not format likely xml

2017-08-29 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Aug 29 06:51:38 2017
New Revision: 311999

URL: http://llvm.org/viewvc/llvm-project?rev=311999&view=rev
Log:
[clang-format] Do not format likely xml

Summary:
This patch detects the leading '<' in likely xml files and stops formatting in
that case. A recent use of a Qt xml file with a .ts extension triggered this:
http://doc.qt.io/qt-4.8/linguist-ts-file-format.html

Reviewers: djasper

Reviewed By: djasper

Subscribers: sammccall, cfe-commits, klimek

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

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/SortIncludesTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=311999&r1=311998&r2=311999&view=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Aug 29 06:51:38 2017
@@ -1539,14 +1539,19 @@ bool isMpegTS(StringRef Code) {
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+   isMpegTS(Code)))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1894,7 +1899,8 @@ tooling::Replacements reformat(const For
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
 return tooling::Replacements();
 
   typedef std::function

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=311999&r1=311998&r2=311999&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Aug 29 06:51:38 2017
@@ -11253,6 +11253,13 @@ TEST_F(FormatTest, UTF8CharacterLiteralC
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang

Modified: cfe/trunk/unittests/Format/SortIncludesTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/SortIncludesTest.cpp?rev=311999&r1=311998&r2=311999&view=diff
==
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp (original)
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp Tue Aug 29 06:51:38 2017
@@ -398,6 +398,17 @@ TEST_F(SortIncludesTest, ValidAffactedRa
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


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


[PATCH] D37136: [clang-format] Do not format likely xml

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311999: [clang-format] Do not format likely xml (authored by 
krasimir).

Changed prior to commit:
  https://reviews.llvm.org/D37136?vs=113085&id=113087#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37136

Files:
  cfe/trunk/lib/Format/Format.cpp
  cfe/trunk/unittests/Format/FormatTest.cpp
  cfe/trunk/unittests/Format/SortIncludesTest.cpp


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1539,14 +1539,19 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+   isMpegTS(Code)))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1894,7 +1899,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
 return tooling::Replacements();
 
   typedef std::function
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: cfe/trunk/unittests/Format/SortIncludesTest.cpp
===
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp
@@ -398,6 +398,17 @@
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1539,14 +1539,19 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+   isMpegTS(Code)))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1894,7 +1899,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
 return tooling::Replacements();
 
   typedef std::function
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: cfe/trunk/unittests/Format/SortIncludesTest.cpp
===
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp
+++ cfe/trunk/unittests/Format/SortInc

r312000 - [clang-format] Refactor likely xml a bit, NFC

2017-08-29 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Aug 29 06:57:31 2017
New Revision: 312000

URL: http://llvm.org/viewvc/llvm-project?rev=312000&view=rev
Log:
[clang-format] Refactor likely xml a bit, NFC

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=312000&r1=311999&r2=312000&view=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Aug 29 06:57:31 2017
@@ -1539,7 +1539,7 @@ bool isMpegTS(StringRef Code) {
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
-bool likelyXml(StringRef Code) {
+bool isLikelyXml(StringRef Code) {
   return Code.ltrim().startswith("<");
 }
 
@@ -1549,9 +1549,10 @@ tooling::Replacements sortIncludes(const
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (likelyXml(Code) ||
-  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-   isMpegTS(Code)))
+  if (isLikelyXml(Code))
+return Replaces;
+  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+  isMpegTS(Code))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1899,8 +1900,9 @@ tooling::Replacements reformat(const For
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (likelyXml(Code) ||
-  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
+  if (isLikelyXml(Code))
+return tooling::Replacements();
+  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
 return tooling::Replacements();
 
   typedef std::function


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


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-08-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 113088.
xazax.hun marked 2 inline comments as done.
xazax.hun added a comment.

- Updates according to review comments.


https://reviews.llvm.org/D34512

Files:
  include/clang/Basic/AllDiagnostics.h
  include/clang/Basic/CMakeLists.txt
  include/clang/Basic/Diagnostic.td
  include/clang/Basic/DiagnosticCrossTUKinds.td
  include/clang/Basic/DiagnosticIDs.h
  include/clang/CrossTU/CrossTUDiagnostic.h
  include/clang/CrossTU/CrossTranslationUnit.h
  lib/AST/ASTImporter.cpp
  lib/Basic/DiagnosticIDs.cpp
  lib/CMakeLists.txt
  lib/CrossTU/CMakeLists.txt
  lib/CrossTU/CrossTranslationUnit.cpp
  test/Analysis/func-mapping-test.cpp
  test/CMakeLists.txt
  test/lit.cfg
  tools/CMakeLists.txt
  tools/clang-func-mapping/CMakeLists.txt
  tools/clang-func-mapping/ClangFnMapGen.cpp
  tools/diagtool/DiagnosticNames.cpp
  unittests/CMakeLists.txt
  unittests/CrossTU/CMakeLists.txt
  unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- /dev/null
+++ unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -0,0 +1,98 @@
+//===- unittest/Tooling/CrossTranslationUnitTest.cpp - Tooling unit tests -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/AST/ASTConsumer.h"
+#include "clang/CrossTU/CrossTranslationUnit.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Config/llvm-config.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace cross_tu {
+
+namespace {
+StringRef IndexFileName = "index.txt";
+StringRef ASTFileName = "f.ast";
+StringRef DefinitionFileName = "input.cc";
+
+class CTUASTConsumer : public clang::ASTConsumer {
+public:
+  explicit CTUASTConsumer(clang::CompilerInstance &CI, bool *Success)
+  : CTU(CI), Success(Success) {}
+
+  void HandleTranslationUnit(ASTContext &Ctx) {
+const TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
+const FunctionDecl *FD = nullptr;
+for (const Decl *D : TU->decls()) {
+  FD = dyn_cast(D);
+  if (FD && FD->getName() == "f")
+break;
+}
+assert(FD);
+bool OrigFDHasBody = FD->hasBody();
+
+// Prepare the index file and the AST file.
+std::error_code EC;
+llvm::raw_fd_ostream OS(IndexFileName, EC, llvm::sys::fs::F_Text);
+OS << "c:@F@f#I# " << ASTFileName << "\n";
+OS.flush();
+StringRef SourceText = "int f(int) { return 0; }\n";
+// This file must exist since the saved ASTFile will reference it.
+llvm::raw_fd_ostream OS2(DefinitionFileName, EC, llvm::sys::fs::F_Text);
+OS2 << SourceText;
+OS2.flush();
+std::unique_ptr ASTWithDefinition =
+tooling::buildASTFromCode(SourceText);
+ASTWithDefinition->Save(ASTFileName);
+
+// Load the definition from the AST file.
+const FunctionDecl *NewFD =
+CTU.getCrossTUDefinition(FD, ".", IndexFileName);
+
+*Success = NewFD && NewFD->hasBody() && !OrigFDHasBody;
+  }
+
+private:
+  CrossTranslationUnitContext CTU;
+  bool *Success;
+};
+
+class CTUAction : public clang::ASTFrontendAction {
+public:
+  CTUAction(bool *Success) : Success(Success) {}
+
+protected:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance &CI, StringRef) override {
+return llvm::make_unique(CI, Success);
+  }
+
+private:
+  bool *Success;
+};
+
+} // end namespace
+
+TEST(CrossTranslationUnit, CanLoadFunctionDefinition) {
+  bool Success = false;
+  EXPECT_TRUE(tooling::runToolOnCode(new CTUAction(&Success), "int f(int);"));
+  EXPECT_TRUE(Success);
+  EXPECT_TRUE(llvm::sys::fs::exists(IndexFileName));
+  EXPECT_FALSE((bool)llvm::sys::fs::remove(IndexFileName));
+  EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
+  EXPECT_FALSE((bool)llvm::sys::fs::remove(ASTFileName));
+  EXPECT_TRUE(llvm::sys::fs::exists(DefinitionFileName));
+  EXPECT_FALSE((bool)llvm::sys::fs::remove(DefinitionFileName));
+}
+
+} // end namespace cross_tu
+} // end namespace clang
Index: unittests/CrossTU/CMakeLists.txt
===
--- /dev/null
+++ unittests/CrossTU/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+  Support
+  )
+
+add_clang_unittest(CrossTUTests
+  CrossTranslationUnitTest.cpp
+  )
+
+target_link_libraries(CrossTUTests
+  clangAST
+  clangBasic
+  clangCrossTU
+  clangFrontend
+  clangTooling
+  )
Index: unittests/CMakeLists.txt
===
--- unittests/CMakeLists.txt
+++ unittests/CMakeLists.txt
@@ -19,6 +19,7 @@
 endif()
 add_subdirectory(ASTMatchers)
 add_subdirectory(AST)
+add_subdirectory(CrossTU)
 add_subdir

[PATCH] D37249: [Bash-autocomplete] Refactor autocomplete code into own function

2017-08-29 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor accepted this revision.
teemperor added a comment.
This revision is now accepted and ready to land.

LGTM!


https://reviews.llvm.org/D37249



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


[PATCH] D37263: [clang-format] Ignore case when sorting using-declarations

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.

This ignores case while sorting using-declarations, fixing the wierd case in the
last test case added.


https://reviews.llvm.org/D37263

Files:
  lib/Format/UsingDeclarationsSorter.cpp
  unittests/Format/UsingDeclarationsSorterTest.cpp


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration &Other) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration &Other) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
rogfer01 added a comment.

There are a few tests checking the precise interaction between `__fp16` and 
`_Float16` values but I don't see tests interacting `_Float16` and the other 
standard floating types `float`, `double` and `long double`.

Do you reckon it is worth adding them as well?




Comment at: test/Frontend/float16.cpp:82
+
+// When do have native half types, we expect to see promotions X:
+

Is this X some form of TODO?


https://reviews.llvm.org/D33719



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


[PATCH] D37263: [clang-format] Ignore case when sorting using-declarations

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 113092.
krasimir added a comment.

- Actually add a test


https://reviews.llvm.org/D37263

Files:
  lib/Format/UsingDeclarationsSorter.cpp
  unittests/Format/UsingDeclarationsSorterTest.cpp


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using A;",
+sortUsingDeclarations("using a;\n"
+  "using A;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration &Other) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using A;",
+sortUsingDeclarations("using a;\n"
+  "using A;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration &Other) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2017-08-29 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel updated this revision to Diff 113094.
koldaniel added a comment.

Renaming the unsafe checker, updating tests.


https://reviews.llvm.org/D35068

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/Driver/Tools.cpp
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  test/Analysis/security-syntax-checks.m

Index: test/Analysis/security-syntax-checks.m
===
--- test/Analysis/security-syntax-checks.m
+++ test/Analysis/security-syntax-checks.m
@@ -13,6 +13,9 @@
 # define BUILTIN(f) f
 #endif /* USE_BUILTINS */
 
+#include "Inputs/system-header-simulator-for-valist.h"
+#include "Inputs/system-header-simulator-for-simple-stream.h"
+
 typedef typeof(sizeof(int)) size_t;
 
 
@@ -202,3 +205,83 @@
   mkdtemp("XX");
 }
 
+
+//===--===
+// deprecated or unsafe buffer handling
+//===--===
+typedef int wchar_t;
+
+int sprintf(char *str, const char *format, ...);
+//int vsprintf (char *s, const char *format, va_list arg);
+int scanf(const char *format, ...);
+int wscanf(const wchar_t *format, ...);
+int fscanf(FILE *stream, const char *format, ...);
+int fwscanf(FILE *stream, const wchar_t *format, ...);
+int vscanf(const char *format, va_list arg);
+int vwscanf(const wchar_t *format, va_list arg);
+int vfscanf(FILE *stream, const char *format, va_list arg);
+int vfwscanf(FILE *stream, const wchar_t *format, va_list arg);
+int sscanf(const char *s, const char *format, ...);
+int swscanf(const wchar_t *ws, const wchar_t *format, ...);
+int vsscanf(const char *s, const char *format, va_list arg);
+int vswscanf(const wchar_t *ws, const wchar_t *format, va_list arg);
+int swprintf(wchar_t *ws, size_t len, const wchar_t *format, ...);
+int snprintf(char *s, size_t n, const char *format, ...);
+int vswprintf(wchar_t *ws, size_t len, const wchar_t *format, va_list arg);
+int vsnprintf(char *s, size_t n, const char *format, va_list arg);
+void *memcpy(void *destination, const void *source, size_t num);
+void *memmove(void *destination, const void *source, size_t num);
+char *strncpy(char *destination, const char *source, size_t num);
+char *strncat(char *destination, const char *source, size_t num);
+void *memset(void *ptr, int value, size_t num);
+
+void test_deprecated_or_unsafe_buffer_handling_1() {
+  char buf [5];
+  wchar_t wbuf [5];
+  int a;
+  FILE *file;
+  sprintf(buf, "a"); // expected-warning{{Using 'sprintf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'sprintf_s'}}
+  scanf("%d", &a); // expected-warning{{Using 'scanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'scanf_s'}}
+  scanf("%s", buf); // expected-warning{{Call to function 'scanf' is insecure as it does not provide bounding of the memory buffer. Replace with analogous functions that support length arguments or provides boundary checks such as 'scanf_s' in case of C11}} expected-warning{{Using 'scanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'scanf_s'}}
+  scanf("%4s", buf); // expected-warning{{Using 'scanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'scanf_s'}}
+  wscanf((const wchar_t*) L"%s", buf); // expected-warning{{Call to function 'wscanf' is insecure as it does not provide bounding of the memory buffer. Replace with analogous functions that support length arguments or provides boundary checks such as 'wscanf_s' in case of C11}} expected-warning{{Using 'wscanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'wscanf_s'}}
+  fscanf(file, "%d", &a); // expected-warning{{Using 'fscanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'fscanf_s'}}
+  fscanf(file, "%s", buf); // expected-warning{{Call to function 'fscanf' is insecure as it does n

[PATCH] D35678: Omit sumbodule semantics for TS modules

2017-08-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312007: [modules-ts] Omit submodule semantics for TS modules 
(authored by borisk).

Changed prior to commit:
  https://reviews.llvm.org/D35678?vs=110875&id=113098#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35678

Files:
  cfe/trunk/lib/Frontend/CompilerInstance.cpp
  cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp


Index: cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
===
--- cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
+++ cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
@@ -2,13 +2,17 @@
 // RUN: mkdir -p %t
 // RUN: echo 'export module x; export int a, b;' > %t/x.cppm
 // RUN: echo 'export module x.y; export int c;' > %t/x.y.cppm
+// RUN: echo 'export module a.b; export int d;' > %t/a.b.cppm
 //
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/x.cppm -o 
%t/x.pcm
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface 
-fmodule-file=%t/x.pcm %t/x.y.cppm -o %t/x.y.pcm
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/a.b.cppm 
-o %t/a.b.pcm
 //
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_NAME=z
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
+// RUN:-DMODULE_NAME=a.b
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_X -DMODULE_NAME=x
 
 module MODULE_NAME;
@@ -33,6 +37,7 @@
 import x [[blarg::noreturn]]; // expected-warning {{unknown attribute 
'noreturn' ignored}}
 
 import x.y;
+import a.b; // Does not imply existence of module a.
 import x.; // expected-error {{expected a module name after 'import'}}
 import .x; // expected-error {{expected a module name after 'import'}}
 
Index: cfe/trunk/lib/Frontend/CompilerInstance.cpp
===
--- cfe/trunk/lib/Frontend/CompilerInstance.cpp
+++ cfe/trunk/lib/Frontend/CompilerInstance.cpp
@@ -1601,7 +1601,22 @@
  Module::NameVisibilityKind Visibility,
  bool IsInclusionDirective) {
   // Determine what file we're searching from.
-  StringRef ModuleName = Path[0].first->getName();
+  // FIXME: Should we be deciding whether this is a submodule (here and
+  // below) based on -fmodules-ts or should we pass a flag and make the
+  // caller decide?
+  std::string ModuleName;
+  if (getLangOpts().ModulesTS) {
+// FIXME: Same code as Sema::ActOnModuleDecl() so there is probably a
+// better place/way to do this.
+for (auto &Piece : Path) {
+  if (!ModuleName.empty())
+ModuleName += ".";
+  ModuleName += Piece.first->getName();
+}
+  }
+  else
+ModuleName = Path[0].first->getName();
+
   SourceLocation ModuleNameLoc = Path[0].second;
 
   // If we've already handled this import, just return the cached result.
@@ -1816,7 +1831,7 @@
 
   // Verify that the rest of the module path actually corresponds to
   // a submodule.
-  if (Path.size() > 1) {
+  if (!getLangOpts().ModulesTS && Path.size() > 1) {
 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
   StringRef Name = Path[I].first->getName();
   clang::Module *Sub = Module->findSubmodule(Name);


Index: cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
===
--- cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
+++ cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
@@ -2,13 +2,17 @@
 // RUN: mkdir -p %t
 // RUN: echo 'export module x; export int a, b;' > %t/x.cppm
 // RUN: echo 'export module x.y; export int c;' > %t/x.y.cppm
+// RUN: echo 'export module a.b; export int d;' > %t/a.b.cppm
 //
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/x.cppm -o %t/x.pcm
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface -fmodule-file=%t/x.pcm %t/x.y.cppm -o %t/x.y.pcm
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/a.b.cppm -o %t/a.b.pcm
 //
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm -verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm -fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_NAME=z
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm -verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.

r312007 - [modules-ts] Omit submodule semantics for TS modules

2017-08-29 Thread Boris Kolpackov via cfe-commits
Author: borisk
Date: Tue Aug 29 08:30:18 2017
New Revision: 312007

URL: http://llvm.org/viewvc/llvm-project?rev=312007&view=rev
Log:
[modules-ts] Omit submodule semantics for TS modules

If a TS module name has more than one component (e.g., foo.bar) then we
erroneously activated the submodule semantics when encountering a module
declaration in the module implementation unit (e.g., 'module foo.bar;').

Reviewed By: rsmith

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


Modified:
cfe/trunk/lib/Frontend/CompilerInstance.cpp
cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp

Modified: cfe/trunk/lib/Frontend/CompilerInstance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInstance.cpp?rev=312007&r1=312006&r2=312007&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInstance.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInstance.cpp Tue Aug 29 08:30:18 2017
@@ -1601,7 +1601,22 @@ CompilerInstance::loadModule(SourceLocat
  Module::NameVisibilityKind Visibility,
  bool IsInclusionDirective) {
   // Determine what file we're searching from.
-  StringRef ModuleName = Path[0].first->getName();
+  // FIXME: Should we be deciding whether this is a submodule (here and
+  // below) based on -fmodules-ts or should we pass a flag and make the
+  // caller decide?
+  std::string ModuleName;
+  if (getLangOpts().ModulesTS) {
+// FIXME: Same code as Sema::ActOnModuleDecl() so there is probably a
+// better place/way to do this.
+for (auto &Piece : Path) {
+  if (!ModuleName.empty())
+ModuleName += ".";
+  ModuleName += Piece.first->getName();
+}
+  }
+  else
+ModuleName = Path[0].first->getName();
+
   SourceLocation ModuleNameLoc = Path[0].second;
 
   // If we've already handled this import, just return the cached result.
@@ -1816,7 +1831,7 @@ CompilerInstance::loadModule(SourceLocat
 
   // Verify that the rest of the module path actually corresponds to
   // a submodule.
-  if (Path.size() > 1) {
+  if (!getLangOpts().ModulesTS && Path.size() > 1) {
 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
   StringRef Name = Path[I].first->getName();
   clang::Module *Sub = Module->findSubmodule(Name);

Modified: 
cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp?rev=312007&r1=312006&r2=312007&view=diff
==
--- cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp 
(original)
+++ cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp 
Tue Aug 29 08:30:18 2017
@@ -2,13 +2,17 @@
 // RUN: mkdir -p %t
 // RUN: echo 'export module x; export int a, b;' > %t/x.cppm
 // RUN: echo 'export module x.y; export int c;' > %t/x.y.cppm
+// RUN: echo 'export module a.b; export int d;' > %t/a.b.cppm
 //
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/x.cppm -o 
%t/x.pcm
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface 
-fmodule-file=%t/x.pcm %t/x.y.cppm -o %t/x.y.pcm
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/a.b.cppm 
-o %t/a.b.pcm
 //
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_NAME=z
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
+// RUN:-DMODULE_NAME=a.b
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_X -DMODULE_NAME=x
 
 module MODULE_NAME;
@@ -33,6 +37,7 @@ import x [[noreturn]]; // expected-error
 import x [[blarg::noreturn]]; // expected-warning {{unknown attribute 
'noreturn' ignored}}
 
 import x.y;
+import a.b; // Does not imply existence of module a.
 import x.; // expected-error {{expected a module name after 'import'}}
 import .x; // expected-error {{expected a module name after 'import'}}
 


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


[PATCH] D35216: [analyzer] Escape symbols when creating std::initializer_list.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/StaticAnalyzer/Core/ExprEngine.cpp:1104
+// expression classes separately.
+if (!isa(Ex))
+  for (auto Child : Ex->children()) {

dcoughlin wrote:
> What is special about ObjCBoxedExpr here? Naively I would have expected that 
> we'd want to keep the old behavior for ObjCArrayLiteral and ObjCDictionary as 
> well.
Yeah, i got it all wrong initially.

If a `char *` is boxed into `NSString`, it doesn't escape, even though `Val` 
would be the string pointer - which is what i wanted to express here; we 
already had a test for that.

Similarly, if, say, a C struct is boxed, the pointer to the struct doesn't 
escape. However, contents of the struct do escape! Conveniently, `Val` here 
would be the (lazy) compound value, similarly to `std::initializer_list`, so we 
don't need to explicitly avoid escaping the struct pointer itself.

If a C integer is boxed, nothing escapes, of course, until we implement the 
mythical non-pointer escape (eg. file descriptor integers in stream checker 
should escape when they get boxed).

For `ObjC{Array,Dictionary}Expr`essions, contents of the array/dictionary do 
actually escape. However, because only `NSObject`s can be within such boxed 
literals, and `RetainCountChecker` ignores escapes, it is largely irrelevant 
how we behave in this case - i've even no idea how to test that, so i guess it 
could be fixed later.

Reference: https://clang.llvm.org/docs/ObjectiveCLiterals.html


https://reviews.llvm.org/D35216



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


[PATCH] D35216: [analyzer] Escape symbols when creating std::initializer_list.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 113101.
NoQ added a comment.

Fix a bit of ObjCBoxedExpr behavior.


https://reviews.llvm.org/D35216

Files:
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/Analysis/initializer.cpp
  test/Analysis/objc-boxing.m

Index: test/Analysis/objc-boxing.m
===
--- test/Analysis/objc-boxing.m
+++ test/Analysis/objc-boxing.m
@@ -5,6 +5,16 @@
 typedef signed char BOOL;
 typedef long NSInteger;
 typedef unsigned long NSUInteger;
+
+@protocol NSObject
+@end
+@interface NSObject  {}
+@end
+@protocol NSCopying
+@end
+@protocol NSCoding
+@end
+
 @interface NSString @end
 @interface NSString (NSStringExtensionMethods)
 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
@@ -28,7 +38,15 @@
 + (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value ;
 @end
 
+@interface NSValue : NSObject 
+- (void)getValue:(void *)value;
++ (NSValue *)valueWithBytes:(const void *)value
+   objCType:(const char *)type;
+@end
 
+typedef typeof(sizeof(int)) size_t;
+extern void *malloc(size_t);
+extern void free(void *);
 extern char *strdup(const char *str);
 
 id constant_string() {
@@ -39,6 +57,23 @@
 return @(strdup("boxed dynamic string")); // expected-warning{{Potential memory leak}}
 }
 
+typedef struct __attribute__((objc_boxable)) {
+  const char *str;
+} BoxableStruct;
+
+id leak_within_boxed_struct() {
+  BoxableStruct bs;
+  bs.str = strdup("dynamic string"); // The duped string is now owned by val.
+  NSValue *val = @(bs); // no-warning
+  return val;
+}
+
+id leak_of_boxed_struct() {
+  BoxableStruct *bs = malloc(sizeof(BoxableStruct)); // This pointer isn't owned by val.
+  NSValue *val = @(*bs); // expected-warning{{Potential leak of memory pointed to by 'bs'}}
+  return val;
+}
+
 id const_char_pointer(int *x) {
   if (x)
 return @(3);
Index: test/Analysis/initializer.cpp
===
--- test/Analysis/initializer.cpp
+++ test/Analysis/initializer.cpp
@@ -1,7 +1,9 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=constructors -std=c++11 -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,cplusplus.NewDeleteLeaks,debug.ExprInspection -analyzer-config c++-inlining=constructors -std=c++11 -verify %s
 
 void clang_analyzer_eval(bool);
 
+#include "Inputs/system-header-simulator-cxx.h"
+
 class A {
   int x;
 public:
@@ -204,3 +206,13 @@
const char(&f)[2];
 };
 }
+
+namespace CXX_initializer_lists {
+struct C {
+  C(std::initializer_list list);
+};
+void foo() {
+  int *x = new int;
+  C c{x}; // no-warning
+}
+}
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -827,6 +827,21 @@
   }
 }
 
+namespace {
+class CollectReachableSymbolsCallback final : public SymbolVisitor {
+  InvalidatedSymbols Symbols;
+
+public:
+  explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
+  const InvalidatedSymbols &getSymbols() const { return Symbols; }
+
+  bool VisitSymbol(SymbolRef Sym) override {
+Symbols.insert(Sym);
+return true;
+  }
+};
+} // end anonymous namespace
+
 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
ExplodedNodeSet &DstTop) {
   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
@@ -1103,8 +1118,33 @@
 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
resultType,
currBldrCtx->blockCount());
-ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
-Bldr2.generateNode(S, N, state);
+ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
+
+// Escape pointers passed into the list.
+// TODO: Ideally we also need to escape the elements of
+// ObjCArrayLiterals and ObjCDictionaryLiterals, however these
+// only consist of ObjC objects, and escapes of ObjC objects
+// aren't so important (eg., retain count checker ignores them).
+if (isa(Ex) ||
+(isa(Ex) &&
+ cast(Ex)->getSubExpr()->getType()->isRecordType()))
+  for (auto Child : Ex->children()) {
+if (!Child)
+  continue;
+
+SVal Val = State->getSVal(Child, LCtx);
+
+CollectReachableSymbolsCallback Scanner =
+State->scanReachableSymbols(
+Val);
+const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
+
+State = getCheckerManager().runCheckersForPointerEscape(
+State, EscapedSymbols,
+/*CallEvent*/ nullptr, PSK_EscapeOther, nullptr);
+  }
+
+Bldr2.generateNode(S, N, State);
   }

[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer updated this revision to Diff 113100.
SjoerdMeijer added a comment.

No changes were needed to make the conversions work, the existing logic is 
taking care of that, but I agree it doesn't hurt to add a few test cases. So 
I've added tests to both files, and cleaned up that comment.


https://reviews.llvm.org/D33719

Files:
  include/clang-c/Index.h
  include/clang/AST/ASTContext.h
  include/clang/AST/BuiltinTypes.def
  include/clang/Basic/Specifiers.h
  include/clang/Basic/TokenKinds.def
  include/clang/Lex/LiteralSupport.h
  include/clang/Sema/DeclSpec.h
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/ASTContext.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/MicrosoftMangle.cpp
  lib/AST/NSAPI.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/Type.cpp
  lib/AST/TypeLoc.cpp
  lib/Analysis/PrintfFormatString.cpp
  lib/CodeGen/CGDebugInfo.cpp
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenTypes.cpp
  lib/CodeGen/ItaniumCXXABI.cpp
  lib/Format/FormatToken.cpp
  lib/Index/USRGeneration.cpp
  lib/Lex/LiteralSupport.cpp
  lib/Parse/ParseDecl.cpp
  lib/Parse/ParseExpr.cpp
  lib/Parse/ParseExprCXX.cpp
  lib/Parse/ParseTentative.cpp
  lib/Sema/DeclSpec.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaTemplateVariadic.cpp
  lib/Sema/SemaType.cpp
  lib/Serialization/ASTCommon.cpp
  lib/Serialization/ASTReader.cpp
  test/CodeGenCXX/float16-declarations.cpp
  test/Frontend/float16.cpp
  test/Lexer/half-literal.cpp
  tools/libclang/CXType.cpp

Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -53,6 +53,7 @@
 BTCASE(Float);
 BTCASE(Double);
 BTCASE(LongDouble);
+BTCASE(Float16);
 BTCASE(Float128);
 BTCASE(NullPtr);
 BTCASE(Overload);
@@ -520,7 +521,7 @@
 TKIND(Char_U);
 TKIND(UChar);
 TKIND(Char16);
-TKIND(Char32);  
+TKIND(Char32);
 TKIND(UShort);
 TKIND(UInt);
 TKIND(ULong);
@@ -538,6 +539,7 @@
 TKIND(Float);
 TKIND(Double);
 TKIND(LongDouble);
+TKIND(Float16);
 TKIND(Float128);
 TKIND(NullPtr);
 TKIND(Overload);
Index: test/Lexer/half-literal.cpp
===
--- test/Lexer/half-literal.cpp
+++ test/Lexer/half-literal.cpp
@@ -1,3 +1,6 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -pedantic %s
 float a = 1.0h; // expected-error{{invalid suffix 'h' on floating constant}}
 float b = 1.0H; // expected-error{{invalid suffix 'H' on floating constant}}
+
+_Float16 c = 1.f166; // expected-error{{invalid suffix 'f166' on floating constant}}
+_Float16 d = 1.f1;   // expected-error{{invalid suffix 'f1' on floating constant}}
Index: test/Frontend/float16.cpp
===
--- /dev/null
+++ test/Frontend/float16.cpp
@@ -0,0 +1,326 @@
+// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -ast-dump -fnative-half-type %s | FileCheck %s --check-prefix=CHECK-NATIVE
+
+/*  Various contexts where type _Float16 can appear. */
+
+/*  Namespace */
+namespace {
+  _Float16 f1n;
+  _Float16 f2n = 33.f16;
+  _Float16 arr1n[10];
+  _Float16 arr2n[] = { 1.2, 3.0, 3.e4 };
+  const volatile _Float16 func1n(const _Float16 &arg) {
+return arg + f2n + arr1n[4] - arr2n[1];
+  }
+}
+
+//CHECK: |-NamespaceDecl
+//CHECK: | |-VarDecl {{.*}} f1n '_Float16'
+//CHECK: | |-VarDecl {{.*}} f2n '_Float16' cinit
+//CHECK: | | `-FloatingLiteral {{.*}} '_Float16' 3.30e+01
+//CHECK: | |-VarDecl {{.*}} arr1n '_Float16 [10]'
+//CHECK: | |-VarDecl {{.*}} arr2n '_Float16 [3]' cinit
+//CHECK: | | `-InitListExpr {{.*}} '_Float16 [3]'
+//CHECK: | |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | |   | `-FloatingLiteral {{.*}} 'double' 1.20e+00
+//CHECK: | |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | |   | `-FloatingLiteral {{.*}} 'double' 3.00e+00
+//CHECK: | |   `-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | | `-FloatingLiteral {{.*}} 'double' 3.00e+04
+//CHECK: | `-FunctionDecl {{.*}} func1n 'const volatile _Float16 (const _Float16 &)'
+
+/* File */
+_Float16 f1f;
+_Float16 f2f = 32.4;
+_Float16 arr1f[10];
+_Float16 arr2f[] = { -1.2, -3.0, -3.e4 };
+_Float16 func1f(_Float16 arg);
+
+//CHECK: |-VarDecl {{.*}} f1f '_Float16'
+//CHECK: |-VarDecl {{.*}} f2f '_Float16' cinit
+//CHECK: | `-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   `-FloatingLiteral {{.*}} 'double' 3.24e+01
+//CHECK: |-VarDecl {{.*}} arr1f '_Float16 [10]'
+//CHECK: |-VarDecl {{.*}} arr2f '_Float16 [3]' cinit
+//CHECK: | `-InitListExpr {{.*}} '_Float16 [3]'
+//CHECK: |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   | `-UnaryOperator {{.*}} 'double' prefix '-'
+//CHECK: |   |   `-FloatingLiteral {{.*}} 'double' 1.20e+00
+//CHECK: |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   | `-UnaryOperator {{.*}} 'double' prefix '-'
+//CHECK: |   |   `-FloatingLiteral {{.*}} 'double' 3.00

[PATCH] D37001: [clang-diff] Use data collectors for node comparison

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:537
+
+#include "../../AST/DeclDataCollectors.inc"
+

I didn't realize that you're including files from within `lib`. That's not 
ideal. You should add a pre-commit that moves the *.inc files over to 
include/AST (and marks them as textual in Clang's `module.modulemap`). Then you 
should include them using the clang/AST path.


https://reviews.llvm.org/D37001



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


[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
rogfer01 accepted this revision.
rogfer01 added a comment.
This revision is now accepted and ready to land.

Thanks @SjoerdMeijer

This LGTM now. Wait a couple of days in case @rsmith has more comments.


https://reviews.llvm.org/D33719



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


[PATCH] D36750: [analyzer] RetainCount: When diagnosing overrelease, mention if it's coming from a nested block.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 113102.
NoQ marked an inline comment as done.
NoQ added a comment.

Avoid creating a new `RefVal` kind.

In https://reviews.llvm.org/D36750#843427, @dcoughlin wrote:

> > By the way, plist-based tests in retain-release.m are disabled since 
> > r163536 (~2012), and need to be updated. It's trivial to re-enable them but 
> > annoying to maintain - would we prefer to re-enable or delete them or 
> > replace with -analyzer-output=text tests?
>
> My preference would be to factor out/re-target some specific tests into their 
> own file and check that with -verify + -analyzer-output=text and with plist 
> comparisons


Hmm, which specific tests do you have in mind? And is it worth it to try to 
recover the intended arrows in plists from the old plist tests?


https://reviews.llvm.org/D36750

Files:
  lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
  test/Analysis/retain-release.m


Index: test/Analysis/retain-release.m
===
--- test/Analysis/retain-release.m
+++ test/Analysis/retain-release.m
@@ -2300,6 +2300,23 @@
   CFRelease(obj);
 }
 
+//===--===//
+// When warning within blocks make it obvious that warnings refer to blocks.
+//===--===//
+
+int useBlock(int (^block)());
+void rdar31699502_hardToNoticeBlocks() {
+  if (useBlock(^{
+NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+NSArray *array = [NSArray array];
+[array release]; // expected-warning{{Incorrect decrement of the reference 
count of an object that is not owned at this point by the current block}}
+[pool drain];
+return 0;
+  })) {
+return;
+  }
+}
+
 // CHECK:  diagnostics
 // CHECK-NEXT:  
 // CHECK-NEXT:   
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -1722,6 +1722,17 @@
 }
   };
 
+  class BadReleaseByBlock : public CFRefBug {
+  public:
+BadReleaseByBlock(const CheckerBase *checker)
+: CFRefBug(checker, "Bad release") {}
+
+const char *getDescription() const override {
+  return "Incorrect decrement of the reference count of an object that is "
+ "not owned at this point by the current block";
+}
+  };
+
   class DeallocGC : public CFRefBug {
   public:
 DeallocGC(const CheckerBase *checker)
@@ -2560,7 +2571,8 @@
 check::RegionChanges,
 eval::Assume,
 eval::Call > {
-  mutable std::unique_ptr useAfterRelease, releaseNotOwned;
+  mutable std::unique_ptr useAfterRelease;
+  mutable std::unique_ptr releaseNotOwned, releaseNotOwnedByBlock;
   mutable std::unique_ptr deallocGC, deallocNotOwned;
   mutable std::unique_ptr overAutorelease, returnNotOwnedForOwned;
   mutable std::unique_ptr leakWithinFunction, leakAtReturn;
@@ -3396,9 +3408,15 @@
   BT = useAfterRelease.get();
   break;
 case RefVal::ErrorReleaseNotOwned:
-  if (!releaseNotOwned)
-releaseNotOwned.reset(new BadRelease(this));
-  BT = releaseNotOwned.get();
+  if (isa(C.getLocationContext()->getDecl())) {
+if (!releaseNotOwnedByBlock)
+  releaseNotOwnedByBlock.reset(new BadReleaseByBlock(this));
+BT = releaseNotOwnedByBlock.get();
+  } else {
+if (!releaseNotOwned)
+  releaseNotOwned.reset(new BadRelease(this));
+BT = releaseNotOwned.get();
+  }
   break;
 case RefVal::ErrorDeallocGC:
   if (!deallocGC)


Index: test/Analysis/retain-release.m
===
--- test/Analysis/retain-release.m
+++ test/Analysis/retain-release.m
@@ -2300,6 +2300,23 @@
   CFRelease(obj);
 }
 
+//===--===//
+// When warning within blocks make it obvious that warnings refer to blocks.
+//===--===//
+
+int useBlock(int (^block)());
+void rdar31699502_hardToNoticeBlocks() {
+  if (useBlock(^{
+NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+NSArray *array = [NSArray array];
+[array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the current block}}
+[pool drain];
+return 0;
+  })) {
+return;
+  }
+}
+
 // CHECK:  diagnostics
 // CHECK-NEXT:  
 // CHECK-NEXT:   
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -1722,6 +1722,17 @@
 }
   };
 
+  class BadReleaseByBlo

[PATCH] D37038: Replace temp MD nodes with unique/distinct before cloning

2017-08-29 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

This may have gotten lost earlier:  Would it be possible to instruct 
CloneFunction to not clone any temporary MDNodes via one of the flags that are 
passed to the ValueMapper?


https://reviews.llvm.org/D37038



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


Re: r311823 - Add flag to request Clang is ABI-compatible with older versions of itself

2017-08-29 Thread Hans Wennborg via cfe-commits
Merged in r312013.

On Fri, Aug 25, 2017 at 6:06 PM, Richard Smith  wrote:
> Hi Hans,
>
> We should get this into Clang 5 so that people can opt out of the ABI bugfix
> for passing C++ class types by value.
>
> On 25 August 2017 at 18:04, Richard Smith via cfe-commits
>  wrote:
>>
>> Author: rsmith
>> Date: Fri Aug 25 18:04:35 2017
>> New Revision: 311823
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=311823&view=rev
>> Log:
>> Add flag to request Clang is ABI-compatible with older versions of itself
>>
>> This patch adds a flag -fclang-abi-compat that can be used to request that
>> Clang attempts to be ABI-compatible with some older version of itself.
>>
>> This is provided on a best-effort basis; right now, this can be used to
>> undo
>> the ABI change in r310401, reverting Clang to its prior C++ ABI for
>> pass/return
>> by value of class types affected by that change, and to undo the ABI
>> change in
>> r262688, reverting Clang to using integer registers rather than SSE
>> registers
>> for passing <1 x long long> vectors. The intent is that we will maintain
>> this
>> backwards compatibility path as we make ABI-breaking fixes in future.
>>
>> The reversion to the old behavior for r310401 is also applied to the PS4
>> target
>> since that change is not part of its platform ABI (which is essentially to
>> do
>> whatever Clang 3.2 did).
>>
>> Added:
>> cfe/trunk/test/CodeGenCXX/clang-abi-compat.cpp
>> cfe/trunk/test/Frontend/clang-abi-compat.cpp
>> Modified:
>> 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/ABIInfo.h
>> cfe/trunk/lib/CodeGen/CodeGenTypes.cpp
>> cfe/trunk/lib/CodeGen/CodeGenTypes.h
>> cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
>> cfe/trunk/lib/CodeGen/TargetInfo.cpp
>> cfe/trunk/lib/Driver/ToolChains/Clang.cpp
>> cfe/trunk/lib/Frontend/CompilerInvocation.cpp
>> cfe/trunk/test/CodeGenCXX/uncopyable-args.cpp
>> cfe/trunk/test/Driver/flags.c
>>
>> Modified: cfe/trunk/include/clang/Driver/Options.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=311823&r1=311822&r2=311823&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Driver/Options.td (original)
>> +++ cfe/trunk/include/clang/Driver/Options.td Fri Aug 25 18:04:35 2017
>> @@ -711,6 +711,9 @@ def fbuiltin : Flag<["-"], "fbuiltin">,
>>  def fbuiltin_module_map : Flag <["-"], "fbuiltin-module-map">,
>> Group,
>>Flags<[DriverOption]>, HelpText<"Load the clang builtins module map
>> file.">;
>>  def fcaret_diagnostics : Flag<["-"], "fcaret-diagnostics">,
>> Group;
>> +def fclang_abi_compat_EQ : Joined<["-"], "fclang-abi-compat=">,
>> Group,
>> +  Flags<[CC1Option]>, MetaVarName<"">,
>> Values<".,latest">,
>> +  HelpText<"Attempt to match the ABI of Clang ">;
>>  def fclasspath_EQ : Joined<["-"], "fclasspath=">, Group;
>>  def fcolor_diagnostics : Flag<["-"], "fcolor-diagnostics">,
>> Group,
>>Flags<[CoreOption, CC1Option]>, HelpText<"Use colors in diagnostics">;
>>
>> Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.def
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.def?rev=311823&r1=311822&r2=311823&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Frontend/CodeGenOptions.def (original)
>> +++ cfe/trunk/include/clang/Frontend/CodeGenOptions.def Fri Aug 25
>> 18:04:35 2017
>> @@ -120,6 +120,10 @@ CODEGENOPT(NoZeroInitializedInBSS , 1, 0
>>  ENUM_CODEGENOPT(ObjCDispatchMethod, ObjCDispatchMethodKind, 2, Legacy)
>>  CODEGENOPT(OmitLeafFramePointer , 1, 0) ///< Set when
>> -momit-leaf-frame-pointer is
>>  ///< enabled.
>> +
>> +/// A version of Clang that we should attempt to be ABI-compatible with.
>> +ENUM_CODEGENOPT(ClangABICompat, ClangABI, 4, ClangABI::Latest)
>> +
>>  VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option
>> specified.
>>  VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is
>> specified.
>>
>>
>> Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.h?rev=311823&r1=311822&r2=311823&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Frontend/CodeGenOptions.h (original)
>> +++ cfe/trunk/include/clang/Frontend/CodeGenOptions.h Fri Aug 25 18:04:35
>> 2017
>> @@ -69,6 +69,23 @@ public:
>>  LocalExecTLSModel
>>};
>>
>> +  /// Clang versions with different platform ABI conformance.
>> +  enum class ClangABI {
>> +/// Attempt to be ABI-compatible with code generated by Clang 3.8.x
>> +/// (SVN r257626). This causes <1 x long long> to be 

r312017 - [ms] Fix vbtable index for covariant overrides of vbase methods

2017-08-29 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Tue Aug 29 10:40:04 2017
New Revision: 312017

URL: http://llvm.org/viewvc/llvm-project?rev=312017&view=rev
Log:
[ms] Fix vbtable index for covariant overrides of vbase methods

Overriding a method from a virtual base with a covariant return type
consumes a slot from the vftable in the virtual base. This can make it
impossible to implement certain diamond inheritance hierarchies, but we
have to follow along for compatibility in the simple cases.

This patch only affects our vtable dumper and member pointer function
mangling, since all other callers of getMethodVFTableLocation seem to
recompute VBTableIndex instead of using the one in the method location.

Patch by David Majnemer

Modified:
cfe/trunk/lib/AST/VTableBuilder.cpp
cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp

Modified: cfe/trunk/lib/AST/VTableBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/VTableBuilder.cpp?rev=312017&r1=312016&r2=312017&view=diff
==
--- cfe/trunk/lib/AST/VTableBuilder.cpp (original)
+++ cfe/trunk/lib/AST/VTableBuilder.cpp Tue Aug 29 10:40:04 2017
@@ -2963,6 +2963,9 @@ void VFTableBuilder::AddMethods(BaseSubo
   CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
   ThisAdjustmentOffset);
 
+unsigned VBIndex =
+LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
+
 if (OverriddenMD) {
   // If MD overrides anything in this vftable, we need to update the
   // entries.
@@ -2975,6 +2978,8 @@ void VFTableBuilder::AddMethods(BaseSubo
 
   MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
 
+  VBIndex = OverriddenMethodInfo.VBTableIndex;
+
   // Let's check if the overrider requires any return adjustments.
   // We must create a new slot if the MD's return type is not trivially
   // convertible to the OverriddenMD's one.
@@ -2987,8 +2992,7 @@ void VFTableBuilder::AddMethods(BaseSubo
   if (!ReturnAdjustingThunk) {
 // No return adjustment needed - just replace the overridden method 
info
 // with the current info.
-MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
-  OverriddenMethodInfo.VFTableIndex);
+MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
 MethodInfoMap.erase(OverriddenMDIterator);
 
 assert(!MethodInfoMap.count(MD) &&
@@ -3015,8 +3019,6 @@ void VFTableBuilder::AddMethods(BaseSubo
 
 // If we got here, MD is a method not seen in any of the sub-bases or
 // it requires return adjustment. Insert the method info for this method.
-unsigned VBIndex =
-LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
 MethodInfo MI(VBIndex,
   HasRTTIComponent ? Components.size() - 1 : Components.size(),
   ReturnAdjustingThunk);

Modified: cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp?rev=312017&r1=312016&r2=312017&view=diff
==
--- cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp Tue Aug 
29 10:40:04 2017
@@ -201,3 +201,18 @@ D::D() {}
 // GLOBALS: @"\01?fn@D@test3@@$4PPPM@A@AEPAUB@2@XZ"
 // GLOBALS: @"\01?fn@D@test3@@$4PPPM@A@AEPAU12@XZ"
 }
+
+namespace pr34302 {
+// C::f is lives in the vftable inside its virtual B subobject. In the MS ABI,
+// covariant return type virtual methods extend vftables from virtual bases,
+// even though that can make it impossible to implement certain diamond
+// hierarchies correctly.
+struct A { virtual ~A(); };
+struct B : A { virtual B *f(); };
+struct C : virtual B { C *f(); };
+C c;
+// VFTABLES-LABEL: VFTable indices for 'pr34302::C' (2 entries).
+// VFTABLES-NEXT:  -- accessible via vbtable index 1, vfptr at offset 0 --
+// VFTABLES-NEXT:0 | pr34302::C::~C() [scalar deleting]
+// VFTABLES-NEXT:2 | pr34302::C *pr34302::C::f()
+}


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


r312018 - [Bash-autocomplete] Refactor autocomplete code into own function

2017-08-29 Thread Yuka Takahashi via cfe-commits
Author: yamaguchi
Date: Tue Aug 29 10:46:46 2017
New Revision: 312018

URL: http://llvm.org/viewvc/llvm-project?rev=312018&view=rev
Log:
[Bash-autocomplete] Refactor autocomplete code into own function

Summary:
We wrote many codes in HandleImediateArgs, so I've refactored it into
handleAutocompletions.

Reviewers: v.g.vassilev, teemperor

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang/Driver/Driver.h
cfe/trunk/lib/Driver/Driver.cpp

Modified: cfe/trunk/include/clang/Driver/Driver.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Driver.h?rev=312018&r1=312017&r2=312018&view=diff
==
--- cfe/trunk/include/clang/Driver/Driver.h (original)
+++ cfe/trunk/include/clang/Driver/Driver.h Tue Aug 29 10:46:46 2017
@@ -425,6 +425,10 @@ public:
   // FIXME: This should be in CompilationInfo.
   std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
 
+  /// handleAutocompletions - Handle --autocomplete by searching and printing
+  /// possible flags, descriptions, and its arguments.
+  void handleAutocompletions(StringRef PassedFlags) const;
+
   /// HandleImmediateArgs - Handle any arguments which should be
   /// treated before building actions or binding tools.
   ///

Modified: cfe/trunk/lib/Driver/Driver.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Driver.cpp?rev=312018&r1=312017&r2=312018&view=diff
==
--- cfe/trunk/lib/Driver/Driver.cpp (original)
+++ cfe/trunk/lib/Driver/Driver.cpp Tue Aug 29 10:46:46 2017
@@ -1156,6 +1156,56 @@ static void PrintDiagnosticCategories(ra
 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
 }
 
+void Driver::handleAutocompletions(StringRef PassedFlags) const {
+  // Print out all options that start with a given argument. This is used for
+  // shell autocompletion.
+  std::vector SuggestedCompletions;
+
+  unsigned short DisableFlags =
+  options::NoDriverOption | options::Unsupported | options::Ignored;
+  // We want to show cc1-only options only when clang is invoked as "clang
+  // -cc1".
+  // When clang is invoked as "clang -cc1", we add "#" to the beginning of an
+  // --autocomplete
+  // option so that the clang driver can distinguish whether it is requested to
+  // show cc1-only options or not.
+  if (PassedFlags[0] == '#') {
+DisableFlags &= ~options::NoDriverOption;
+PassedFlags = PassedFlags.substr(1);
+  }
+
+  if (PassedFlags.find(',') == StringRef::npos) {
+// If the flag is in the form of "--autocomplete=-foo",
+// we were requested to print out all option names that start with "-foo".
+// For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
+SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
+
+// We have to query the -W flags manually as they're not in the OptTable.
+// TODO: Find a good way to add them to OptTable instead and them remove
+// this code.
+for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
+  if (S.startswith(PassedFlags))
+SuggestedCompletions.push_back(S);
+  } else {
+// If the flag is in the form of "--autocomplete=foo,bar", we were
+// requested to print out all option values for "-foo" that start with
+// "bar". For example,
+// "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
+StringRef Option, Arg;
+std::tie(Option, Arg) = PassedFlags.split(',');
+SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
+  }
+
+  // Sort the autocomplete candidates so that shells print them out in a
+  // deterministic order. We could sort in any way, but we chose
+  // case-insensitive sorting for consistency with the -help option
+  // which prints out options in the case-insensitive alphabetical order.
+  std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
+[](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
+
+  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
+}
+
 bool Driver::HandleImmediateArgs(const Compilation &C) {
   // The order these options are handled in gcc is all over the place, but we
   // don't expect inconsistencies w.r.t. that to matter in practice.
@@ -1249,50 +1299,8 @@ bool Driver::HandleImmediateArgs(const C
   }
 
   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
-// Print out all options that start with a given argument. This is used for
-// shell autocompletion.
 StringRef PassedFlags = A->getValue();
-std::vector SuggestedCompletions;
-
-unsigned short DisableFlags = options::NoDriverOption | 
options::Unsupported | options::Ignored;
-// We want to show cc1-only options only when clang is invoked as "clang 
-cc1".
-// When clang is invoked as "clang -cc1", we add "#" t

[PATCH] D37249: [Bash-autocomplete] Refactor autocomplete code into own function

2017-08-29 Thread Yuka Takahashi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312018: [Bash-autocomplete] Refactor autocomplete code into 
own function (authored by yamaguchi).

Changed prior to commit:
  https://reviews.llvm.org/D37249?vs=113027&id=113118#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37249

Files:
  cfe/trunk/include/clang/Driver/Driver.h
  cfe/trunk/lib/Driver/Driver.cpp

Index: cfe/trunk/lib/Driver/Driver.cpp
===
--- cfe/trunk/lib/Driver/Driver.cpp
+++ cfe/trunk/lib/Driver/Driver.cpp
@@ -1156,6 +1156,56 @@
 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
 }
 
+void Driver::handleAutocompletions(StringRef PassedFlags) const {
+  // Print out all options that start with a given argument. This is used for
+  // shell autocompletion.
+  std::vector SuggestedCompletions;
+
+  unsigned short DisableFlags =
+  options::NoDriverOption | options::Unsupported | options::Ignored;
+  // We want to show cc1-only options only when clang is invoked as "clang
+  // -cc1".
+  // When clang is invoked as "clang -cc1", we add "#" to the beginning of an
+  // --autocomplete
+  // option so that the clang driver can distinguish whether it is requested to
+  // show cc1-only options or not.
+  if (PassedFlags[0] == '#') {
+DisableFlags &= ~options::NoDriverOption;
+PassedFlags = PassedFlags.substr(1);
+  }
+
+  if (PassedFlags.find(',') == StringRef::npos) {
+// If the flag is in the form of "--autocomplete=-foo",
+// we were requested to print out all option names that start with "-foo".
+// For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
+SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
+
+// We have to query the -W flags manually as they're not in the OptTable.
+// TODO: Find a good way to add them to OptTable instead and them remove
+// this code.
+for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
+  if (S.startswith(PassedFlags))
+SuggestedCompletions.push_back(S);
+  } else {
+// If the flag is in the form of "--autocomplete=foo,bar", we were
+// requested to print out all option values for "-foo" that start with
+// "bar". For example,
+// "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
+StringRef Option, Arg;
+std::tie(Option, Arg) = PassedFlags.split(',');
+SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
+  }
+
+  // Sort the autocomplete candidates so that shells print them out in a
+  // deterministic order. We could sort in any way, but we chose
+  // case-insensitive sorting for consistency with the -help option
+  // which prints out options in the case-insensitive alphabetical order.
+  std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
+[](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
+
+  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
+}
+
 bool Driver::HandleImmediateArgs(const Compilation &C) {
   // The order these options are handled in gcc is all over the place, but we
   // don't expect inconsistencies w.r.t. that to matter in practice.
@@ -1249,50 +1299,8 @@
   }
 
   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
-// Print out all options that start with a given argument. This is used for
-// shell autocompletion.
 StringRef PassedFlags = A->getValue();
-std::vector SuggestedCompletions;
-
-unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
-// We want to show cc1-only options only when clang is invoked as "clang -cc1".
-// When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
-// option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
-if (PassedFlags[0] == '#') {
-  DisableFlags &= ~options::NoDriverOption;
-  PassedFlags = PassedFlags.substr(1);
-}
-
-if (PassedFlags.find(',') == StringRef::npos) {
-  // If the flag is in the form of "--autocomplete=-foo",
-  // we were requested to print out all option names that start with "-foo".
-  // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
-  SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
-
-  // We have to query the -W flags manually as they're not in the OptTable.
-  // TODO: Find a good way to add them to OptTable instead and them remove
-  // this code.
-  for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
-if (S.startswith(PassedFlags))
-  SuggestedCompletions.push_back(S);
-} else {
-  // If the flag is in the form of "--autocomplete=foo,bar", we were
-  // requested to print out all option values for "-foo" that start with
-  // "bar". For example,
-  // "--autocomplete=-stdlib=,l

[PATCH] D37038: Replace temp MD nodes with unique/distinct before cloning

2017-08-29 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

In https://reviews.llvm.org/D37038#89, @aprantl wrote:

> This may have gotten lost earlier:  Would it be possible to instruct 
> CloneFunction to not clone any temporary MDNodes via one of the flags that 
> are passed to the ValueMapper?


I did look at that, sorry for not reporting back.  ValueMapper seems to be 
quite adamant about having non-temporary nodes.  I can try pursuing that 
further but it would be quite the "learning experience" I think.
Alternatively we could try deferring the thunk cloning until after all other 
codegen, but that also seems like a pretty hacky approach.


https://reviews.llvm.org/D37038



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: compiler-rt/trunk/lib/asan/scripts/asan_device_setup:98
 if [[ $_ABI == x86* ]]; then
-_ARCH=i686
+_ARCH=i386
 elif [[ $_ABI == armeabi* ]]; then

There are lots of copies of this script in various project that now all need to 
be updated (searching the web for asan_device_setup shows some).

For me personally, this means updating Chromium (also the build system needs an 
update) to handle different names before and after this revision.

Do you have any suggestions for how we should handle this rename? Is there some 
backwards-compatibility fix we could do?

As you noticed this broke some LLVM buildbots. It also broke Chromium 
buildbots, and I suppose other projects which use asan. I'm wondering if the 
fallout is worth the benefits here.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse updated this revision to Diff 113129.
morehouse added a comment.

- Disable stack depth tracking on Mac.


https://reviews.llvm.org/D37156

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/test/fuzzer/deep-recursion.test
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function &F,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function &F, ArrayRef AllBlocks);
+  bool InjectCoverage(Function &F, ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function &F, Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function &F, ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function &F, ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
+  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   &getAnalysis(F).getDomTree();
   const PostDominatorTree *PDT =
   &getAnalysis(F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto &BB : F) {
 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
@@ -515,10 +519,14 @@
   if (Options.TraceGep)
 if (GetElementPtrInst *GEP = dyn_cast(&Inst))
   GepTraceTargets.push_back(GEP);
-   }
+  if (Options.StackDepth)
+if (isa(Inst) ||
+(isa

[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov added a comment.

Another fact: gcc 7.2.0 supports this attribute at x86_64. It would be great if 
two major compilers were feature compatible and worked in a similar way.


https://reviews.llvm.org/D36272



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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Kostya Serebryany via Phabricator via cfe-commits
kcc added inline comments.



Comment at: clang/lib/Driver/SanitizerArgs.cpp:297
 CoverageTraceCmp | CoveragePCTable;
+#if !defined(__APPLE__)
+// Due to TLS differences, stack depth tracking is disabled on Mac.

please use if(SomeCondition) instead of #if

In general: 99% of cases where you may want to use #if -- you shouldn't



Comment at: 
compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc:20
 #include "sanitizer_symbolizer.h"
+#include 
 

no standard hearder in this files. Just use the 'uptr' type. 


https://reviews.llvm.org/D37156



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

I may have underestimated the number of places that will need to be patched 
because of this change. Perhaps we should restore the special case in the 
android library name?


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

I'm happy to help with whatever needs to be done to keep breakage to the 
minimum, provided that we determine some clear path forward that doesn't 
involve regressing to the half-broken state for non-Android Linux systems and 
it's doable in the free time I can spare. However, I should point out that it 
was a very bad idea to hardcode paths all over the projects in the first place.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D36272#851709, @erichkeane wrote:

> Aaron would likely know better than me... but could it be the spelling type 
> should be GCC instead of GNU?


Yes, this should be spelled with `GCC` rather than `GNU`, as it's a documented 
GCC attribute and needs the C++11 spelling you get from that switch. That 
doesn't have to be a part of this patch, however, when it gets done, we should 
also add documentation to AttrDocs.td for the attribute.




Comment at: lib/CodeGen/TargetInfo.cpp:2293
+// Get the LLVM function.
+llvm::Function *Fn = cast(GV);
+

You can use `auto *` here instead of spelling out the type twice.



Comment at: lib/CodeGen/TargetInfo.cpp:2430
+  // Get the LLVM function.
+  llvm::Function *Fn = cast(GV);
+

You can use `auto *` here as well.


https://reviews.llvm.org/D36272



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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse updated this revision to Diff 113133.
morehouse added a comment.

- Eliminate "#if".
- Replace uintptr_t with uptr.


https://reviews.llvm.org/D37156

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/test/fuzzer/deep-recursion.test
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function &F,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function &F, ArrayRef AllBlocks);
+  bool InjectCoverage(Function &F, ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function &F, Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function &F, ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function &F, ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
+  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   &getAnalysis(F).getDomTree();
   const PostDominatorTree *PDT =
   &getAnalysis(F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto &BB : F) {
 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
@@ -515,10 +519,14 @@
   if (Options.TraceGep)
 if (GetElementPtrInst *GEP = dyn_cast(&Inst))
   GepTraceTargets.push_back(GEP);
-   }
+  if (Options.StackDepth)
+if (isa(Inst) ||
+ 

[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor updated this revision to Diff 113134.
andrew.w.kaylor added a comment.

Added warnings for null pointer arithmetic.


https://reviews.llvm.org/D37042

Files:
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/CGExprScalar.cpp
  lib/Sema/SemaExpr.cpp
  test/CodeGen/nullptr-arithmetic.c
  test/Sema/pointer-addition.c

Index: lib/CodeGen/CGExprScalar.cpp
===
--- lib/CodeGen/CGExprScalar.cpp
+++ lib/CodeGen/CGExprScalar.cpp
@@ -2671,6 +2671,37 @@
   unsigned width = cast(index->getType())->getBitWidth();
   auto &DL = CGF.CGM.getDataLayout();
   auto PtrTy = cast(pointer->getType());
+
+  // Some versions of glibc and gcc use idioms (particularly in their malloc
+  // routines) that add a pointer-sized integer (known to be a pointer value)
+  // to a null pointer in order to cast the value back to an integer or as
+  // part of a pointer alignment algorithm.  This is undefined behavior, but
+  // we'd like to be able to compile programs that use it.
+  //
+  // Normally, we'd generate a GEP with a null-pointer base here in response
+  // to that code, but it's also UB to dereference a pointer created that
+  // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
+  // generate a direct cast of the integer value to a pointer.
+  //
+  // The idiom (p = nullptr + N) is not met if any of the following are true:
+  //
+  //   The operation is subtraction.
+  //   The index is not pointer-sized.
+  //   The pointer type is not byte-sized.
+  //   The index operand is a constant.
+  //
+  if (isa(pointer) && !isSubtraction && 
+  (width == DL.getTypeSizeInBits(PtrTy)) && 
+  !isa(index)) {
+// The pointer type might come back as null, so it's deferred until here.
+const PointerType *pointerType 
+  = pointerOperand->getType()->getAs();
+if (pointerType && pointerType->getPointeeType()->isCharType()) { 
+  // (nullptr + N) -> inttoptr N to 
+  return CGF.Builder.CreateIntToPtr(index, pointer->getType());
+}
+  }
+
   if (width != DL.getTypeSizeInBits(PtrTy)) {
 // Zero-extend or sign-extend the pointer value according to
 // whether the index is signed or not.
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -8490,6 +8490,18 @@
 << 0 /* one pointer */ << Pointer->getSourceRange();
 }
 
+/// \brief Diagnose invalid arithmetic on a null pointer.
+///
+/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
+/// idiom, which we recognize as a GNU extension.
+///
+static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
+Expr *Pointer, bool IsGNUIdiom) {
+  S.Diag(Loc, IsGNUIdiom ? diag::ext_gnu_null_ptr_arith
+ : diag::warn_pointer_arith_null_ptr)
+<< Pointer->getSourceRange();
+}
+
 /// \brief Diagnose invalid arithmetic on two function pointers.
 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
 Expr *LHS, Expr *RHS) {
@@ -8784,6 +8796,21 @@
   if (!IExp->getType()->isIntegerType())
 return InvalidOperands(Loc, LHS, RHS);
 
+  // Adding to a null pointer is never an error, but should warn.
+  if (PExp->IgnoreParenCasts()->isNullPointerConstant(Context, 
+ Expr::NPC_ValueDependentIsNull)) {
+// Check the conditions to see if this is the 'p = (i8*)nullptr + n' idiom.
+bool IsGNUIdiom = false;
+const PointerType *pointerType = PExp->getType()->getAs();
+if (!IExp->isIntegerConstantExpr(Context) &&
+pointerType->getPointeeType()->isCharType() &&
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;
+
+diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
+  }
+
   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
 return QualType();
 
@@ -8845,6 +8872,13 @@
 
 // The result type of a pointer-int computation is the pointer type.
 if (RHS.get()->getType()->isIntegerType()) {
+  // Subtracting from a null pointer should produce a warning.
+  // The last argument to the diagnose call says this doesn't match the
+  // GNU int-to-pointer idiom.
+  if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
+   Expr::NPC_ValueDependentIsNull))
+diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
+
   if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
 return QualType();
 
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKi

[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a reviewer: rsmith.
efriedma added a comment.

I didn't think of this earlier, but strictly speaking, I think 
"(char*)nullptr+0" isn't undefined in C++?  But probably worth emitting the 
warning anyway; anyone writing out arithmetic on null is probably doing 
something suspicious, even if it isn't technically undefined.




Comment at: include/clang/Basic/DiagnosticSemaKinds.td:6032
+def ext_gnu_null_ptr_arith : Extension<
+  "inttoptr casting using arithmetic on a null pointer is a GNU extension">,
+  InGroup;

The keyword "inttoptr" is part of LLVM, not something we expect users to 
understand.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

Please make sure you use exactly the same check in Sema and CodeGen (probably 
easiest to stick a helper into lib/AST/).


https://reviews.llvm.org/D37042



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


r312024 - [OPENMP] Capture global variables in all target executable regions.

2017-08-29 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Aug 29 12:30:57 2017
New Revision: 312024

URL: http://llvm.org/viewvc/llvm-project?rev=312024&view=rev
Log:
[OPENMP] Capture global variables in all target executable regions.

Capturing of the global variables occurs only in target regions. Patch
fixes it and allows capturing of globals in all target executable
directives.

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

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=312024&r1=312023&r2=312024&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Tue Aug 29 12:30:57 2017
@@ -1278,7 +1278,7 @@ VarDecl *Sema::IsOpenMPCapturedDecl(Valu
   //
   auto *VD = dyn_cast(D);
   if (VD && !VD->hasLocalStorage()) {
-if (DSAStack->getCurrentDirective() == OMPD_target &&
+if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
 !DSAStack->isClauseParsingMode())
   return VD;
 if (DSAStack->hasDirective(

Modified: cfe/trunk/test/OpenMP/target_teams_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/target_teams_codegen.cpp?rev=312024&r1=312023&r2=312024&view=diff
==
--- cfe/trunk/test/OpenMP/target_teams_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/target_teams_codegen.cpp Tue Aug 29 12:30:57 2017
@@ -83,6 +83,8 @@ struct TT{
   ty Y;
 };
 
+int global;
+
 // CHECK: define {{.*}}[[FOO:@.+]](
 int foo(int n) {
   int a = 0;
@@ -178,6 +180,7 @@ int foo(int n) {
   {
 a += 1;
 aa += 1;
+global += 1;
   }
 
   // We capture 3 VLA sizes in this target region
@@ -372,6 +375,7 @@ int foo(int n) {
 // CHECK:   [[AA_ADDR:%.+]] = alloca i[[SZ]], align
 // CHECK:   [[A_CASTED:%.+]] = alloca i[[SZ]], align
 // CHECK:   [[AA_CASTED:%.+]] = alloca i[[SZ]], align
+// CHECK:   [[GLOBAL_CASTED:%.+]] = alloca i[[SZ]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align
 // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32*
@@ -384,18 +388,28 @@ int foo(int n) {
 // CHECK-DAG:   [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align
 // CHECK-DAG:   [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i16*
 // CHECK-DAG:   store i16 [[AA]], i16* [[AA_C]], align
+// CHECK-DAG:   [[GLOBAL:%.+]] = load i32, i32* @global, align
+// CHECK-64-DAG:[[GLOBAL_C:%.+]] = bitcast i[[SZ]]* [[GLOBAL_CASTED]] to i32*
+// CHECK-64-DAG:store i32 [[GLOBAL]], i32* [[GLOBAL_C]], align
+// CHECK-32-DAG:store i32 [[GLOBAL]], i32* [[GLOBAL_CASTED]], align
 // CHECK-DAG:   [[PARAM1:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CASTED]], align
 // CHECK-DAG:   [[PARAM2:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align
-// CHECK-DAG:   call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) 
@__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 2, void (i32*, i32*, ...)* 
bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]])* [[OMP_OUTLINED3:@.+]] to void 
(i32*, i32*, ...)*), i[[SZ]] [[PARAM1]], i[[SZ]] [[PARAM2]])
+// CHECK-DAG:   [[PARAM3:%.+]] = load i[[SZ]], i[[SZ]]* [[GLOBAL_CASTED]], 
align
+// CHECK-DAG:   call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) 
@__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 3, void (i32*, i32*, ...)* 
bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]], i[[SZ]])* [[OMP_OUTLINED3:@.+]] to 
void (i32*, i32*, ...)*), i[[SZ]] [[PARAM1]], i[[SZ]] [[PARAM2]], i[[SZ]] 
[[PARAM3]])
 //
 //
-// CHECK:   define internal {{.*}}void [[OMP_OUTLINED3]](i32* noalias 
%.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}})
+// CHECK:   define internal {{.*}}void [[OMP_OUTLINED3]](i32* noalias 
%.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, 
i[[SZ]] %{{.+}})
 // CHECK:   [[A_ADDR:%.+]] = alloca i[[SZ]], align
 // CHECK:   [[AA_ADDR:%.+]] = alloca i[[SZ]], align
+// CHECK:   [[GLOBAL_ADDR:%.+]] = alloca i[[SZ]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align
+// CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[GLOBAL_ADDR]], align
 // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32*
 // CHECK-DAG:   [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16*
+// CHECK-64-DAG:[[GLOBAL_CADDR:%.+]] = bitcast i[[SZ]]* [[GLOBAL_ADDR]] to i32*
+// CHECK-64:store i32 {{.+}}, i32* [[GLOBAL_CADDR]],
+// CHECK-32:store i32 {{.+}}, i32* [[GLOBAL_ADDR]],
 // CHECK:   ret void
 // CHECK-NEXT:  }
 


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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Kostya Serebryany via Phabricator via cfe-commits
kcc accepted this revision.
kcc added a comment.

LGTM


https://reviews.llvm.org/D37156



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


r312026 - [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 12:48:12 2017
New Revision: 312026

URL: http://llvm.org/viewvc/llvm-project?rev=312026&view=rev
Log:
[SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

Summary:
- Don't sanitize __sancov_lowest_stack.
- Don't instrument leaf functions.
- Add CoverageStackDepth to Fuzzer and FuzzerNoLink.
- Disable stack depth tracking on Mac.

Reviewers: vitalybuka, kcc, george.karpenkov

Reviewed By: kcc

Subscribers: kubamracek, cfe-commits, llvm-commits, hiraditya

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

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312026&r1=312025&r2=312026&view=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 12:48:12 2017
@@ -291,9 +291,13 @@ SanitizerArgs::SanitizerArgs(const ToolC
 Add |= FuzzerNoLink;
 
   // Enable coverage if the fuzzing flag is set.
-  if (Add & FuzzerNoLink)
+  if (Add & FuzzerNoLink) {
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
+// Due to TLS differences, stack depth tracking is disabled on Mac.
+if (!TC.getTriple().isOSDarwin())
+  CoverageFeatures |= CoverageStackDepth;
+  }
 
   Kinds |= Add;
 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {


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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312026: [SanitizeCoverage] Enable stack-depth coverage for 
-fsanitize=fuzzer (authored by morehouse).

Changed prior to commit:
  https://reviews.llvm.org/D37156?vs=113133&id=113136#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37156

Files:
  cfe/trunk/lib/Driver/SanitizerArgs.cpp
  compiler-rt/trunk/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/trunk/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/trunk/test/fuzzer/deep-recursion.test
  llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function &F,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function &F, ArrayRef AllBlocks);
+  bool InjectCoverage(Function &F, ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function &F, Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function &F, ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function &F, ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
+  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   &getAnalysis(F).getDomTree();
   const PostDominatorTree *PDT =
   &getAnalysis(F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto &BB : F) {
 if (shouldInstrumentBlock

r312029 - Minimal runtime for UBSan.

2017-08-29 Thread Evgeniy Stepanov via cfe-commits
Author: eugenis
Date: Tue Aug 29 13:03:51 2017
New Revision: 312029

URL: http://llvm.org/viewvc/llvm-project?rev=312029&view=rev
Log:
Minimal runtime for UBSan.

Summary:
An implementation of ubsan runtime library suitable for use in production.

Minimal attack surface.
* No stack traces.
* Definitely no C++ demangling.
* No UBSAN_OPTIONS=log_file=/path (very suid-unfriendly). And no UBSAN_OPTIONS 
in general.
* as simple as possible

Minimal CPU and RAM overhead.
* Source locations unnecessary in the presence of (split) debug info.
* Values and types (as in A+B overflows T) can be reconstructed from 
register/stack dumps, once you know what type of error you are looking at.
* above two items save 3% binary size.

When UBSan is used with -ftrap-function=abort, sometimes it is hard to reason 
about failures. This library replaces abort with a slightly more informative 
message without much extra overhead. Since ubsan interface in not stable, this 
code must reside in compiler-rt.

Reviewers: pcc, kcc

Subscribers: srhines, mgorny, aprantl, krytarowski, llvm-commits

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

Added:
cfe/trunk/test/CodeGen/unsigned-overflow-minimal.c
Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/include/clang/Driver/SanitizerArgs.h
cfe/trunk/include/clang/Frontend/CodeGenOptions.def
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/Driver/SanitizerArgs.cpp
cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/Driver/fsanitize.c
cfe/trunk/test/Driver/sanitizer-ld.c

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=312029&r1=312028&r2=312029&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Tue Aug 29 13:03:51 2017
@@ -885,6 +885,10 @@ def fsanitize_undefined_trap_on_error :
 Group;
 def fno_sanitize_undefined_trap_on_error : Flag<["-"], 
"fno-sanitize-undefined-trap-on-error">,
Group;
+def fsanitize_minimal_runtime : Flag<["-"], "fsanitize-minimal-runtime">,
+Group;
+def fno_sanitize_minimal_runtime : Flag<["-"], "fno-sanitize-minimal-runtime">,
+Group;
 def fsanitize_link_cxx_runtime : Flag<["-"], "fsanitize-link-c++-runtime">,
  Group;
 def fsanitize_cfi_cross_dso : Flag<["-"], "fsanitize-cfi-cross-dso">,

Modified: cfe/trunk/include/clang/Driver/SanitizerArgs.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/SanitizerArgs.h?rev=312029&r1=312028&r2=312029&view=diff
==
--- cfe/trunk/include/clang/Driver/SanitizerArgs.h (original)
+++ cfe/trunk/include/clang/Driver/SanitizerArgs.h Tue Aug 29 13:03:51 2017
@@ -43,6 +43,7 @@ class SanitizerArgs {
   bool TsanMemoryAccess = true;
   bool TsanFuncEntryExit = true;
   bool TsanAtomics = true;
+  bool MinimalRuntime = false;
 
  public:
   /// Parses the sanitizer arguments from an argument list.
@@ -58,6 +59,7 @@ class SanitizerArgs {
!Sanitizers.has(SanitizerKind::Address);
   }
   bool needsUbsanRt() const;
+  bool requiresMinimalRuntime() const { return MinimalRuntime; }
   bool needsDfsanRt() const { return Sanitizers.has(SanitizerKind::DataFlow); }
   bool needsSafeStackRt() const { return SafeStackRuntime; }
   bool needsCfiRt() const;

Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.def?rev=312029&r1=312028&r2=312029&view=diff
==
--- cfe/trunk/include/clang/Frontend/CodeGenOptions.def (original)
+++ cfe/trunk/include/clang/Frontend/CodeGenOptions.def Tue Aug 29 13:03:51 2017
@@ -152,6 +152,8 @@ CODEGENOPT(SanitizeMemoryTrackOrigins, 2
 CODEGENOPT(SanitizeMemoryUseAfterDtor, 1, 0) ///< Enable use-after-delete 
detection
  ///< in MemorySanitizer
 CODEGENOPT(SanitizeCfiCrossDso, 1, 0) ///< Enable cross-dso support in CFI.
+CODEGENOPT(SanitizeMinimalRuntime, 1, 0) ///< Use "_minimal" sanitizer runtime 
for
+ ///< diagnostics.
 CODEGENOPT(SanitizeCoverageType, 2, 0) ///< Type of sanitizer coverage
///< instrumentation.
 CODEGENOPT(SanitizeCoverageIndirectCalls, 1, 0) ///< Enable sanitizer coverage

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=312029&r1=312028&r2=312029&view=diff
===

[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

IMHO it was a very bad idea to include the "architecture name" (not even a 
target triple!) in the library path in the first place. No one else does that. 
GCC made the right choice and called theirs "libasan.so".

My plan is to tweak the code that sets the library name to use i686 when the 
target is i386 and the os is android, both in compiler-rt and in clang. There 
will be no duplicate targets.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


r312032 - Disable stack depth tracking on Windows.

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 13:44:41 2017
New Revision: 312032

URL: http://llvm.org/viewvc/llvm-project?rev=312032&view=rev
Log:
Disable stack depth tracking on Windows.

Windows doesn't support the tls_model attribute.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312032&r1=312031&r2=312032&view=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 13:44:41 2017
@@ -315,8 +315,8 @@ SanitizerArgs::SanitizerArgs(const ToolC
   if (Add & FuzzerNoLink) {
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
-// Due to TLS differences, stack depth tracking is disabled on Mac.
-if (!TC.getTriple().isOSDarwin())
+// Due to TLS differences, stack depth tracking is disabled on Mac/Win.
+if (!TC.getTriple().isOSDarwin() && !TC.getTriple().isOSWindows())
   CoverageFeatures |= CoverageStackDepth;
   }
 


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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In https://reviews.llvm.org/D37042#855713, @efriedma wrote:

> I didn't think of this earlier, but strictly speaking, I think 
> "(char*)nullptr+0" isn't undefined in C++?


Yes, that's correct. (C++'s model is basically equivalent to having an object 
of size zero at the null address, so things like `(char*)nullptr - 
(char*)nullptr` and `(char*)nullptr + 0` are valid.)

> But probably worth emitting the warning anyway; anyone writing out arithmetic 
> on null is probably doing something suspicious, even if it isn't technically 
> undefined.

I agree. We should probably suppress the warning if the non-pointer operand is 
known to be zero in C++, and weaken the wording slightly "[..] has undefined 
behavior if offset is nonzero" otherwise, though.




Comment at: include/clang/Basic/DiagnosticSemaKinds.td:6032
+def ext_gnu_null_ptr_arith : Extension<
+  "inttoptr casting using arithmetic on a null pointer is a GNU extension">,
+  InGroup;

efriedma wrote:
> The keyword "inttoptr" is part of LLVM, not something we expect users to 
> understand.
How about something like "arithmetic on null pointer treated as cast from 
integer to pointer as a GNU extension"?



Comment at: lib/Sema/SemaExpr.cpp:8799
 
+  // Adding to a null pointer is never an error, but should warn.
+  if (PExp->IgnoreParenCasts()->isNullPointerConstant(Context, 

Maybe `// Adding to a null pointer results in undefined behavior.` to explain 
why we warn (a reader of the code can already see that we do warn in this case).



Comment at: lib/Sema/SemaExpr.cpp:8805
+const PointerType *pointerType = PExp->getType()->getAs();
+if (!IExp->isIntegerConstantExpr(Context) &&
+pointerType->getPointeeType()->isCharType() &&

It seems strange to me to disable this when the RHS is an ICE. If we're going 
to support this as an extension, we should make the rules for it as simple as 
we reasonably can; this ICE check seems like an unnecessary complication.


https://reviews.llvm.org/D37042



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In https://reviews.llvm.org/D26764#855791, @eugenis wrote:

> IMHO it was a very bad idea to include the "architecture name" (not even a 
> target triple!) in the library path in the first place. No one else does 
> that. GCC made the right choice and called theirs "libasan.so".
>
> My plan is to tweak the code that sets the library name to use i686 when the 
> target is i386 and the os is android, both in compiler-rt and in clang. There 
> will be no duplicate targets.


Sounds good to me. Let me know if you think this will take a while and we 
should revert to green in the meantime.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


r312037 - Re-enable stack depth instrumentation on Windows.

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 14:15:33 2017
New Revision: 312037

URL: http://llvm.org/viewvc/llvm-project?rev=312037&view=rev
Log:
Re-enable stack depth instrumentation on Windows.

Specified tls_model attribute properly. Should compile on Windows
now.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312037&r1=312036&r2=312037&view=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 14:15:33 2017
@@ -315,8 +315,8 @@ SanitizerArgs::SanitizerArgs(const ToolC
   if (Add & FuzzerNoLink) {
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
-// Due to TLS differences, stack depth tracking is disabled on Mac/Win.
-if (!TC.getTriple().isOSDarwin() && !TC.getTriple().isOSWindows())
+// Due to TLS differences, stack depth tracking is disabled on Mac.
+if (!TC.getTriple().isOSDarwin())
   CoverageFeatures |= CoverageStackDepth;
   }
 


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


[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis created this revision.
Herald added a subscriber: srhines.

Recent changes canonicalized clang_rt library names to refer to
"i386" on all x86 targets. Android historically uses i686.

This change adds a special case to keep i686 in all clang_rt
libraries when targeting Android.


https://reviews.llvm.org/D37278

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/test/Driver/sanitizer-ld.c
  compiler-rt/cmake/Modules/AddCompilerRT.cmake


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} 
${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} 
${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: clang/test/Driver/sanitizer-ld.c
===
--- clang/test/Driver/sanitizer-ld.c
+++ clang/test/Driver/sanitizer-ld.c
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -305,6 +305,9 @@
? "armhf"
: "arm";
 
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} ${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} ${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_

[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 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.

Thanks! Looks good to me.




Comment at: clang/lib/Driver/ToolChain.cpp:308
 
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";

Maybe add a comment here explaining that this is for historical reasons. Or in 
the cmake file below (or both).


https://reviews.llvm.org/D37278



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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov updated this revision to Diff 113166.
anatol.pomozov edited the summary of this revision.

https://reviews.llvm.org/D36272

Files:
  include/clang/Basic/Attr.td
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/function-attributes.c


Index: test/CodeGen/function-attributes.c
===
--- test/CodeGen/function-attributes.c
+++ test/CodeGen/function-attributes.c
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm 
-disable-llvm-passes -Os -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm 
-disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm 
-disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
 // CHECK: define signext i8 @f0(i32 %x) [[NUW:#[0-9]+]]
 // CHECK: define zeroext i8 @f1(i32 %x) [[NUW]]
 // CHECK: define void @f2(i8 signext %x) [[NUW]]
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -2297,6 +2297,15 @@
 if (!IsForDefinition)
   return;
 if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+  if (FD->hasAttr()) {
+// Get the LLVM function.
+auto *Fn = cast(GV);
+
+// Now add the 'alignstack' attribute with a value of 16.
+llvm::AttrBuilder B;
+B.addStackAlignmentAttr(16);
+Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+  }
   if (FD->hasAttr()) {
 llvm::Function *Fn = cast(GV);
 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
@@ -2425,6 +2434,15 @@
   if (!IsForDefinition)
 return;
   if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+if (FD->hasAttr()) {
+  // Get the LLVM function.
+  auto *Fn = cast(GV);
+
+  // Now add the 'alignstack' attribute with a value of 16.
+  llvm::AttrBuilder B;
+  B.addStackAlignmentAttr(16);
+  Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+}
 if (FD->hasAttr()) {
   llvm::Function *Fn = cast(GV);
   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -2042,7 +2042,7 @@
   let Documentation = [AnyX86NoCallerSavedRegistersDocs];
 }
 
-def X86ForceAlignArgPointer : InheritableAttr, TargetSpecificAttr {
+def X86ForceAlignArgPointer : InheritableAttr, 
TargetSpecificAttr {
   let Spellings = [GNU<"force_align_arg_pointer">];
   // Technically, this appertains to a FunctionDecl, but the target-specific
   // code silently allows anything function-like (such as typedefs or function


Index: test/CodeGen/function-attributes.c
===
--- test/CodeGen/function-attributes.c
+++ test/CodeGen/function-attributes.c
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -disable-llvm-passes -Os -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
 // CHECK: define signext i8 @f0(i32 %x) [[NUW:#[0-9]+]]
 // CHECK: define zeroext i8 @f1(i32 %x) [[NUW]]
 // CHECK: define void @f2(i8 signext %x) [[NUW]]
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -2297,6 +2297,15 @@
 if (!IsForDefinition)
   return;
 if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+  if (FD->hasAttr()) {
+// Get the LLVM function.
+auto *Fn = cast(GV);
+
+// Now add the 'alignstack' attribute with a value of 16.
+llvm::AttrBuilder B;
+B.addStackAlignmentAttr(16);
+Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+  }
   if (FD->hasAttr()) {
 llvm::Function *Fn = cast(GV);
 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
@@ -2425,6 +2434,15 @@
   if (!IsForDefinition)
 return;
   if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+if (FD->hasAttr()) {
+  // Get the LLVM function.
+  auto *Fn = cast(GV);
+
+  // Now add the 'alignstack' attribute with a value of 16.
+  llvm::AttrBuilder B;
+  B.addStackAlignmentAttr(16);
+  Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+}
 if (FD->hasAttr()) {
   llvm::Function *Fn = cast(GV);
   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -2042,7 +2042,7 @@
   let Documentation = [AnyX86NoCallerSavedRegistersDocs];
 }

r312047 - Revert "[SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer"

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 14:56:56 2017
New Revision: 312047

URL: http://llvm.org/viewvc/llvm-project?rev=312047&view=rev
Log:
Revert "[SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer"

This reverts r312026 due to bot breakage.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312047&r1=312046&r2=312047&view=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 14:56:56 2017
@@ -312,13 +312,9 @@ SanitizerArgs::SanitizerArgs(const ToolC
 Add |= FuzzerNoLink;
 
   // Enable coverage if the fuzzing flag is set.
-  if (Add & FuzzerNoLink) {
+  if (Add & FuzzerNoLink)
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
-// Due to TLS differences, stack depth tracking is disabled on Mac.
-if (!TC.getTriple().isOSDarwin())
-  CoverageFeatures |= CoverageStackDepth;
-  }
 
   Kinds |= Add;
 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {


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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Did you figure out why this doesn't work on windows?  Not having the 
windows-specific x64 test seems like a mistake, unless we're going to make this 
a linux-only attribute.  In which case, you'll have to remove this attribute in 
the 32-bit windows case.


https://reviews.llvm.org/D36272



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


[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis updated this revision to Diff 113167.
eugenis added a comment.

+comment


https://reviews.llvm.org/D37278

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/test/Driver/sanitizer-ld.c
  compiler-rt/cmake/Modules/AddCompilerRT.cmake


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} 
${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} 
${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: clang/test/Driver/sanitizer-ld.c
===
--- clang/test/Driver/sanitizer-ld.c
+++ clang/test/Driver/sanitizer-ld.c
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -305,6 +305,10 @@
? "armhf"
: "arm";
 
+  // For historic reasons, Android library is using i686 instead of i386.
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} ${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} ${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: clang/test/Driver

[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov added a comment.

The function-attributes.c test  does not pass at Windows 
 even without my patch. Unfortunately I 
am not familiar with clang enough to debug this issue.


https://reviews.llvm.org/D36272



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


r312048 - Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgeniy Stepanov via cfe-commits
Author: eugenis
Date: Tue Aug 29 15:12:31 2017
New Revision: 312048

URL: http://llvm.org/viewvc/llvm-project?rev=312048&view=rev
Log:
Restore clang_rt library name on i686-android.

Summary:
Recent changes canonicalized clang_rt library names to refer to
"i386" on all x86 targets. Android historically uses i686.

This change adds a special case to keep i686 in all clang_rt
libraries when targeting Android.

Reviewers: hans, mgorny, beanz

Subscribers: srhines, cfe-commits, llvm-commits

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

Modified:
cfe/trunk/lib/Driver/ToolChain.cpp
cfe/trunk/test/Driver/sanitizer-ld.c

Modified: cfe/trunk/lib/Driver/ToolChain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChain.cpp?rev=312048&r1=312047&r2=312048&view=diff
==
--- cfe/trunk/lib/Driver/ToolChain.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChain.cpp Tue Aug 29 15:12:31 2017
@@ -305,6 +305,10 @@ static StringRef getArchNameForCompilerR
? "armhf"
: "arm";
 
+  // For historic reasons, Android library is using i686 instead of i386.
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 

Modified: cfe/trunk/test/Driver/sanitizer-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/sanitizer-ld.c?rev=312048&r1=312047&r2=312048&view=diff
==
--- cfe/trunk/test/Driver/sanitizer-ld.c (original)
+++ cfe/trunk/test/Driver/sanitizer-ld.c Tue Aug 29 15:12:31 2017
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \


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


[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312048: Restore clang_rt library name on i686-android. 
(authored by eugenis).

Changed prior to commit:
  https://reviews.llvm.org/D37278?vs=113167&id=113170#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37278

Files:
  cfe/trunk/lib/Driver/ToolChain.cpp
  cfe/trunk/test/Driver/sanitizer-ld.c
  compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake


Index: compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} 
${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} 
${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: cfe/trunk/test/Driver/sanitizer-ld.c
===
--- cfe/trunk/test/Driver/sanitizer-ld.c
+++ cfe/trunk/test/Driver/sanitizer-ld.c
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \
Index: cfe/trunk/lib/Driver/ToolChain.cpp
===
--- cfe/trunk/lib/Driver/ToolChain.cpp
+++ cfe/trunk/lib/Driver/ToolChain.cpp
@@ -305,6 +305,10 @@
? "armhf"
: "arm";
 
+  // For historic reasons, Android library is using i686 instead of i386.
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 


Index: compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} ${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} ${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${

[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

I've landed the android special case in r312048


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


  1   2   >