[PATCH] D36685: [clang-diff] HTML diff navigation

2017-08-23 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

LGTM. There are some unrelated highlighting bugs in HTML though, for example if 
you take:

before:

  int foo();
  
  void bar(int x) {
switch (x) {
case 0:
  bar(2);
}
  }

after:

  void bar(int x) {
switch (x) {
case 4:
  bar(2);
  break;
case 1:
  bar(3);
  break;
}
  }
  
  int foo();
  
  int zed();

Then first time `bar` is selected in the new source the whole function is 
highlighted. Then, if you select `4` in the new source and then re-select the 
function `bar` again, `bar` is highlighted, but there's a gap where `4` is.


https://reviews.llvm.org/D36685



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


r311532 - [clang-format] Align trailing comments if ColumnLimit is 0

2017-08-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Aug 23 00:18:36 2017
New Revision: 311532

URL: http://llvm.org/viewvc/llvm-project?rev=311532&view=rev
Log:
[clang-format] Align trailing comments if ColumnLimit is 0

Summary:
ColumnLimit = 0 means no limit, so comment should always be aligned if 
requested. This was broken with

  https://llvm.org/svn/llvm-project/cfe/trunk@304687

introduced via

  https://reviews.llvm.org/D33830

and is included in 5.0.0-rc2. This commit fixes it and adds a unittest for this 
property.

Should go into clang-5.0 IMHO.

Contributed by @pboettch!

Reviewers: djasper, krasimir

Reviewed By: djasper, krasimir

Subscribers: hans, klimek

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

Modified:
cfe/trunk/lib/Format/WhitespaceManager.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp

Modified: cfe/trunk/lib/Format/WhitespaceManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/WhitespaceManager.cpp?rev=311532&r1=311531&r2=311532&view=diff
==
--- cfe/trunk/lib/Format/WhitespaceManager.cpp (original)
+++ cfe/trunk/lib/Format/WhitespaceManager.cpp Wed Aug 23 00:18:36 2017
@@ -472,9 +472,14 @@ void WhitespaceManager::alignTrailingCom
   continue;
 
 unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
-unsigned ChangeMaxColumn = Style.ColumnLimit >= Changes[i].TokenLength
-   ? Style.ColumnLimit - Changes[i].TokenLength
-   : ChangeMinColumn;
+unsigned ChangeMaxColumn;
+
+if (Style.ColumnLimit == 0)
+  ChangeMaxColumn = UINT_MAX;
+else if (Style.ColumnLimit >= Changes[i].TokenLength)
+  ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
+else
+  ChangeMaxColumn = ChangeMinColumn;
 
 // If we don't create a replacement for this change, we have to consider
 // it to be immovable.

Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=311532&r1=311531&r2=311532&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp Wed Aug 23 00:18:36 2017
@@ -2476,6 +2476,13 @@ TEST_F(FormatTestComments, AlignTrailing
"int k; // line longg long",
getLLVMStyleWithColumns(20)));
 
+  // Always align if ColumnLimit = 0
+  EXPECT_EQ("int i, j; // line 1\n"
+"int k;// line longg long",
+format("int i, j; // line 1\n"
+   "int k; // line longg long",
+   getLLVMStyleWithColumns(0)));
+
   // Align comment line sections aligned with the next token with the next
   // token.
   EXPECT_EQ("class A {\n"


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


[PATCH] D34984: Store token literal data in PCH. Avoids disk read on PreProc expansion.

2017-08-23 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev updated this revision to Diff 112303.
v.g.vassilev added a comment.

Fix StringRef allocation.


https://reviews.llvm.org/D34984

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


Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -4364,6 +4364,8 @@
   Record.push_back(Tok.getKind());
   // FIXME: Should translate token flags to a stable encoding.
   Record.push_back(Tok.getFlags());
+  if (Tok.isLiteral())
+AddString(StringRef(Tok.getLiteralData(), Tok.getLength()), Record);
 }
 
 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Index: lib/Serialization/ASTReader.cpp
===
--- lib/Serialization/ASTReader.cpp
+++ lib/Serialization/ASTReader.cpp
@@ -1508,6 +1508,12 @@
 Tok.setIdentifierInfo(II);
   Tok.setKind((tok::TokenKind)Record[Idx++]);
   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
+  if (Tok.isLiteral()) {
+const RecordData &RD = reinterpret_cast(Record);
+std::string *Lit = new std::string(ReadString(RD, Idx));
+TokenLiteralDataLoaded.push_back(Lit);
+Tok.setLiteralData(Lit->c_str());
+  }
   return Tok;
 }
 
@@ -10372,6 +10378,9 @@
 ASTReader::~ASTReader() {
   if (OwnsDeserializationListener)
 delete DeserializationListener;
+  for (auto PStr : TokenLiteralDataLoaded) {
+delete PStr;
+  }
 }
 
 IdentifierResolver &ASTReader::getIdResolver() {
Index: include/clang/Serialization/ASTReader.h
===
--- include/clang/Serialization/ASTReader.h
+++ include/clang/Serialization/ASTReader.h
@@ -612,6 +612,9 @@
   /// files.
   llvm::DenseSet LoadedUndefs;
 
+  /// \brief Token literal data loaded and owned by us.
+  std::vector TokenLiteralDataLoaded;
+
   typedef ContinuousRangeMap
 GlobalMacroMapType;
 


Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -4364,6 +4364,8 @@
   Record.push_back(Tok.getKind());
   // FIXME: Should translate token flags to a stable encoding.
   Record.push_back(Tok.getFlags());
+  if (Tok.isLiteral())
+AddString(StringRef(Tok.getLiteralData(), Tok.getLength()), Record);
 }
 
 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Index: lib/Serialization/ASTReader.cpp
===
--- lib/Serialization/ASTReader.cpp
+++ lib/Serialization/ASTReader.cpp
@@ -1508,6 +1508,12 @@
 Tok.setIdentifierInfo(II);
   Tok.setKind((tok::TokenKind)Record[Idx++]);
   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
+  if (Tok.isLiteral()) {
+const RecordData &RD = reinterpret_cast(Record);
+std::string *Lit = new std::string(ReadString(RD, Idx));
+TokenLiteralDataLoaded.push_back(Lit);
+Tok.setLiteralData(Lit->c_str());
+  }
   return Tok;
 }
 
@@ -10372,6 +10378,9 @@
 ASTReader::~ASTReader() {
   if (OwnsDeserializationListener)
 delete DeserializationListener;
+  for (auto PStr : TokenLiteralDataLoaded) {
+delete PStr;
+  }
 }
 
 IdentifierResolver &ASTReader::getIdResolver() {
Index: include/clang/Serialization/ASTReader.h
===
--- include/clang/Serialization/ASTReader.h
+++ include/clang/Serialization/ASTReader.h
@@ -612,6 +612,9 @@
   /// files.
   llvm::DenseSet LoadedUndefs;
 
+  /// \brief Token literal data loaded and owned by us.
+  std::vector TokenLiteralDataLoaded;
+
   typedef ContinuousRangeMap
 GlobalMacroMapType;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37023: [analyzer] Fix bugreporter::getDerefExpr() again.

2017-08-23 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hi Artem,
I have a question after quick look. The original code considered `ParenExpr`s 
but I cannot find nothing paren-related in the patch. Is case `(x->y).z` 
handled as expected?


https://reviews.llvm.org/D37023



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


[PATCH] D37023: [analyzer] Fix bugreporter::getDerefExpr() again.

2017-08-23 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Yeah, line 86.


https://reviews.llvm.org/D37023



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


[PATCH] D37023: [analyzer] Fix bugreporter::getDerefExpr() again.

2017-08-23 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Sorry, missed that.


https://reviews.llvm.org/D37023



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


[PATCH] D36664: [analyzer] Make StmtDataCollector customizable

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

Sorry for the delay, was on vacation.

> Since StmtDataCollectors.inc resides in lib I have to use relative paths (so 
> the include directive looks different depending on the current file), we have 
> to live with this, right?

That's right, but do we want this to be in `lib/` ? There users can't access 
this code to build their own DataCollector (at least when they build against an 
installed clang version where this inc file doesn't get installed). And if 
someone uses this file from a clang header by accident we get errors about this 
missing file with installed clang versions (and I think the build bots don't 
perform install tests, so it probably breaks silently).

We probably also can't just move it into `include/` because `*.inc` files there 
break some CMake sanity checks IIRC, so I think the best way forward is to 
tablegen this file which also makes the `StmtDataCollectors.inc` file more 
readable.

> These things should be documented in DataCollection.h I guess.

Agreed, could you do that?

I think this can go in with just these documentation changes (especially since 
its GSoC related and we're in the last week), so please add them and then LGTM. 
Stable hashes and tablegen can be a follow-up patches.


https://reviews.llvm.org/D36664



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


[PATCH] D36836: [clang-tidy] Implement readability-function-cognitive-complexity check

2017-08-23 Thread Roman Lebedev via cfe-commits
Since i initially forgot to include cfe-commits as a subscriber into
the review, the first mail was not sent to the list.
So maybe, for history and clarity, i should forward the mail to the list:
(i'm keeping the reviewers as CC since phabricator, unlike github,
does not add mail-based reviews as comments...)

On Thu, Aug 17, 2017 at 6:57 PM, Roman Lebedev via Phabricator
 wrote:

lebedev.ri created this revision.
lebedev.ri added a project: clang-tools-extra.
Herald added subscribers: xazax.hun, JDevlieghere, mgorny.

Currently, there is basically just one clang-tidy check to impose some
sanity limits on functions - `clang-tidy-readability-function-size`.
It is nice, allows to limit line count, total number of statements,
number of branches, number of function parameters (not counting
implicit `this`), nesting level.
However, those are simple generic metrics. It is still trivially
possible to write a function, which does not violate any of these
metrics, yet is still rather unreadable.

Thus, some additional, slightly more complicated metric is needed.
There is a well-known Cyclomatic complexity
, but certainly
has its downsides.
And there is a COGNITIVE COMPLEXITY by SonarSource
, which is
available for opensource on https://sonarcloud.io/.
I did ask them, and received an answer that it is it can be
implemented in clang-tidy.

This check checks function Cognitive Complexity metric, and flags the
functions with Cognitive Complexity exceeding the configured limit.
The default limit is `25`, same as in 'upstream'.

The metric is implemented as per COGNITIVE COMPLEXITY by SonarSource

specification version 1.2 (19 April 2017), with two notable
exceptions:

- `preprocessor conditionals` (`#ifdef`, `#if`, `#elif`, `#else`,
`#endif`) are not accounted for. Could be done. Currently, upstream
does not account for them either.
- `each method in a recursion cycle` is not accounted for. It can't be
fully implemented, because cross-translational-unit analysis would be
needed, which is not possible in clang-tidy. Thus, at least right now,
i completely avoided implementing it.


Repository:
  rL LLVM

https://reviews.llvm.org/D36836

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
  clang-tidy/readability/FunctionCognitiveComplexityCheck.h
  clang-tidy/readability/ReadabilityTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-function-cognitive-complexity.rst
  test/clang-tidy/check_clang_tidy.py
  test/clang-tidy/readability-function-cognitive-complexity.cpp
Index: test/clang-tidy/readability-function-cognitive-complexity.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-function-cognitive-complexity.cpp
@@ -0,0 +1,549 @@
+// RUN: %check_clang_tidy %s readability-function-cognitive-complexity %t -- -config='{CheckOptions: [{key: readability-function-cognitive-complexity.Threshold, value: 0}]}' -- -std=c++11
+
+// any function should be checked.
+
+extern int ext_func(int x = 0);
+
+int some_func(int x = 0);
+
+static int some_other_func(int x = 0) {}
+
+template void some_templ_func(T x = 0) {}
+
+class SomeClass {
+public:
+  int *begin(int x = 0);
+  int *end(int x = 0);
+  static int func(int x = 0);
+  template void some_templ_func(T x = 0) {}
+};
+
+// nothing ever decreases cognitive complexity, so we can check all the things
+// in one go. none of the following should increase cognitive complexity:
+void unittest_false() {
+  {};
+  ext_func();
+  some_func();
+  some_other_func();
+  some_templ_func();
+  some_templ_func();
+  SomeClass::func();
+  SomeClass C;
+  C.some_templ_func();
+  C.some_templ_func();
+  C.func();
+  C.end();
+  int i = some_func();
+  i = i;
+  i++;
+  --i;
+  i < 0;
+  int j = 0 ?: 1;
+  auto k = new int;
+  delete k;
+  throw i;
+end:
+  return;
+}
+
+////
+//-- B1. Increments --//
+////
+// Check that every thing listed in B1 of the specification does indeed   //
+// recieve the base increment, and that not-body does not increase nesting//
+////
+
+// break does not increase cognitive complexity.
+// only  break LABEL  does, but it is unavaliable in C or C++
+
+// continue does not increase cognitive complexity.
+// only  continue LABEL  does, but it is unavaliable in C or C++
+
+void unittest_b1_00() {
+// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_00' has cognitive complexity of 5 (threshold 0) [readability-function-cognitive-co

[PATCH] D36969: [Basic] Add a DiagnosticError llvm::ErrorInfo subclass

2017-08-23 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman marked 2 inline comments as done.
arphaman added a comment.

In https://reviews.llvm.org/D36969#848906, @vsk wrote:

> Nice! I'd like to get your thoughts on two candidate ergonomic changes:


Makes sense, I've added two similar helper functions in the updated patch.


Repository:
  rL LLVM

https://reviews.llvm.org/D36969



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


[PATCH] D36969: [Basic] Add a DiagnosticError llvm::ErrorInfo subclass

2017-08-23 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman updated this revision to Diff 112327.
arphaman added a comment.

Add helper functions as suggested by Vedant.


Repository:
  rL LLVM

https://reviews.llvm.org/D36969

Files:
  include/clang/Basic/DiagnosticError.h
  lib/Basic/Diagnostic.cpp
  unittests/Basic/DiagnosticTest.cpp

Index: unittests/Basic/DiagnosticTest.cpp
===
--- unittests/Basic/DiagnosticTest.cpp
+++ unittests/Basic/DiagnosticTest.cpp
@@ -8,6 +8,7 @@
 //===--===//
 
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticError.h"
 #include "clang/Basic/DiagnosticIDs.h"
 #include "gtest/gtest.h"
 
@@ -72,4 +73,25 @@
   }
 }
 
+TEST(DiagnosticTest, diagnosticError) {
+  DiagnosticsEngine Diags(new DiagnosticIDs(), new DiagnosticOptions,
+  new IgnoringDiagConsumer());
+  PartialDiagnostic::StorageAllocator Alloc;
+  llvm::Expected> Value = DiagnosticError::create(
+  SourceLocation(), PartialDiagnostic(diag::err_cannot_open_file, Alloc)
+<< "file"
+<< "error");
+  ASSERT_TRUE(!Value);
+  llvm::Error Err = Value.takeError();
+  Optional ErrDiag = DiagnosticError::take(Err);
+  llvm::cantFail(std::move(Err));
+  ASSERT_FALSE(!ErrDiag);
+  EXPECT_EQ(ErrDiag->first, SourceLocation());
+  EXPECT_EQ(ErrDiag->second.getDiagID(), diag::err_cannot_open_file);
+
+  Value = std::make_pair(20, 1);
+  ASSERT_FALSE(!Value);
+  EXPECT_EQ(*Value, std::make_pair(20, 1));
+  EXPECT_EQ(Value->first, 20);
+}
 }
Index: lib/Basic/Diagnostic.cpp
===
--- lib/Basic/Diagnostic.cpp
+++ lib/Basic/Diagnostic.cpp
@@ -11,8 +11,9 @@
 //
 //===--===//
 
-#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/CharInfo.h"
+#include "clang/Basic/DiagnosticError.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/PartialDiagnostic.h"
@@ -1050,3 +1051,5 @@
   llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
  "A partial is on the lam");
 }
+
+char DiagnosticError::ID;
Index: include/clang/Basic/DiagnosticError.h
===
--- /dev/null
+++ include/clang/Basic/DiagnosticError.h
@@ -0,0 +1,61 @@
+//===--- DiagnosticError.h - Diagnostic payload for llvm::Error -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_ERROR_H
+#define LLVM_CLANG_BASIC_DIAGNOSTIC_ERROR_H
+
+#include "clang/Basic/PartialDiagnostic.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+
+/// \brief Carries a Clang diagnostic in an llvm::Error.
+///
+/// Users should emit the stored diagnostic using the DiagnosticsEngine.
+class DiagnosticError : public llvm::ErrorInfo {
+public:
+  DiagnosticError(PartialDiagnosticAt Diag) : Diag(std::move(Diag)) {}
+
+  void log(raw_ostream &OS) const override { OS << "clang diagnostic"; }
+
+  PartialDiagnosticAt &getDiagnostic() { return Diag; }
+  const PartialDiagnosticAt &getDiagnostic() const { return Diag; }
+
+  /// Creates a new \c DiagnosticError that contains the given diagnostic at
+  /// the given location.
+  static llvm::Error create(SourceLocation Loc, PartialDiagnostic Diag) {
+return llvm::make_error(
+PartialDiagnosticAt(Loc, std::move(Diag)));
+  }
+
+  /// Extracts and returns the diagnostic payload from the given \c Error if
+  /// the error is a \c DiagnosticError. Returns none if the given error is not
+  /// a \c DiagnosticError.
+  static Optional take(llvm::Error &Err) {
+Optional Result;
+Err = llvm::handleErrors(std::move(Err), [&](DiagnosticError &E) {
+  Result = std::move(E.getDiagnostic());
+});
+return Result;
+  }
+
+  static char ID;
+
+private:
+  // Users are not expected to use error_code.
+  std::error_code convertToErrorCode() const override {
+return llvm::inconvertibleErrorCode();
+  }
+
+  PartialDiagnosticAt Diag;
+};
+
+} // end namespace clang
+
+#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_ERROR_H
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r311544 - Fix typos, remove unused private members of CommonOptionsParser, NFC

2017-08-23 Thread Johannes Altmanninger via cfe-commits
Author: krobelus
Date: Wed Aug 23 03:43:26 2017
New Revision: 311544

URL: http://llvm.org/viewvc/llvm-project?rev=311544&view=rev
Log:
Fix typos, remove unused private members of CommonOptionsParser, NFC

Modified:
cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
cfe/trunk/include/clang/AST/TypeNodes.def
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/include/clang/Analysis/CloneDetection.h
cfe/trunk/include/clang/Tooling/CommonOptionsParser.h
cfe/trunk/include/clang/Tooling/CompilationDatabase.h
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/RecursiveASTVisitor.h?rev=311544&r1=311543&r2=311544&view=diff
==
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h (original)
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h Wed Aug 23 03:43:26 2017
@@ -83,7 +83,7 @@ namespace clang {
   return false;
\
   } while (false)
 
-/// \brief A class that does preordor or postorder
+/// \brief A class that does preorder or postorder
 /// depth-first traversal on the entire Clang AST and visits each node.
 ///
 /// This class performs three distinct tasks:

Modified: cfe/trunk/include/clang/AST/TypeNodes.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/TypeNodes.def?rev=311544&r1=311543&r2=311544&view=diff
==
--- cfe/trunk/include/clang/AST/TypeNodes.def (original)
+++ cfe/trunk/include/clang/AST/TypeNodes.def Wed Aug 23 03:43:26 2017
@@ -23,7 +23,7 @@
 //NON_CANONICAL_TYPE(Class, Base) - A type that can show up
 //anywhere in the AST but will never be a part of a canonical
 //type. Clients that only need to deal with canonical types
-//(ignoring, e.g., typedefs and other type alises used for
+//(ignoring, e.g., typedefs and other type aliases used for
 //pretty-printing) can ignore these types.
 //
 //DEPENDENT_TYPE(Class, Base) - A type that will only show up

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=311544&r1=311543&r2=311544&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Wed Aug 23 03:43:26 2017
@@ -25,7 +25,7 @@
 //
 //  For example, when we're interested in child classes of a certain class, we
 //  would write:
-//cxxRecordDecl(hasName("MyClass"), hasChild(id("child", recordDecl(
+//cxxRecordDecl(hasName("MyClass"), has(id("child", recordDecl(
 //  When the match is found via the MatchFinder, a user provided callback will
 //  be called with a BoundNodes instance that contains a mapping from the
 //  strings that we provided for the id(...) calls to the nodes that were

Modified: cfe/trunk/include/clang/Analysis/CloneDetection.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/CloneDetection.h?rev=311544&r1=311543&r2=311544&view=diff
==
--- cfe/trunk/include/clang/Analysis/CloneDetection.h (original)
+++ cfe/trunk/include/clang/Analysis/CloneDetection.h Wed Aug 23 03:43:26 2017
@@ -8,7 +8,7 @@
 
//===--===//
 ///
 /// \file
-/// This file defines classes for searching and anlyzing source code clones.
+/// This file defines classes for searching and analyzing source code clones.
 ///
 
//===--===//
 

Modified: cfe/trunk/include/clang/Tooling/CommonOptionsParser.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/CommonOptionsParser.h?rev=311544&r1=311543&r2=311544&view=diff
==
--- cfe/trunk/include/clang/Tooling/CommonOptionsParser.h (original)
+++ cfe/trunk/include/clang/Tooling/CommonOptionsParser.h Wed Aug 23 03:43:26 
2017
@@ -85,7 +85,7 @@ public:
   ///
   /// All options not belonging to \p Category become hidden.
   ///
-  /// I also allows calls to set the required number of positional parameters.
+  /// It also allows calls to set the required number of positional parameters.
   ///
   /// This constructor exits program in case of error.
   CommonOptionsParser(int &argc, const char **argv,
@@ -108,8 +108,6 @@ public:
 private:
   std::unique_ptr Compilations;
   std::vector SourcePathList;
-  std::vector ExtraArgsBefore;
-  std::vector ExtraArgsAfter;
 };
 
 class ArgumentsAdjustingCompilations : public CompilationDatabase {

Modified: cfe/trunk/include/clang/Too

r311523 - bpf: add -mcpu=# support for bpf

2017-08-23 Thread Yonghong Song via cfe-commits
Author: yhs
Date: Tue Aug 22 21:26:17 2017
New Revision: 311523

URL: http://llvm.org/viewvc/llvm-project?rev=311523&view=rev
Log:
bpf: add -mcpu=# support for bpf

-mcpu=# will support:
  . generic: the default insn set
  . v1: insn set version 1, the same as generic
  . v2: insn set version 2, version 1 + additional jmp insns
  . probe: the compiler will probe the underlying kernel to
   decide proper version of insn set.

Examples:
$ clang -target bpf -mcpu=v1 -c t.c
$ clang -target bpf -mcpu=v2 -c t.c
$ clang -target bpf -mcpu=generic -c t.c
$ clang -target bpf -mcpu=probe -c t.c
$ clang -target bpf -mcpu=v3 -c t.c
error: unknown target CPU 'v3'

Signed-off-by: Yonghong Song 
Acked-by: Alexei Starovoitov 

Modified:
cfe/trunk/lib/Basic/Targets/BPF.h
cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp

Modified: cfe/trunk/lib/Basic/Targets/BPF.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/BPF.h?rev=311523&r1=311522&r2=311523&view=diff
==
--- cfe/trunk/lib/Basic/Targets/BPF.h (original)
+++ cfe/trunk/lib/Basic/Targets/BPF.h Tue Aug 22 21:26:17 2017
@@ -76,6 +76,18 @@ public:
   return CCCR_OK;
 }
   }
+
+  bool isValidCPUName(StringRef Name) const override {
+if (Name == "generic" || Name == "v1" ||
+Name == "v2" || Name == "probe")
+  return true;
+return false;
+  }
+
+  bool setCPU(const std::string &Name) override {
+StringRef CPUName(Name);
+return isValidCPUName(CPUName);
+  }
 };
 } // namespace targets
 } // namespace clang

Modified: cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp?rev=311523&r1=311522&r2=311523&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp Tue Aug 22 21:26:17 2017
@@ -320,6 +320,8 @@ std::string tools::getCPUName(const ArgL
 return TargetCPUName;
   }
 
+  case llvm::Triple::bpfel:
+  case llvm::Triple::bpfeb:
   case llvm::Triple::sparc:
   case llvm::Triple::sparcel:
   case llvm::Triple::sparcv9:


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


[PATCH] D35271: Fix printing policy for AST context loaded from file

2017-08-23 Thread Johann Klähn via Phabricator via cfe-commits
jklaehn updated this revision to Diff 112334.
jklaehn added a comment.

Update regression test to use `createTemporaryFile()` and `tool_output_file` as 
suggested.


https://reviews.llvm.org/D35271

Files:
  lib/Frontend/ASTUnit.cpp
  unittests/Frontend/ASTUnitTest.cpp
  unittests/Frontend/CMakeLists.txt

Index: unittests/Frontend/CMakeLists.txt
===
--- unittests/Frontend/CMakeLists.txt
+++ unittests/Frontend/CMakeLists.txt
@@ -3,6 +3,7 @@
   )
 
 add_clang_unittest(FrontendTests
+  ASTUnitTest.cpp
   FrontendActionTest.cpp
   CodeGenActionTest.cpp
   )
Index: unittests/Frontend/ASTUnitTest.cpp
===
--- /dev/null
+++ unittests/Frontend/ASTUnitTest.cpp
@@ -0,0 +1,87 @@
+//===- unittests/Frontend/ASTUnitTest.cpp - ASTUnit tests -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include 
+
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PCHContainerOperations.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+TEST(ASTUnit, SaveLoadPreservesLangOptionsInPrintingPolicy) {
+  // Check that the printing policy is restored with the correct language
+  // options when loading an ASTUnit from a file.  To this end, an ASTUnit
+  // for a C++ translation unit is set up and written to a temporary file.
+
+  // By default `UseVoidForZeroParams` is true for non-C++ language options,
+  // thus we can check this field after loading the ASTUnit to deduce whether
+  // the correct (C++) language options were used when setting up the printing
+  // policy.
+
+  {
+PrintingPolicy PolicyWithDefaultLangOpt(LangOptions{});
+EXPECT_TRUE(PolicyWithDefaultLangOpt.UseVoidForZeroParams);
+  }
+
+  int FD;
+  llvm::SmallString<256> InputFileName;
+  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD, InputFileName));
+  tool_output_file input_file(InputFileName, FD);
+  input_file.os() << "";
+
+  const char* Args[] = {"clang", "-xc++", InputFileName.c_str()};
+
+  IntrusiveRefCntPtr Diags =
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+  std::shared_ptr CInvok =
+  createInvocationFromCommandLine(Args, Diags);
+
+  if (!CInvok)
+FAIL() << "could not create compiler invocation";
+
+  FileManager *FileMgr =
+  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
+  auto PCHContainerOps = std::make_shared();
+
+  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(
+  CInvok, PCHContainerOps, Diags, FileMgr);
+
+  if (!AST)
+FAIL() << "failed to create ASTUnit";
+
+  EXPECT_FALSE(AST->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
+
+  llvm::SmallString<256> ASTFileName;
+  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "ast", FD, ASTFileName));
+  tool_output_file ast_file(ASTFileName, FD);
+  AST->Save(ASTFileName.str());
+
+  EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
+
+  std::unique_ptr AU = ASTUnit::LoadFromASTFile(
+  ASTFileName.str(), PCHContainerOps->getRawReader(), ASTUnit::LoadEverything, Diags,
+  FileSystemOptions(), /*UseDebugInfo=*/false);
+
+  if (!AU)
+FAIL() << "failed to load ASTUnit";
+
+  EXPECT_FALSE(AU->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
+}
+
+} // anonymous namespace
Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -542,6 +542,9 @@
 // Initialize the ASTContext
 Context->InitBuiltinTypes(*Target);
 
+// Adjust printing policy based on language options.
+Context->setPrintingPolicy(PrintingPolicy(LangOpt));
+
 // We didn't have access to the comment options when the ASTContext was
 // constructed, so register them now.
 Context->getCommentCommandTraits().registerCommentOptions(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D36956: [clang-format] Emit absolute splits before lines for comments

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


https://reviews.llvm.org/D36956



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


[PATCH] D36354: [clang-tidy] Implement type-based check for `gsl::owner`

2017-08-23 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth marked 2 inline comments as done.
JonasToth added a comment.

improved structure a bit


https://reviews.llvm.org/D36354



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


[PATCH] D36354: [clang-tidy] Implement type-based check for `gsl::owner`

2017-08-23 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 112336.
JonasToth added a comment.

- test case fixed expected warning
- address review comments from aaron


https://reviews.llvm.org/D36354

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
  clang-tidy/cppcoreguidelines/OwningMemoryCheck.h
  clang-tidy/utils/Matchers.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-owning-memory.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-owning-memory.cpp

Index: test/clang-tidy/cppcoreguidelines-owning-memory.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-owning-memory.cpp
@@ -0,0 +1,347 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-owning-memory %t
+
+namespace gsl {
+template 
+using owner = T;
+} // namespace gsl
+
+template 
+class unique_ptr {
+public:
+  unique_ptr(gsl::owner resource) : memory(resource) {}
+  unique_ptr(const unique_ptr &) = default;
+
+  ~unique_ptr() { delete memory; }
+
+private:
+  gsl::owner memory;
+};
+
+void takes_owner(gsl::owner owned_int) {
+}
+
+void takes_pointer(int *unowned_int) {
+}
+
+void takes_owner_and_more(int some_int, gsl::owner owned_int, float f) {
+}
+
+template 
+void takes_templated_owner(gsl::owner owned_T) {
+}
+
+gsl::owner returns_owner1() { return gsl::owner(new int(42)); } // Ok
+gsl::owner returns_owner2() { return new int(42); } // Ok
+
+int *returns_no_owner1() { return nullptr; }
+int *returns_no_owner2() {
+  return new int(42);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning an owner/resource from a function but not declaring it as one
+}
+int *returns_no_owner3() {
+  int *should_be_owner = new int(42);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource
+  return should_be_owner;
+}
+int *returns_no_owner4() {
+  gsl::owner owner = new int(42);
+  return owner;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning an owner/resource from a function but not declaring it as one
+}
+
+unique_ptr returns_no_owner5() {
+  return unique_ptr(new int(42)); // Ok
+}
+
+/// FIXME CSA finds it, but the report is misleading.
+void csa_not_finding_leak() {
+  gsl::owner o1 = new int(42); // Ok
+
+  gsl::owner o2 = o1; // Ok
+  o2 = new int(45); // conceptual leak, the memory from o1 is now leaked, since its considered moved in the guideLINEs
+
+  delete o2;
+  // actual leak occurs here, its found, but mixed
+  delete o1;
+}
+
+void test_assignment_and_initialization() {
+  int stack_int1 = 15;
+  int stack_int2;
+
+  gsl::owner owned_int1 = &stack_int1; // BAD
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource
+
+  gsl::owner owned_int2;
+  owned_int2 = &stack_int2; // BAD since no owner, bad since uninitialized
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning neither an owner nor a recognized resource
+
+  gsl::owner owned_int3 = new int(42); // Good
+  owned_int3 = nullptr; // Good
+
+  gsl::owner owned_int4(nullptr); // Ok
+  owned_int4 = new int(42); // Good
+
+  gsl::owner owned_int5 = owned_int3; // Good
+
+  gsl::owner owned_int6{nullptr}; // Ok
+  owned_int6 = owned_int4; // Good
+
+  // FIXME, flow analysis for the case of reassignment. Value must be released before
+  owned_int6 = owned_int3; // BAD, because reassignment without resource release
+
+  auto owned_int7 = returns_owner1(); // Bad, since typededuction eliminates the owner wrapper
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner
+
+  const auto owned_int8 = returns_owner2(); // Bad, since typededuction eliminates the owner wrapper
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner
+
+  gsl::owner owned_int9 = returns_owner1(); // Ok
+  int *unowned_int3 = returns_owner1(); // Bad
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource
+
+  gsl::owner owned_int10;
+  owned_int10 = returns_owner1(); // Ok
+
+  int *unowned_int4;
+  unowned_int4 = returns_owner1(); // Bad
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning newly created owner/resource to non-owner
+
+  gsl::owner owned_int11 = returns_no_owner1(); // Bad since no owner
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource
+
+  gsl::owner owned_int12;
+  owned_int12 = returns_no_owner1(); // Bad since no owner
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning neither an owner nor a recognized resource
+
+  int *unowned_int5 = returns_no_owner1(); // Ok
+  int *unowned_int6;
+  unowned_int

[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon added a comment.

In https://reviews.llvm.org/D37014#849157, @lebedev.ri wrote:

> Please add the following test: (and make sure that it does the right thing :))
>
>   bool f_with_preproc_condition() {
> auto test = 42;
> assert(test == 42);
> return test;
>   }
>
>
> I.e. if `-DNDEBUG` is present, variable is not needed, but if `-DNDEBUG` is 
> *NOT* present...


Shouldn't we ignore these cases whether or not `-DNDEBUG` is present? If we 
apply the fix here and remove the variable while we have `-DNDEBUG`, and then 
remove this define, then we'll get a compiler error for `test` not found.
In this case it can be fixed fairly easily, but this could in fact introduce 
bugs with more complex conditional macros and preprocessor directives. For 
example:

  #ifdef WIN32
  #define MY_MACRO(test) test = 0
  #else
  #define MY_MACRO(test) /* nothing */
  
  bool f() {
auto test = 42;
MY_MACRO(test);
return (test == 42)
  }

If we want to ignore these cases not matter what, which seems to me like the 
most logical and reasonable thing to do, we need to be able to know if there 
are preprocessor directives between the variable declaration and the `return` 
statement.
In order to do that, we would need to be able to get the `PreprocessingRecord` 
of the current compilation in order to call getPreprocessedEntitiesInRange() 
,
 but AFAICT this cannot be accessed from clang-tidy checks at the moment. 
Should we introduce a way to reach that object from checks?


Repository:
  rL LLVM

https://reviews.llvm.org/D37014



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


[PATCH] D30295: [analyzer] clarify undef shift result when shift count is negative or exceeds the bit width

2017-08-23 Thread Daniel Marjamäki via Phabricator via cfe-commits
danielmarjamaki added a comment.

ping


Repository:
  rL LLVM

https://reviews.llvm.org/D30295



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


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D37014#850064, @tbourvon wrote:

> In https://reviews.llvm.org/D37014#849157, @lebedev.ri wrote:
>
> > Please add the following test: (and make sure that it does the right thing 
> > :))
> >
> >   bool f_with_preproc_condition() {
> > auto test = 42;
> > assert(test == 42);
> > return test;
> >   }
> >
> >
> > I.e. if `-DNDEBUG` is present, variable is not needed, but if `-DNDEBUG` is 
> > *NOT* present...
>
>
> Shouldn't we ignore these cases whether or not `-DNDEBUG` is present?


That's *exactly* what i was talking about.

> If we apply the fix here and remove the variable while we have `-DNDEBUG`, 
> and then remove this define, then we'll get a compiler error for `test` not 
> found.
>  In this case it can be fixed fairly easily, but this could in fact introduce 
> bugs with more complex conditional macros and preprocessor directives. For 
> example:
> 
>   #ifdef WIN32
>   #define MY_MACRO(test) test = 0
>   #else
>   #define MY_MACRO(test) /* nothing */
>   #endif
>   
>   bool f() {
> auto test = 42;
> MY_MACRO(test);
> return (test == 42);
>   }
> 
> 
> If we want to ignore these cases not matter what, which seems to me like the 
> most logical and reasonable thing to do, we need to be able to know if there 
> are preprocessor directives between the variable declaration and the `return` 
> statement.
>  In order to do that, we would need to be able to get the 
> `PreprocessingRecord` of the current compilation in order to call 
> getPreprocessedEntitiesInRange() 
> ,
>  but AFAICT this cannot be accessed from clang-tidy checks at the moment. 
> Should we introduce a way to reach that object from checks?

Currently, there is a `registerPPCallbacks()` function in `ClangTidyCheck` 
class,  which allows you to register a subclass of `PPCallbacks`, and manually 
handle all the preprocessor thingies.
That being said, getPreprocessedEntitiesInRange() 

 looks interesting, and it *might* help me in https://reviews.llvm.org/D36836.


Repository:
  rL LLVM

https://reviews.llvm.org/D37014



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


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon added a comment.

In https://reviews.llvm.org/D37014#850088, @lebedev.ri wrote:

> In https://reviews.llvm.org/D37014#850064, @tbourvon wrote:
>
> > In https://reviews.llvm.org/D37014#849157, @lebedev.ri wrote:
> >
> > > Please add the following test: (and make sure that it does the right 
> > > thing :))
> > >
> > >   bool f_with_preproc_condition() {
> > > auto test = 42;
> > > assert(test == 42);
> > > return test;
> > >   }
> > >
> > >
> > > I.e. if `-DNDEBUG` is present, variable is not needed, but if `-DNDEBUG` 
> > > is *NOT* present...
> >
> >
> > Shouldn't we ignore these cases whether or not `-DNDEBUG` is present?
>
>
> That's *exactly* what i was talking about.
>
> > If we apply the fix here and remove the variable while we have `-DNDEBUG`, 
> > and then remove this define, then we'll get a compiler error for `test` not 
> > found.
> >  In this case it can be fixed fairly easily, but this could in fact 
> > introduce bugs with more complex conditional macros and preprocessor 
> > directives. For example:
> > 
> >   #ifdef WIN32
> >   #define MY_MACRO(test) test = 0
> >   #else
> >   #define MY_MACRO(test) /* nothing */
> >   #endif
> >   
> >   bool f() {
> > auto test = 42;
> > MY_MACRO(test);
> > return (test == 42);
> >   }
> > 
> > 
> > If we want to ignore these cases not matter what, which seems to me like 
> > the most logical and reasonable thing to do, we need to be able to know if 
> > there are preprocessor directives between the variable declaration and the 
> > `return` statement.
> >  In order to do that, we would need to be able to get the 
> > `PreprocessingRecord` of the current compilation in order to call 
> > getPreprocessedEntitiesInRange() 
> > ,
> >  but AFAICT this cannot be accessed from clang-tidy checks at the moment. 
> > Should we introduce a way to reach that object from checks?
>
> Currently, there is a `registerPPCallbacks()` function in `ClangTidyCheck` 
> class,  which allows you to register a subclass of `PPCallbacks`, and 
> manually handle all the preprocessor thingies.
>  That being said, getPreprocessedEntitiesInRange() 
> 
>  looks interesting, and it *might* help me in https://reviews.llvm.org/D36836.


IMO it makes more sense to expose `PreprocessingRecord`, as registering 
callbacks and maintaining a private inner database for every check not only 
isn't ideal in terms of performance, but also duplicates logic and could lead 
to inconsistencies.
I think I'm going to work on getting this object accessible through 
`MatchResult` and `MatchFinder` so that it is accessible from both checks and 
matchers. Probably in a separate patch. Please let me know if you have any more 
thoughts on this.


Repository:
  rL LLVM

https://reviews.llvm.org/D37014



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


r311552 - [Bash-autocompletion] Add support for static analyzer flags

2017-08-23 Thread Yuka Takahashi via cfe-commits
Author: yamaguchi
Date: Wed Aug 23 06:39:47 2017
New Revision: 311552

URL: http://llvm.org/viewvc/llvm-project?rev=311552&view=rev
Log:
[Bash-autocompletion] Add support for static analyzer flags

Summary:
This is a patch for clang autocomplete feature.

It will collect values which -analyzer-checker takes, which is defined in
clang/StaticAnalyzer/Checkers/Checkers.inc, dynamically.
First, from ValuesCode class in Options.td, TableGen will generate C++
code in Options.inc. Options.inc will be included in DriverOptions.cpp, and
calls OptTable's addValues function. addValues function will add second
argument to Option's Values class. Values contains string like "foo,bar,.."
which is handed to Values class
in OptTable.

Reviewers: v.g.vassilev, teemperor, ruiu

Subscribers: hiraditya, cfe-commits

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

Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/lib/Driver/DriverOptions.cpp
cfe/trunk/test/Driver/autocomplete.c

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=311552&r1=311551&r2=311552&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Wed Aug 23 06:39:47 2017
@@ -99,7 +99,19 @@ def analyzer_stats : Flag<["-"], "analyz
   HelpText<"Print internal analyzer statistics.">;
 
 def analyzer_checker : Separate<["-"], "analyzer-checker">,
-  HelpText<"Choose analyzer checkers to enable">;
+  HelpText<"Choose analyzer checkers to enable">,
+  ValuesCode<[{
+const char *Values =
+#define GET_CHECKERS
+#define CHECKER(FULLNAME, CLASS, DESCFILE, HT, G, H)  FULLNAME ","
+#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
+#undef GET_CHECKERS
+#define GET_PACKAGES
+#define PACKAGE(FULLNAME, G, D)  FULLNAME ","
+#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
+#undef GET_PACKAGES
+;
+  }]>;
 def analyzer_checker_EQ : Joined<["-"], "analyzer-checker=">,
   Alias;
 

Modified: cfe/trunk/lib/Driver/DriverOptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/DriverOptions.cpp?rev=311552&r1=311551&r2=311552&view=diff
==
--- cfe/trunk/lib/Driver/DriverOptions.cpp (original)
+++ cfe/trunk/lib/Driver/DriverOptions.cpp Wed Aug 23 06:39:47 2017
@@ -11,6 +11,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
+#include 
 
 using namespace clang::driver;
 using namespace clang::driver::options;
@@ -40,5 +41,13 @@ public:
 }
 
 std::unique_ptr clang::driver::createDriverOptTable() {
-  return llvm::make_unique();
+  auto Result = llvm::make_unique();
+  // Options.inc is included in DriverOptions.cpp, and calls OptTable's
+  // addValues function.
+  // Opt is a variable used in the code fragment in Options.inc.
+  OptTable &Opt = *Result;
+#define OPTTABLE_ARG_INIT
+#include "clang/Driver/Options.inc"
+#undef OPTTABLE_ARG_INIT
+  return std::move(Result);
 }

Modified: cfe/trunk/test/Driver/autocomplete.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/autocomplete.c?rev=311552&r1=311551&r2=311552&view=diff
==
--- cfe/trunk/test/Driver/autocomplete.c (original)
+++ cfe/trunk/test/Driver/autocomplete.c Wed Aug 23 06:39:47 2017
@@ -93,3 +93,5 @@
 // WARNING-NEXT: -Wmax-unsigned-zero
 // RUN: %clang --autocomplete=-Wno-invalid-pp- | FileCheck %s 
-check-prefix=NOWARNING
 // NOWARNING: -Wno-invalid-pp-token
+// RUN: %clang --autocomplete=-analyzer-checker, | FileCheck %s 
-check-prefix=ANALYZER
+// ANALYZER: unix.Malloc


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


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon updated this revision to Diff 112351.
tbourvon added a comment.

Fixing the reviewers' remarks, mainly formatting and const-correctness, as well 
as adding a few more tests.


https://reviews.llvm.org/D37014

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tidy/readability/UnnecessaryIntermediateVarCheck.cpp
  clang-tidy/readability/UnnecessaryIntermediateVarCheck.h
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  clang-tidy/utils/Matchers.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-unnecessary-intermediate-var.rst
  test/clang-tidy/readability-unnecessary-intermediate-var.cpp

Index: test/clang-tidy/readability-unnecessary-intermediate-var.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-unnecessary-intermediate-var.cpp
@@ -0,0 +1,174 @@
+// RUN: %check_clang_tidy %s readability-unnecessary-intermediate-var %t
+
+bool f() {
+  auto test = 1; // Test
+  // CHECK-FIXES: {{^}}  // Test{{$}}
+  return (test == 1);
+  // CHECK-FIXES: {{^}}  return (1 == 1);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f2() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (test1 == test2);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: and so is 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-4]]:11: note: because they are only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-9]]:8: note: consider removing both this variable declaration
+  // CHECK-MESSAGES: :[[@LINE-8]]:8: note: and this one
+  // CHECK-MESSAGES: :[[@LINE-7]]:11: note: and directly using the variable initialization expressions here
+}
+
+bool f3() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  return (test1 == 2);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-7]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f4() {
+  auto test1 = 1; // Test1
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (test2 == 3);
+  // CHECK-FIXES: {{^}}  return (2 == 3);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f5() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  return (2 == test1);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:16: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-7]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f6() {
+  auto test1 = 1; // Test1
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (3 == test2);
+  // CHECK-FIXES: {{^}}  return (2 == 3);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:16: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+int foo() { return

[PATCH] D36782: [Bash-autocompletion] Add support for static analyzer flags

2017-08-23 Thread Yuka Takahashi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
yamaguchi marked an inline comment as done.
Closed by commit rL311552: [Bash-autocompletion] Add support for static 
analyzer flags (authored by yamaguchi).

Changed prior to commit:
  https://reviews.llvm.org/D36782?vs=111548&id=112353#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D36782

Files:
  cfe/trunk/include/clang/Driver/CC1Options.td
  cfe/trunk/lib/Driver/DriverOptions.cpp
  cfe/trunk/test/Driver/autocomplete.c
  llvm/trunk/include/llvm/Option/OptParser.td
  llvm/trunk/include/llvm/Option/OptTable.h
  llvm/trunk/lib/Option/OptTable.cpp
  llvm/trunk/utils/TableGen/OptParserEmitter.cpp

Index: llvm/trunk/include/llvm/Option/OptParser.td
===
--- llvm/trunk/include/llvm/Option/OptParser.td
+++ llvm/trunk/include/llvm/Option/OptParser.td
@@ -93,6 +93,7 @@
   string HelpText = ?;
   string MetaVarName = ?;
   string Values = ?;
+  code ValuesCode = ?;
   list Flags = [];
   OptionGroup Group = ?;
   Option Alias = ?;
@@ -128,6 +129,7 @@
 class HelpText { string HelpText = text; }
 class MetaVarName { string MetaVarName = name; }
 class Values { string Values = value; }
+class ValuesCode { code ValuesCode = valuecode; }
 
 // Predefined options.
 
Index: llvm/trunk/include/llvm/Option/OptTable.h
===
--- llvm/trunk/include/llvm/Option/OptTable.h
+++ llvm/trunk/include/llvm/Option/OptTable.h
@@ -57,8 +57,8 @@
   };
 
 private:
-  /// \brief The static option information table.
-  ArrayRef OptionInfos;
+  /// \brief The option information table.
+  std::vector OptionInfos;
   bool IgnoreCase;
 
   unsigned TheInputOptionID = 0;
@@ -143,6 +143,17 @@
   std::vector findByPrefix(StringRef Cur,
 unsigned short DisableFlags) const;
 
+  /// Add Values to Option's Values class
+  ///
+  /// \param [in] Option - Prefix + Name of the flag which Values will be
+  ///  changed. For example, "-analyzer-checker".
+  /// \param [in] Values - String of Values seperated by ",", such as
+  ///  "foo, bar..", where foo and bar is the argument which the Option flag
+  ///  takes
+  ///
+  /// \return true in success, and false in fail.
+  bool addValues(const char *Option, const char *Values);
+
   /// \brief Parse a single argument; returning the new argument and
   /// updating Index.
   ///
Index: llvm/trunk/lib/Option/OptTable.cpp
===
--- llvm/trunk/lib/Option/OptTable.cpp
+++ llvm/trunk/lib/Option/OptTable.cpp
@@ -196,7 +196,7 @@
 
 // Returns true if one of the Prefixes + In.Names matches Option
 static bool optionMatches(const OptTable::Info &In, StringRef Option) {
-  if (In.Values && In.Prefixes)
+  if (In.Prefixes)
 for (size_t I = 0; In.Prefixes[I]; I++)
   if (Option == std::string(In.Prefixes[I]) + In.Name)
 return true;
@@ -209,8 +209,9 @@
 std::vector
 OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
   // Search all options and return possible values.
-  for (const Info &In : OptionInfos.slice(FirstSearchableIndex)) {
-if (!optionMatches(In, Option))
+  for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
+const Info &In = OptionInfos[I];
+if (!In.Values || !optionMatches(In, Option))
   continue;
 
 SmallVector Candidates;
@@ -228,7 +229,8 @@
 std::vector
 OptTable::findByPrefix(StringRef Cur, unsigned short DisableFlags) const {
   std::vector Ret;
-  for (const Info &In : OptionInfos.slice(FirstSearchableIndex)) {
+  for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
+const Info &In = OptionInfos[I];
 if (!In.Prefixes || (!In.HelpText && !In.GroupID))
   continue;
 if (In.Flags & DisableFlags)
@@ -245,6 +247,17 @@
   return Ret;
 }
 
+bool OptTable::addValues(const char *Option, const char *Values) {
+  for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
+Info &In = OptionInfos[I];
+if (optionMatches(In, Option)) {
+  In.Values = Values;
+  return true;
+}
+  }
+  return false;
+}
+
 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
@@ -256,8 +269,8 @@
   if (isInput(PrefixesUnion, Str))
 return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
 
-  const Info *Start = OptionInfos.begin() + FirstSearchableIndex;
-  const Info *End = OptionInfos.end();
+  const Info *Start = OptionInfos.data() + FirstSearchableIndex;
+  const Info *End = OptionInfos.data() + OptionInfos.size();
   StringRef Name = StringRef(Str).ltrim(PrefixChars);
 
   // Search for the first next option which could be a prefix.
Index: llvm/trunk/utils/TableGen/OptParserEmitter.cpp
==

[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon marked 14 inline comments as done.
tbourvon added inline comments.



Comment at: clang-tidy/readability/UselessIntermediateVarCheck.h:29
+  : ClangTidyCheck(Name, Context),
+MaximumLineLength(Options.get("MaximumLineLength", 100)) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;

JonasToth wrote:
> It would be nice, if there is a way to get this information from a 
> clang-format file. 
There is no easy way to get this information unless you want to use all the 
LibFormat stuff that includes finding the .clang-format file, etc... It doesn't 
seem like it is the responsibility of this checker to take care of that.



Comment at: test/clang-tidy/readability-useless-intermediate-var.cpp:1
+// RUN: %check_clang_tidy %s readability-useless-intermediate-var %t
+

JonasToth wrote:
> the tests seem to be to less compared to the code volume of the check.
> 
> situations i think should be tested:
> 
> - initialization from a function, method call
> - initialization with a lambda
> ```
> const auto SomeVar = []() { /* super complicated stuff */ return Result; } ();
> return SomeVar;
> ```
> - template stuff -> proof that they work two, even thought it doesnt seem to 
> be relevant, at least what i can see.
> - what happens if a "temporary" is used as an argument for a function call?
> ```
> const auto Var = std::sqrt(10);
> return std::pow(Var, 10);
> ```
> - proof that really long function calls (like STL Algorithm tends to be) are 
> not inlined as well
Your 4th point is not something possible with this check. For now it only looks 
at `return` statements with comparisons.
As for the 5th, it doesn't really matter what the expression we are looking at 
is, so this case is already covered by the very long string literal in the last 
test.


https://reviews.llvm.org/D37014



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


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon updated this revision to Diff 112356.
tbourvon marked an inline comment as done.
tbourvon added a comment.

Forgot to move the comments on small matchers as suggested by review.


https://reviews.llvm.org/D37014

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tidy/readability/UnnecessaryIntermediateVarCheck.cpp
  clang-tidy/readability/UnnecessaryIntermediateVarCheck.h
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  clang-tidy/utils/Matchers.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-unnecessary-intermediate-var.rst
  test/clang-tidy/readability-unnecessary-intermediate-var.cpp

Index: test/clang-tidy/readability-unnecessary-intermediate-var.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-unnecessary-intermediate-var.cpp
@@ -0,0 +1,174 @@
+// RUN: %check_clang_tidy %s readability-unnecessary-intermediate-var %t
+
+bool f() {
+  auto test = 1; // Test
+  // CHECK-FIXES: {{^}}  // Test{{$}}
+  return (test == 1);
+  // CHECK-FIXES: {{^}}  return (1 == 1);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f2() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (test1 == test2);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: and so is 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-4]]:11: note: because they are only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-9]]:8: note: consider removing both this variable declaration
+  // CHECK-MESSAGES: :[[@LINE-8]]:8: note: and this one
+  // CHECK-MESSAGES: :[[@LINE-7]]:11: note: and directly using the variable initialization expressions here
+}
+
+bool f3() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  return (test1 == 2);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-7]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f4() {
+  auto test1 = 1; // Test1
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (test2 == 3);
+  // CHECK-FIXES: {{^}}  return (2 == 3);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f5() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  return (2 == test1);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:16: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-7]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f6() {
+  auto test1 = 1; // Test1
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (3 == test2);
+  // CHECK-FIXES: {{^}}  return (2 == 3);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:16: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+int foo() { re

[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2017-08-23 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: clang-tidy/readability/UnnecessaryIntermediateVarCheck.cpp:376
+// expression wouldn't really benefit readability. Therefore we abort.
+if (NewReturnLength > MaximumLineLength) {
+  return;

Is there really no way to format the fixes, and *then* check the line length?
```
$ clang-tidy --help
...
  -format-style=   - 
 Style for formatting code around applied fixes:
   - 'none' (default) turns off formatting
   - 'file' (literally 'file', not a 
placeholder)
 uses .clang-format file in the closest 
parent
 directory
   - '{  }' specifies options inline, e.g.
 -format-style='{BasedOnStyle: llvm, 
IndentWidth: 8}'
   - 'llvm', 'google', 'webkit', 'mozilla'
 See clang-format documentation for the 
up-to-date
 information about formatting styles and 
options.
 This option overrides the 'FormatStyle` option 
in
 .clang-tidy file, if any.
...
```
so `clang-tidy` is at least aware of `clang-format`.



Comment at: clang-tidy/readability/UnnecessaryIntermediateVarCheck.h:30
+  : ClangTidyCheck(Name, Context),
+MaximumLineLength(Options.get("MaximumLineLength", 100)) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;

It would be better to default to `80`, especially if it can't be read from 
`.clang-tidy`.



Comment at: test/clang-tidy/readability-unnecessary-intermediate-var.cpp:172
+bool f_long_expression() {
+  auto test = "this is a very very very very very very very very very long 
expression to test max line length detection";
+  return (test == "");

Please add edge-cases, i.e. just below `MaximumLineLength`, exactly 
`MaximumLineLength`, ...


https://reviews.llvm.org/D37014



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


[PATCH] D36876: [IRGen] Evaluate constant static variables referenced through member expressions

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



Comment at: lib/CodeGen/CGExprComplex.cpp:163
+else
+  CGF.EmitLValue(ME->getBase());
+return *Constant;

rjmccall wrote:
> rjmccall wrote:
> > There's an EmitIgnoredExpr you could use.
> > 
> > Also, I think it would be fine to add a generic tryEmitMemberExprAsConstant 
> > that takes a MemberExpr and does this DRE stuff behind the scenes; it's not 
> > at all different for the different emitters.
> Well, actually, now I see why it's different for the complex emitter, but I 
> think you could probably extract out a function that forms a complex pair 
> from a constant output without too much trouble.
> 
> Also, as long as you're working with this, I think it's likely that the Agg 
> emitter needs to handle this, too.  I'm not sure I accept the claim there 
> that constant r-value emission never applies to aggregates, but at the very 
> least you need to handle references just as the DRE case does.
It looks like that constant reference code in Agg emitter is dead, so I removed 
it. 

The static constant variables that were references to aggregates were still 
inconsistent between DREs and MEs, so I now try to emit MEs as DREs in 
CodeGenFunction's Lvalue emitter now.


Repository:
  rL LLVM

https://reviews.llvm.org/D36876



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


[PATCH] D36876: [IRGen] Evaluate constant static variables referenced through member expressions

2017-08-23 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman updated this revision to Diff 112360.
arphaman marked 2 inline comments as done.
arphaman added a comment.

- Create `tryEmitAsConstant` for MemberExprs and `emitConstant` helper for 
complex values as suggested by John.
- Remove dead constant emission code from CGExprAggregate.cpp
- Emit static variable member expressions as DREs when emitting Lvalues to 
ensure the IR is consistent between DREs and MEs that reference a constant 
static variables whose type is a reference to an aggregate


Repository:
  rL LLVM

https://reviews.llvm.org/D36876

Files:
  lib/CodeGen/CGExpr.cpp
  lib/CodeGen/CGExprAgg.cpp
  lib/CodeGen/CGExprComplex.cpp
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenFunction.h
  test/CodeGenCXX/member-expr-references-variable.cpp

Index: test/CodeGenCXX/member-expr-references-variable.cpp
===
--- /dev/null
+++ test/CodeGenCXX/member-expr-references-variable.cpp
@@ -0,0 +1,104 @@
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
+
+struct Agg { const char * x; const char * y; constexpr Agg() : x(0), y(0) {} };
+
+struct Struct {
+   constexpr static const char *name = "foo";
+
+   constexpr static __complex float complexValue = 42.0;
+
+   static constexpr const Agg &agg = Agg();
+
+   Struct();
+   Struct(int x);
+};
+
+void use(int n, const char *c);
+
+Struct *getPtr();
+
+// CHECK: @[[STR:.*]] = private unnamed_addr constant [4 x i8] c"foo\00", align 1
+
+void scalarStaticVariableInMemberExpr(Struct *ptr, Struct &ref) {
+  use(1, Struct::name);
+// CHECK: call void @_Z3useiPKc(i32 1, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0))
+  Struct s;
+  use(2, s.name);
+// CHECK: call void @_Z3useiPKc(i32 2, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0))
+  use(3, ptr->name);
+// CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8
+// CHECK: call void @_Z3useiPKc(i32 3, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0))
+  use(4, ref.name);
+// CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8
+// CHECK: call void @_Z3useiPKc(i32 4, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0))
+  use(5, Struct(2).name);
+// CHECK: call void @_ZN6StructC1Ei(%struct.Struct* %{{.*}}, i32 2)
+// CHECK: call void @_Z3useiPKc(i32 5, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0))
+  use(6, getPtr()->name);
+// CHECK: call %struct.Struct* @_Z6getPtrv()
+// CHECK: call void @_Z3useiPKc(i32 6, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0))
+}
+
+void use(int n, __complex float v);
+
+void complexStaticVariableInMemberExpr(Struct *ptr, Struct &ref) {
+  use(1, Struct::complexValue);
+// CHECK: store float 4.20e+01, float* %[[coerce0:.*]].{{.*}}, align 4
+// CHECK: store float 0.00e+00, float* %[[coerce0]].{{.*}}, align 4
+// CHECK: %[[cast0:.*]] = bitcast { float, float }* %[[coerce0]] to <2 x float>*
+// CHECK: %[[vector0:.*]] = load <2 x float>, <2 x float>* %[[cast0]], align 4
+// CHECK: call void @_Z3useiCf(i32 1, <2 x float> %[[vector0]])
+  Struct s;
+  use(2, s.complexValue);
+// CHECK: store float 4.20e+01, float* %[[coerce1:.*]].{{.*}}, align 4
+// CHECK: store float 0.00e+00, float* %[[coerce1]].{{.*}}, align 4
+// CHECK: %[[cast1:.*]] = bitcast { float, float }* %[[coerce1]] to <2 x float>*
+// CHECK: %[[vector1:.*]] = load <2 x float>, <2 x float>* %[[cast1]], align 4
+// CHECK: call void @_Z3useiCf(i32 2, <2 x float> %[[vector1]])
+  use(3, ptr->complexValue);
+// CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8
+// CHECK: store float 4.20e+01, float* %[[coerce2:.*]].{{.*}}, align 4
+// CHECK: store float 0.00e+00, float* %[[coerce2]].{{.*}}, align 4
+// CHECK: %[[cast2:.*]] = bitcast { float, float }* %[[coerce2]] to <2 x float>*
+// CHECK: %[[vector2:.*]] = load <2 x float>, <2 x float>* %[[cast2]], align 4
+// CHECK: call void @_Z3useiCf(i32 3, <2 x float> %[[vector2]])
+  use(4, ref.complexValue);
+// CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8
+// CHECK: store float 4.20e+01, float* %[[coerce3:.*]].{{.*}}, align 4
+// CHECK: store float 0.00e+00, float* %[[coerce3]].{{.*}}, align 4
+// CHECK: %[[cast3:.*]] = bitcast { float, float }* %[[coerce3]] to <2 x float>*
+// CHECK: %[[vector3:.*]] = load <2 x float>, <2 x float>* %[[cast3]], align 4
+// CHECK: call void @_Z3useiCf(i32 4, <2 x float> %[[vector3]])
+  use(5, Struct(2).complexValue);
+// CHECK: call void @_ZN6StructC1Ei(%struct.Struct* %{{.*}}, i32 2)
+// CHECK: store float 4.20e+01, float* %[[coerce4:.*]].{{.*}}, align 4
+// CHECK: store float 0.00e+00, float* %[[coerce4]].{{.*}}, align 4
+// CHECK: %[[cast4:.*]] = bitcast { float, float }* %[[coerce4]] to <2 x float>*
+// CHECK: %[[vector4:.*]] = load <2 x float>, <2 x float>* %[[cast4]], align 4
+// CHECK: call void @_Z3useiCf(i32

[PATCH] D36354: [clang-tidy] Implement type-based check for `gsl::owner`

2017-08-23 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 112363.
JonasToth marked 3 inline comments as done.
JonasToth added a comment.

- adjust the diagnostics to include the types


https://reviews.llvm.org/D36354

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
  clang-tidy/cppcoreguidelines/OwningMemoryCheck.h
  clang-tidy/utils/Matchers.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-owning-memory.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-owning-memory.cpp

Index: test/clang-tidy/cppcoreguidelines-owning-memory.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-owning-memory.cpp
@@ -0,0 +1,348 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-owning-memory %t
+
+namespace gsl {
+template 
+using owner = T;
+} // namespace gsl
+
+template 
+class unique_ptr {
+public:
+  unique_ptr(gsl::owner resource) : memory(resource) {}
+  unique_ptr(const unique_ptr &) = default;
+
+  ~unique_ptr() { delete memory; }
+
+private:
+  gsl::owner memory;
+};
+
+void takes_owner(gsl::owner owned_int) {
+}
+
+void takes_pointer(int *unowned_int) {
+}
+
+void takes_owner_and_more(int some_int, gsl::owner owned_int, float f) {
+}
+
+template 
+void takes_templated_owner(gsl::owner owned_T) {
+}
+
+gsl::owner returns_owner1() { return gsl::owner(new int(42)); } // Ok
+gsl::owner returns_owner2() { return new int(42); } // Ok
+
+int *returns_no_owner1() { return nullptr; }
+int *returns_no_owner2() {
+  return new int(42);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a 'gsl::owner<>' from a function but not declaring it; return type is 'int *'
+}
+int *returns_no_owner3() {
+  int *should_be_owner = new int(42);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *' with a newly created 'gsl::owner<>'
+  return should_be_owner;
+}
+int *returns_no_owner4() {
+  gsl::owner owner = new int(42);
+  return owner;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a 'gsl::owner<>' from a function but not declaring it; return type is 'int *'
+}
+
+unique_ptr returns_no_owner5() {
+  return unique_ptr(new int(42)); // Ok
+}
+
+/// FIXME: CSA finds it, but the report is misleading.
+void csa_not_finding_leak() {
+  gsl::owner o1 = new int(42); // Ok
+
+  gsl::owner o2 = o1; // Ok
+  o2 = new int(45); // conceptual leak, the memory from o1 is now leaked, since its considered moved in the guidelines
+
+  delete o2;
+  // actual leak occurs here, its found, but mixed
+  delete o1;
+}
+
+void test_assignment_and_initialization() {
+  int stack_int1 = 15;
+  int stack_int2;
+
+  gsl::owner owned_int1 = &stack_int1; // BAD
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected initialization with value of type 'gsl::owner<>'; got 'int *'
+
+  gsl::owner owned_int2;
+  owned_int2 = &stack_int2; // BAD since no owner, bad since uninitialized
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected assignment source to be of type 'gsl::owner<>'; got 'int *'
+
+  gsl::owner owned_int3 = new int(42); // Good
+  owned_int3 = nullptr; // Good
+
+  gsl::owner owned_int4(nullptr); // Ok
+  owned_int4 = new int(42); // Good
+
+  gsl::owner owned_int5 = owned_int3; // Good
+
+  gsl::owner owned_int6{nullptr}; // Ok
+  owned_int6 = owned_int4; // Good
+
+  // FIXME:, flow analysis for the case of reassignment. Value must be released before
+  owned_int6 = owned_int3; // BAD, because reassignment without resource release
+
+  auto owned_int7 = returns_owner1(); // Bad, since typededuction eliminates the owner wrapper
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *' with a newly created 'gsl::owner<>'
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner
+
+  const auto owned_int8 = returns_owner2(); // Bad, since typededuction eliminates the owner wrapper
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *const' with a newly created 'gsl::owner<>'
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner
+
+  gsl::owner owned_int9 = returns_owner1(); // Ok
+  int *unowned_int3 = returns_owner1(); // Bad
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *' with a newly created 'gsl::owner<>'
+
+  gsl::owner owned_int10;
+  owned_int10 = returns_owner1(); // Ok
+
+  int *unowned_int4;
+  unowned_int4 = returns_owner1(); // Bad
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning newly created 'gsl::owner<>' to non-owner 'int *'
+
+  gsl::owner owned_int11 = returns_no_owner1(); // Bad since no owner
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected initialization with value of type 'gsl::owner<>'; got 'int *'
+
+  gsl::owner owned_int12;
+  owned_int12 = returns_no_owner1(); // Bad since no owner
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected

[PATCH] D36354: [clang-tidy] Implement type-based check for `gsl::owner`

2017-08-23 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

i think the diagnostics are better now, i added the expected and received type 
everywhere i could.


https://reviews.llvm.org/D36354



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


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

2017-08-23 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added inline comments.



Comment at: unittests/Format/FormatTest.cpp:2297
+   "#include \n"
+   "#define MACRO  
"
+   "\\\n"

Please just set Style.ColumnLimit to 60 or so in order not to have to wrap the 
test cases. Makes then much easier to understand.



Comment at: unittests/Format/FormatTest.cpp:2314
+   "#define MACRO  
"
+   "\\\n"
+   "  
some_very_long_func_a"

It's hard to tell with the line wrap, but this does look wrong, the escaped 
newline does not seem to be in column 80.



Comment at: unittests/Format/FormatTest.cpp:2427
+   Style));
+  // Defect: The comment indent corrector in TokenAnnotator gets thrown off by
+  // preprocessor indentation.

Write "FIXME" instead of "Defect"



Comment at: unittests/Format/FormatTestUtils.h:34
   InComment = true;
-} else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) {
+} else if (MessedUp[i] == '#' && (JustPassedNewline || i == 0)) {
   if (i != 0)

Could we just do:

  } else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0 || MessedUp[i 
- 1] == '\n') {

?


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] D36354: [clang-tidy] Implement type-based check for `gsl::owner`

2017-08-23 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 112364.
JonasToth added a comment.

remove unnecessary outcommented lines


https://reviews.llvm.org/D36354

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
  clang-tidy/cppcoreguidelines/OwningMemoryCheck.h
  clang-tidy/utils/Matchers.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-owning-memory.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-owning-memory.cpp

Index: test/clang-tidy/cppcoreguidelines-owning-memory.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-owning-memory.cpp
@@ -0,0 +1,348 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-owning-memory %t
+
+namespace gsl {
+template 
+using owner = T;
+} // namespace gsl
+
+template 
+class unique_ptr {
+public:
+  unique_ptr(gsl::owner resource) : memory(resource) {}
+  unique_ptr(const unique_ptr &) = default;
+
+  ~unique_ptr() { delete memory; }
+
+private:
+  gsl::owner memory;
+};
+
+void takes_owner(gsl::owner owned_int) {
+}
+
+void takes_pointer(int *unowned_int) {
+}
+
+void takes_owner_and_more(int some_int, gsl::owner owned_int, float f) {
+}
+
+template 
+void takes_templated_owner(gsl::owner owned_T) {
+}
+
+gsl::owner returns_owner1() { return gsl::owner(new int(42)); } // Ok
+gsl::owner returns_owner2() { return new int(42); } // Ok
+
+int *returns_no_owner1() { return nullptr; }
+int *returns_no_owner2() {
+  return new int(42);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a 'gsl::owner<>' from a function but not declaring it; return type is 'int *'
+}
+int *returns_no_owner3() {
+  int *should_be_owner = new int(42);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *' with a newly created 'gsl::owner<>'
+  return should_be_owner;
+}
+int *returns_no_owner4() {
+  gsl::owner owner = new int(42);
+  return owner;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a 'gsl::owner<>' from a function but not declaring it; return type is 'int *'
+}
+
+unique_ptr returns_no_owner5() {
+  return unique_ptr(new int(42)); // Ok
+}
+
+/// FIXME: CSA finds it, but the report is misleading.
+void csa_not_finding_leak() {
+  gsl::owner o1 = new int(42); // Ok
+
+  gsl::owner o2 = o1; // Ok
+  o2 = new int(45); // conceptual leak, the memory from o1 is now leaked, since its considered moved in the guidelines
+
+  delete o2;
+  // actual leak occurs here, its found, but mixed
+  delete o1;
+}
+
+void test_assignment_and_initialization() {
+  int stack_int1 = 15;
+  int stack_int2;
+
+  gsl::owner owned_int1 = &stack_int1; // BAD
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected initialization with value of type 'gsl::owner<>'; got 'int *'
+
+  gsl::owner owned_int2;
+  owned_int2 = &stack_int2; // BAD since no owner, bad since uninitialized
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected assignment source to be of type 'gsl::owner<>'; got 'int *'
+
+  gsl::owner owned_int3 = new int(42); // Good
+  owned_int3 = nullptr; // Good
+
+  gsl::owner owned_int4(nullptr); // Ok
+  owned_int4 = new int(42); // Good
+
+  gsl::owner owned_int5 = owned_int3; // Good
+
+  gsl::owner owned_int6{nullptr}; // Ok
+  owned_int6 = owned_int4; // Good
+
+  // FIXME:, flow analysis for the case of reassignment. Value must be released before
+  owned_int6 = owned_int3; // BAD, because reassignment without resource release
+
+  auto owned_int7 = returns_owner1(); // Bad, since typededuction eliminates the owner wrapper
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *' with a newly created 'gsl::owner<>'
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner
+
+  const auto owned_int8 = returns_owner2(); // Bad, since typededuction eliminates the owner wrapper
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *const' with a newly created 'gsl::owner<>'
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner
+
+  gsl::owner owned_int9 = returns_owner1(); // Ok
+  int *unowned_int3 = returns_owner1(); // Bad
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner 'int *' with a newly created 'gsl::owner<>'
+
+  gsl::owner owned_int10;
+  owned_int10 = returns_owner1(); // Ok
+
+  int *unowned_int4;
+  unowned_int4 = returns_owner1(); // Bad
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning newly created 'gsl::owner<>' to non-owner 'int *'
+
+  gsl::owner owned_int11 = returns_no_owner1(); // Bad since no owner
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected initialization with value of type 'gsl::owner<>'; got 'int *'
+
+  gsl::owner owned_int12;
+  owned_int12 = returns_no_owner1(); // Bad since no owner
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected assignment source to be of type 'gsl::owner<>'; got

r311557 - Revert r311552: [Bash-autocompletion] Add support for static analyzer flags

2017-08-23 Thread Rui Ueyama via cfe-commits
Author: ruiu
Date: Wed Aug 23 07:48:58 2017
New Revision: 311557

URL: http://llvm.org/viewvc/llvm-project?rev=311557&view=rev
Log:
Revert r311552: [Bash-autocompletion] Add support for static analyzer flags

This reverts commit r311552 because it broke ubsan and asan bots.

Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/lib/Driver/DriverOptions.cpp
cfe/trunk/test/Driver/autocomplete.c

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=311557&r1=311556&r2=311557&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Wed Aug 23 07:48:58 2017
@@ -99,19 +99,7 @@ def analyzer_stats : Flag<["-"], "analyz
   HelpText<"Print internal analyzer statistics.">;
 
 def analyzer_checker : Separate<["-"], "analyzer-checker">,
-  HelpText<"Choose analyzer checkers to enable">,
-  ValuesCode<[{
-const char *Values =
-#define GET_CHECKERS
-#define CHECKER(FULLNAME, CLASS, DESCFILE, HT, G, H)  FULLNAME ","
-#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
-#undef GET_CHECKERS
-#define GET_PACKAGES
-#define PACKAGE(FULLNAME, G, D)  FULLNAME ","
-#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
-#undef GET_PACKAGES
-;
-  }]>;
+  HelpText<"Choose analyzer checkers to enable">;
 def analyzer_checker_EQ : Joined<["-"], "analyzer-checker=">,
   Alias;
 

Modified: cfe/trunk/lib/Driver/DriverOptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/DriverOptions.cpp?rev=311557&r1=311556&r2=311557&view=diff
==
--- cfe/trunk/lib/Driver/DriverOptions.cpp (original)
+++ cfe/trunk/lib/Driver/DriverOptions.cpp Wed Aug 23 07:48:58 2017
@@ -11,7 +11,6 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
-#include 
 
 using namespace clang::driver;
 using namespace clang::driver::options;
@@ -41,13 +40,5 @@ public:
 }
 
 std::unique_ptr clang::driver::createDriverOptTable() {
-  auto Result = llvm::make_unique();
-  // Options.inc is included in DriverOptions.cpp, and calls OptTable's
-  // addValues function.
-  // Opt is a variable used in the code fragment in Options.inc.
-  OptTable &Opt = *Result;
-#define OPTTABLE_ARG_INIT
-#include "clang/Driver/Options.inc"
-#undef OPTTABLE_ARG_INIT
-  return std::move(Result);
+  return llvm::make_unique();
 }

Modified: cfe/trunk/test/Driver/autocomplete.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/autocomplete.c?rev=311557&r1=311556&r2=311557&view=diff
==
--- cfe/trunk/test/Driver/autocomplete.c (original)
+++ cfe/trunk/test/Driver/autocomplete.c Wed Aug 23 07:48:58 2017
@@ -93,5 +93,3 @@
 // WARNING-NEXT: -Wmax-unsigned-zero
 // RUN: %clang --autocomplete=-Wno-invalid-pp- | FileCheck %s 
-check-prefix=NOWARNING
 // NOWARNING: -Wno-invalid-pp-token
-// RUN: %clang --autocomplete=-analyzer-checker, | FileCheck %s 
-check-prefix=ANALYZER
-// ANALYZER: unix.Malloc


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


Re: r284549 - DR1330: instantiate exception-specifications when "needed". We previously did

2017-08-23 Thread Alex L via cfe-commits
Hi Richard,

It looks like this commit caused PR34298 (https://bugs.llvm.org/show_bu
g.cgi?id=34298). Now Clang fails to compile a libc++ std::function member
variable with an incomplete return type. Libstdc++ works though, so I
assume that the right way to fix this is to change libc++?

Cheers,
Alex

On 19 October 2016 at 00:39, Richard Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: rsmith
> Date: Tue Oct 18 18:39:12 2016
> New Revision: 284549
>
> URL: http://llvm.org/viewvc/llvm-project?rev=284549&view=rev
> Log:
> DR1330: instantiate exception-specifications when "needed". We previously
> did
> not instantiate exception specifications of functions if they were only
> used in
> unevaluated contexts (other than 'noexcept' expressions).
>
> In C++17 onwards, this becomes essential since the exception specification
> is
> now part of the function's type.
>
> Note that this means that constructs like the following no longer work:
>
>   struct A {
> static T f() noexcept(...);
> decltype(f()) *p;
>   };
>
> ... because the decltype expression now needs the exception specification
> of
> 'f', which has not yet been parsed.
>
> Modified:
> cfe/trunk/lib/Sema/SemaExpr.cpp
> cfe/trunk/lib/Sema/SemaOverload.cpp
> cfe/trunk/test/CXX/drs/dr13xx.cpp
> cfe/trunk/test/SemaCXX/constant-expression-cxx1z.cpp
> cfe/trunk/test/SemaCXX/cxx0x-defaulted-functions.cpp
> cfe/trunk/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
> cfe/trunk/test/SemaTemplate/instantiate-exception-spec-cxx11.cpp
> cfe/trunk/www/cxx_dr_status.html
>
> Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/
> SemaExpr.cpp?rev=284549&r1=284548&r2=284549&view=diff
> 
> ==
> --- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaExpr.cpp Tue Oct 18 18:39:12 2016
> @@ -2889,6 +2889,14 @@ ExprResult Sema::BuildDeclarationNameExp
>
>{
>  QualType type = VD->getType();
> +if (auto *FPT = type->getAs()) {
> +  // C++ [except.spec]p17:
> +  //   An exception-specification is considered to be needed when:
> +  //   - in an expression, the function is the unique lookup result or
> +  // the selected member of a set of overloaded functions.
> +  ResolveExceptionSpec(Loc, FPT);
> +  type = VD->getType();
> +}
>  ExprValueKind valueKind = VK_RValue;
>
>  switch (D->getKind()) {
> @@ -13138,6 +13146,19 @@ void Sema::MarkFunctionReferenced(Source
> Func->getMemberSpecializationInfo()))
>  checkSpecializationVisibility(Loc, Func);
>
> +  // C++14 [except.spec]p17:
> +  //   An exception-specification is considered to be needed when:
> +  //   - the function is odr-used or, if it appears in an unevaluated
> operand,
> +  // would be odr-used if the expression were potentially-evaluated;
> +  //
> +  // Note, we do this even if MightBeOdrUse is false. That indicates that
> the
> +  // function is a pure virtual function we're calling, and in that case
> the
> +  // function was selected by overload resolution and we need to resolve
> its
> +  // exception specification for a different reason.
> +  const FunctionProtoType *FPT = Func->getType()->getAs<
> FunctionProtoType>();
> +  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
> +ResolveExceptionSpec(Loc, FPT);
> +
>// If we don't need to mark the function as used, and we don't need to
>// try to provide a definition, there's nothing more to do.
>if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
> @@ -13196,12 +13217,6 @@ void Sema::MarkFunctionReferenced(Source
>// FIXME: Is this really right?
>if (CurContext == Func) return;
>
> -  // Resolve the exception specification for any function which is
> -  // used: CodeGen will need it.
> -  const FunctionProtoType *FPT = Func->getType()->getAs<
> FunctionProtoType>();
> -  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
> -ResolveExceptionSpec(Loc, FPT);
> -
>// Implicit instantiation of function templates and member functions of
>// class templates.
>if (Func->isImplicitlyInstantiable()) {
>
> Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/
> SemaOverload.cpp?rev=284549&r1=284548&r2=284549&view=diff
> 
> ==
> --- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaOverload.cpp Tue Oct 18 18:39:12 2016
> @@ -13166,6 +13166,13 @@ Expr *Sema::FixOverloadedFunctionReferen
> UnOp->getOperatorLoc());
>}
>
> +  // C++ [except.spec]p17:
> +  //   An exception-specification is considered to be needed when:
> +  //   - in an expression the function is the unique lookup result or the
> +  // selected member of a set of overl

r311559 - [clang-format] Emit absolute splits before lines for comments

2017-08-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Aug 23 08:16:47 2017
New Revision: 311559

URL: http://llvm.org/viewvc/llvm-project?rev=311559&view=rev
Log:
[clang-format] Emit absolute splits before lines for comments

Summary:
This patch makes the splits emitted for the beginning of comment lines during
reformatting absolute. Previously, they were relative to the start of the
non-whitespace content of the line, which messes up further TailOffset
calculations in breakProtrudingToken. This fixes an assertion failure reported
in bug 34236: https://bugs.llvm.org/show_bug.cgi?id=34236.

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=311559&r1=311558&r2=311559&view=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Wed Aug 23 08:16:47 2017
@@ -545,15 +545,18 @@ void BreakableBlockComment::insertBreak(
 }
 
 BreakableToken::Split BreakableBlockComment::getSplitBefore(
-unsigned LineIndex,
-unsigned PreviousEndColumn,
-unsigned ColumnLimit,
+unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
 llvm::Regex &CommentPragmasRegex) const {
   if (!mayReflow(LineIndex, CommentPragmasRegex))
 return Split(StringRef::npos, 0);
   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
-  return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
-ColumnLimit);
+  Split Result = getReflowSplit(TrimmedContent, ReflowPrefix, 
PreviousEndColumn,
+ColumnLimit);
+  // Result is relative to TrimmedContent. Adapt it relative to
+  // Content[LineIndex].
+  if (Result.first != StringRef::npos)
+Result.first += Content[LineIndex].size() - TrimmedContent.size();
+  return Result;
 }
 
 unsigned BreakableBlockComment::getReflownColumn(
@@ -633,17 +636,12 @@ void BreakableBlockComment::replaceWhite
 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
 /*Spaces=*/0);
 // Check if we need to also insert a break at the whitespace range.
-// For this we first adapt the reflow split relative to the beginning of 
the
-// content.
 // Note that we don't need a penalty for this break, since it doesn't 
change
 // the total number of lines.
-Split BreakSplit = SplitBefore;
-BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
 unsigned ReflownColumn =
 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
-if (ReflownColumn > ColumnLimit) {
-  insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
-}
+if (ReflownColumn > ColumnLimit)
+  insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
 return;
   }
 

Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=311559&r1=311558&r2=311559&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp Wed Aug 23 08:16:47 2017
@@ -2803,6 +2803,23 @@ TEST_F(FormatTestComments, NonTrailingBl
"A = B;",
getLLVMStyleWithColumns(40)));
 }
+
+TEST_F(FormatTestComments, NoCrush_Bug34236) {
+  // This is a test case from a crasher reported in:
+  // https://bugs.llvm.org/show_bug.cgi?id=34236
+  EXPECT_EQ(
+  R"(
+/**/ /*
+  *   a
+  * b c
+  * d*/)",
+  format(
+  R"(
+/**/ /*
+ *   a b
+ *   c d*/)",
+  getLLVMStyleWithColumns(80)));
+}
 } // 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] D36956: [clang-format] Emit absolute splits before lines for comments

2017-08-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311559: [clang-format] Emit absolute splits before lines for 
comments (authored by krasimir).

Changed prior to commit:
  https://reviews.llvm.org/D36956?vs=112147&id=112372#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D36956

Files:
  cfe/trunk/lib/Format/BreakableToken.cpp
  cfe/trunk/unittests/Format/FormatTestComments.cpp


Index: cfe/trunk/lib/Format/BreakableToken.cpp
===
--- cfe/trunk/lib/Format/BreakableToken.cpp
+++ cfe/trunk/lib/Format/BreakableToken.cpp
@@ -545,15 +545,18 @@
 }
 
 BreakableToken::Split BreakableBlockComment::getSplitBefore(
-unsigned LineIndex,
-unsigned PreviousEndColumn,
-unsigned ColumnLimit,
+unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
 llvm::Regex &CommentPragmasRegex) const {
   if (!mayReflow(LineIndex, CommentPragmasRegex))
 return Split(StringRef::npos, 0);
   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
-  return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
-ColumnLimit);
+  Split Result = getReflowSplit(TrimmedContent, ReflowPrefix, 
PreviousEndColumn,
+ColumnLimit);
+  // Result is relative to TrimmedContent. Adapt it relative to
+  // Content[LineIndex].
+  if (Result.first != StringRef::npos)
+Result.first += Content[LineIndex].size() - TrimmedContent.size();
+  return Result;
 }
 
 unsigned BreakableBlockComment::getReflownColumn(
@@ -633,17 +636,12 @@
 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
 /*Spaces=*/0);
 // Check if we need to also insert a break at the whitespace range.
-// For this we first adapt the reflow split relative to the beginning of 
the
-// content.
 // Note that we don't need a penalty for this break, since it doesn't 
change
 // the total number of lines.
-Split BreakSplit = SplitBefore;
-BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
 unsigned ReflownColumn =
 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
-if (ReflownColumn > ColumnLimit) {
-  insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
-}
+if (ReflownColumn > ColumnLimit)
+  insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
 return;
   }
 
Index: cfe/trunk/unittests/Format/FormatTestComments.cpp
===
--- cfe/trunk/unittests/Format/FormatTestComments.cpp
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp
@@ -2803,6 +2803,23 @@
"A = B;",
getLLVMStyleWithColumns(40)));
 }
+
+TEST_F(FormatTestComments, NoCrush_Bug34236) {
+  // This is a test case from a crasher reported in:
+  // https://bugs.llvm.org/show_bug.cgi?id=34236
+  EXPECT_EQ(
+  R"(
+/**/ /*
+  *   a
+  * b c
+  * d*/)",
+  format(
+  R"(
+/**/ /*
+ *   a b
+ *   c d*/)",
+  getLLVMStyleWithColumns(80)));
+}
 } // end namespace
 } // end namespace format
 } // end namespace clang


Index: cfe/trunk/lib/Format/BreakableToken.cpp
===
--- cfe/trunk/lib/Format/BreakableToken.cpp
+++ cfe/trunk/lib/Format/BreakableToken.cpp
@@ -545,15 +545,18 @@
 }
 
 BreakableToken::Split BreakableBlockComment::getSplitBefore(
-unsigned LineIndex,
-unsigned PreviousEndColumn,
-unsigned ColumnLimit,
+unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
 llvm::Regex &CommentPragmasRegex) const {
   if (!mayReflow(LineIndex, CommentPragmasRegex))
 return Split(StringRef::npos, 0);
   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
-  return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
-ColumnLimit);
+  Split Result = getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
+ColumnLimit);
+  // Result is relative to TrimmedContent. Adapt it relative to
+  // Content[LineIndex].
+  if (Result.first != StringRef::npos)
+Result.first += Content[LineIndex].size() - TrimmedContent.size();
+  return Result;
 }
 
 unsigned BreakableBlockComment::getReflownColumn(
@@ -633,17 +636,12 @@
 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
 /*Spaces=*/0);
 // Check if we need to also insert a break at the whitespace range.
-// For this we first adapt the reflow split relative to the beginning of the
-/

[PATCH] D37004: [clang-diff] Fix the html output for CXXOperatorCallExpr

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



Comment at: test/Tooling/clang-diff-ast.cpp:42
 // CHECK: CXXRecordDecl: X;X;(
-class X : Base {
+struct X : Base {
   int m;

Looks like an unrelated change.


https://reviews.llvm.org/D37004



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


[PATCH] D37004: [clang-diff] Fix the html output for CXXOperatorCallExpr

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



Comment at: test/Tooling/clang-diff-ast.cpp:113
+
+// CHECK: CXXOperatorCallExpr
+// CHECK-NEXT: DeclRefExpr: str::operator+

This test doesn't work because it passes prior to this patch. You should test 
the HTML output instead.


https://reviews.llvm.org/D37004



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


r311561 - Implement CFG construction for __try / __except / __leave.

2017-08-23 Thread Nico Weber via cfe-commits
Author: nico
Date: Wed Aug 23 08:33:16 2017
New Revision: 311561

URL: http://llvm.org/viewvc/llvm-project?rev=311561&view=rev
Log:
Implement CFG construction for __try / __except / __leave.

This makes -Wunreachable-code work for programs containing SEH (except for
__finally, which is still missing for now).

__try is modeled like try (but simpler since it can only have a single __except
or __finally), __except is fairly similar to catch (but simpler, since it can't
contain declarations). __leave is implemented similarly to break / continue.

Use the existing addTryDispatchBlock infrastructure (which
FindUnreachableCode() in ReachableCode.cpp uses via cfg->try_blocks_begin()) to
mark things in the __except blocks as reachable.

Re-use TryTerminatedBlock. This means we add EH edges from calls to the __try
block, but not from all other statements. While this is incomplete, it matches
LLVM's SEH codegen support. Also, in practice, BuildOpts.AddEHEdges is always
false in practice from what I can tell, so we never even insert the call EH
edges either.

https://reviews.llvm.org/D36914

Added:
cfe/trunk/test/Sema/warn-unreachable-ms.c
Modified:
cfe/trunk/lib/Analysis/CFG.cpp

Modified: cfe/trunk/lib/Analysis/CFG.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/CFG.cpp?rev=311561&r1=311560&r2=311561&view=diff
==
--- cfe/trunk/lib/Analysis/CFG.cpp (original)
+++ cfe/trunk/lib/Analysis/CFG.cpp Wed Aug 23 08:33:16 2017
@@ -395,12 +395,16 @@ class CFGBuilder {
   ASTContext *Context;
   std::unique_ptr cfg;
 
-  CFGBlock *Block;
-  CFGBlock *Succ;
+  CFGBlock *Block;  // Current block.
+  CFGBlock *Succ;  // Block after the current block.
   JumpTarget ContinueJumpTarget;
   JumpTarget BreakJumpTarget;
+  JumpTarget SEHLeaveJumpTarget;
   CFGBlock *SwitchTerminatedBlock;
   CFGBlock *DefaultCaseBlock;
+
+  // This can point either to a try or a __try block. The frontend forbids
+  // mixing both kinds in one function, so having one for both is enough.
   CFGBlock *TryTerminatedBlock;
 
   // Current position in local scope.
@@ -436,13 +440,12 @@ class CFGBuilder {
 
 public:
   explicit CFGBuilder(ASTContext *astContext,
-  const CFG::BuildOptions &buildOpts) 
-: Context(astContext), cfg(new CFG()), // crew a new CFG
-  Block(nullptr), Succ(nullptr),
-  SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
-  TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
-  switchExclusivelyCovered(false), switchCond(nullptr),
-  cachedEntry(nullptr), lastLookup(nullptr) {}
+  const CFG::BuildOptions &buildOpts)
+  : Context(astContext), cfg(new CFG()), // crew a new CFG
+Block(nullptr), Succ(nullptr), SwitchTerminatedBlock(nullptr),
+DefaultCaseBlock(nullptr), TryTerminatedBlock(nullptr), badCFG(false),
+BuildOpts(buildOpts), switchExclusivelyCovered(false),
+switchCond(nullptr), cachedEntry(nullptr), lastLookup(nullptr) {}
 
   // buildCFG - Used by external clients to construct the CFG.
   std::unique_ptr buildCFG(const Decl *D, Stmt *Statement);
@@ -501,6 +504,10 @@ private:
   CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
   CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
   CFGBlock *VisitReturnStmt(ReturnStmt *R);
+  CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
+  CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
+  CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
+  CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
   CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
   CFGBlock *VisitSwitchStmt(SwitchStmt *S);
   CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
@@ -1731,6 +1738,18 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, Ad
 case Stmt::ReturnStmtClass:
   return VisitReturnStmt(cast(S));
 
+case Stmt::SEHExceptStmtClass:
+  return VisitSEHExceptStmt(cast(S));
+
+case Stmt::SEHFinallyStmtClass:
+  return VisitSEHFinallyStmt(cast(S));
+
+case Stmt::SEHLeaveStmtClass:
+  return VisitSEHLeaveStmt(cast(S));
+
+case Stmt::SEHTryStmtClass:
+  return VisitSEHTryStmt(cast(S));
+
 case Stmt::UnaryExprOrTypeTraitExprClass:
   return VisitUnaryExprOrTypeTraitExpr(cast(S),
asc);
@@ -2462,6 +2481,117 @@ CFGBlock *CFGBuilder::VisitReturnStmt(Re
   return VisitStmt(R, AddStmtChoice::AlwaysAdd);
 }
 
+CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
+  // SEHExceptStmt are treated like labels, so they are the first statement in 
a
+  // block.
+
+  // Save local scope position because in case of exception variable ScopePos
+  // won't be restored when traversing AST.
+  SaveAndRestore save_scope_pos(ScopePos);
+
+  addStmt(ES->getBlock());
+  CFGBlock *SEHExceptBlock = Block;
+  if (!SEHExceptBlock)
+SEHExceptBlock = createBlock();
+
+  appendStmt(SEHExceptBlock, ES);

Re: [PATCH] D36914: Implement CFG construction for __try / __except / __leave.

2017-08-23 Thread Nico Weber via cfe-commits
On Tue, Aug 22, 2017 at 9:23 PM, Reid Kleckner via Phabricator via
cfe-commits  wrote:

> rnk accepted this revision.
> rnk added a comment.
> This revision is now accepted and ready to land.
>

311561, thanks!


> Looks good!
>
>
>
> 
> Comment at: test/Sema/warn-unreachable-ms.c:42
> +  }
> +}
> 
> rnk wrote:
> > Can we add a test to exercise that this builds the right CFG?
> > ```
> > __try {
> >   __try {
> > f();
> >   } __except(1) {
> > __leave; // should exit outer try
> >   }
> >   __leave;
> >   f(); // expected-warning{{never be executed}}
> > } __except(1) {
> > }
> > ```
> > Sure. Did you intentionally put two __leaves in there, or do you only
> want the one in the inner __except?
>
> I think both are required to trigger the warning in case f() doesn't
> throw, but I could be wrong.
>

Oh, that way round. But if f() throws and I omit the first __leave, then
the __except() block will just do nothing and fall through to the second
__leave and we'll still get the warning, right?
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] r311562 - unwind: explicitly align `_Unwind_Control_Block`

2017-08-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Wed Aug 23 08:33:45 2017
New Revision: 311562

URL: http://llvm.org/viewvc/llvm-project?rev=311562&view=rev
Log:
unwind: explicitly align `_Unwind_Control_Block`

The C++ ABI requires that the exception object is double-word aligned.
The alignment attribute was applied to the `_Unwind_Exception` type
which is used on non-EHABI targets.  On EHABI, the exception object type
is `_Unwind_Control_Block`.  Apply the explicit maximal alignment on the
type to ensure that the allocation has the correct alignment.

Resolves PR33858!

Modified:
libunwind/trunk/include/unwind.h

Modified: libunwind/trunk/include/unwind.h
URL: 
http://llvm.org/viewvc/llvm-project/libunwind/trunk/include/unwind.h?rev=311562&r1=311561&r2=311562&view=diff
==
--- libunwind/trunk/include/unwind.h (original)
+++ libunwind/trunk/include/unwind.h Wed Aug 23 08:33:45 2017
@@ -100,7 +100,7 @@ struct _Unwind_Control_Block {
   } pr_cache;
 
   long long int :0; /* Enforce the 8-byte alignment */
-};
+} __attribute__((__aligned__));
 
 typedef _Unwind_Reason_Code (*_Unwind_Stop_Fn)
   (_Unwind_State state,


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


r311563 - Headers: give _Unwind_Control_Block double-word alignment

2017-08-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Wed Aug 23 08:35:33 2017
New Revision: 311563

URL: http://llvm.org/viewvc/llvm-project?rev=311563&view=rev
Log:
Headers: give _Unwind_Control_Block double-word alignment

The C++ ABI requires that the exception object (which under AEABI is the
`_Unwind_Control_Block`) is double-word aligned.  The attribute was
applied to the `_Unwind_Exception` type, but not the
`_Unwind_Control_Block`.  This should fix the libunwind test for the
alignment of the exception type.

Modified:
cfe/trunk/lib/Headers/unwind.h

Modified: cfe/trunk/lib/Headers/unwind.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/unwind.h?rev=311563&r1=311562&r2=311563&view=diff
==
--- cfe/trunk/lib/Headers/unwind.h (original)
+++ cfe/trunk/lib/Headers/unwind.h Wed Aug 23 08:35:33 2017
@@ -149,7 +149,7 @@ struct _Unwind_Control_Block {
 uint32_t reserved1;
   } pr_cache;
   long long int : 0; /* force alignment of next item to 8-byte boundary */
-};
+} __attribute__((__aligned__));
 #else
 struct _Unwind_Exception {
   _Unwind_Exception_Class exception_class;


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


[PATCH] D37002: [clang-diff] Treat CXXCtorInitializer as a node

2017-08-23 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 one request below:




Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:954
   }
-  // We need to subtract 1 to get the number of descendants excluding the root.
+  // We need to subtract 1 to get the number of descendants excluding the
+  // root.

Looks like an unrelated formatting change, please pre-commit it instead.


https://reviews.llvm.org/D37002



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


Re: r311563 - Headers: give _Unwind_Control_Block double-word alignment

2017-08-23 Thread Saleem Abdulrasool via cfe-commits
Hans,

Can we get this merged to the 5.0 branch as well?  This corresponds to the
libunwind fix for the alignment of the exception type.

Thanks!

On Wed, Aug 23, 2017 at 8:36 AM Saleem Abdulrasool via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: compnerd
> Date: Wed Aug 23 08:35:33 2017
> New Revision: 311563
>
> URL: http://llvm.org/viewvc/llvm-project?rev=311563&view=rev
> Log:
> Headers: give _Unwind_Control_Block double-word alignment
>
> The C++ ABI requires that the exception object (which under AEABI is the
> `_Unwind_Control_Block`) is double-word aligned.  The attribute was
> applied to the `_Unwind_Exception` type, but not the
> `_Unwind_Control_Block`.  This should fix the libunwind test for the
> alignment of the exception type.
>
> Modified:
> cfe/trunk/lib/Headers/unwind.h
>
> Modified: cfe/trunk/lib/Headers/unwind.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/unwind.h?rev=311563&r1=311562&r2=311563&view=diff
>
> ==
> --- cfe/trunk/lib/Headers/unwind.h (original)
> +++ cfe/trunk/lib/Headers/unwind.h Wed Aug 23 08:35:33 2017
> @@ -149,7 +149,7 @@ struct _Unwind_Control_Block {
>  uint32_t reserved1;
>} pr_cache;
>long long int : 0; /* force alignment of next item to 8-byte boundary */
> -};
> +} __attribute__((__aligned__));
>  #else
>  struct _Unwind_Exception {
>_Unwind_Exception_Class exception_class;
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
-- 
Saleem Abdulrasool
compnerd (at) compnerd (dot) org
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37066: [clang-tidy] A follow-up fix of braced-init-list constructors in make-unique check.

2017-08-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
Herald added subscribers: xazax.hun, JDevlieghere.

https://reviews.llvm.org/D37066

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
  test/clang-tidy/modernize-make-unique.cpp


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -43,6 +43,10 @@
   G(int);
 };
 
+struct H {
+  H(std::vector);
+};
+
 namespace {
 class Foo {};
 } // namespace
@@ -316,6 +320,13 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PG3 = std::unique_ptr(new G{1, 2});
 
+  std::unique_ptr PH1 = std::unique_ptr(new H({1, 2, 3}));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH1 = std::unique_ptr(new H({1, 2, 
3}));
+  PH1.reset(new H({1, 2, 3}));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH1.reset(new H({1, 2, 3}));
+
   std::unique_ptr FF = std::unique_ptr(new Foo());
   // CHECK-MESSAGES: :[[@LINE-1]]:29: warning:
   // CHECK-FIXES: std::unique_ptr FF = std::make_unique();
Index: test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
===
--- test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
+++ test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
@@ -22,4 +22,10 @@
   const _E *begin() const { return __begin_; }
   const _E *end() const { return __begin_ + __size_; }
 };
+
+template 
+class vector {
+ public:
+  vector(initializer_list<_E> init);
+};
 } // namespace std
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -262,20 +262,24 @@
 break;
   }
   case CXXNewExpr::CallInit: {
-// FIXME: Add fixes for constructors with initializer-list parameters.
+// FIXME: Add fixes for constructors with parameters that can be created
+// with a C++11 braced-init-list (e.g. std::vector, std::map).
 // Unlike ordinal cases, braced list can not be deduced in
 // std::make_smart_ptr, we need to specify the type explicitly in the 
fixes:
 //   struct S { S(std::initializer_list, int); };
+//   struct S2 { S2(std::vector); };
 //   smart_ptr(new S({1, 2, 3}, 1));  // C++98 call-style initialization
 //   smart_ptr(new S({}, 1));
+//   smart_ptr(new S2({1, 2, 3}));
 // The above samples have to be replaced with:
 //   std::make_smart_ptr(std::initializer_list({1, 2, 3}), 1);
 //   std::make_smart_ptr(std::initializer_list({}), 1);
+//   std::make_smart_ptr(std::vector({1, 2, 3}));
 if (const auto *CE = New->getConstructExpr()) {
-  for (const auto *Arg : CE->arguments()) {
-if (llvm::isa(Arg)) {
-  return false;
-}
+  if (!ast_matchers::match(findAll(cxxStdInitializerListExpr()), *CE,
+   CE->getConstructor()->getASTContext())
+   .empty()) {
+return false;
   }
 }
 if (ArraySizeExpr.empty()) {


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -43,6 +43,10 @@
   G(int);
 };
 
+struct H {
+  H(std::vector);
+};
+
 namespace {
 class Foo {};
 } // namespace
@@ -316,6 +320,13 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PG3 = std::unique_ptr(new G{1, 2});
 
+  std::unique_ptr PH1 = std::unique_ptr(new H({1, 2, 3}));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH1 = std::unique_ptr(new H({1, 2, 3}));
+  PH1.reset(new H({1, 2, 3}));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH1.reset(new H({1, 2, 3}));
+
   std::unique_ptr FF = std::unique_ptr(new Foo());
   // CHECK-MESSAGES: :[[@LINE-1]]:29: warning:
   // CHECK-FIXES: std::unique_ptr FF = std::make_unique();
Index: test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
===
--- test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
+++ test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h
@@ -22,4 +22,10 @@
   const _E *begin() const { return __begin_; }
   const _E *end() const { return __begin_ + __size_; }
 };
+
+template 
+class vector {
+ public:
+  vector(initializer_list<_E> init);
+};
 } // namespace std
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
=

r311566 - Revert "[clang-format] Emit absolute splits before lines for comments"

2017-08-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Aug 23 08:58:10 2017
New Revision: 311566

URL: http://llvm.org/viewvc/llvm-project?rev=311566&view=rev
Log:
Revert "[clang-format] Emit absolute splits before lines for comments"

This reverts commit r311559, which added a test containing raw string
literals in macros, which chokes gcc:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55971

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=311566&r1=311565&r2=311566&view=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Wed Aug 23 08:58:10 2017
@@ -545,18 +545,15 @@ void BreakableBlockComment::insertBreak(
 }
 
 BreakableToken::Split BreakableBlockComment::getSplitBefore(
-unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
+unsigned LineIndex,
+unsigned PreviousEndColumn,
+unsigned ColumnLimit,
 llvm::Regex &CommentPragmasRegex) const {
   if (!mayReflow(LineIndex, CommentPragmasRegex))
 return Split(StringRef::npos, 0);
   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
-  Split Result = getReflowSplit(TrimmedContent, ReflowPrefix, 
PreviousEndColumn,
-ColumnLimit);
-  // Result is relative to TrimmedContent. Adapt it relative to
-  // Content[LineIndex].
-  if (Result.first != StringRef::npos)
-Result.first += Content[LineIndex].size() - TrimmedContent.size();
-  return Result;
+  return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
+ColumnLimit);
 }
 
 unsigned BreakableBlockComment::getReflownColumn(
@@ -636,12 +633,17 @@ void BreakableBlockComment::replaceWhite
 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
 /*Spaces=*/0);
 // Check if we need to also insert a break at the whitespace range.
+// For this we first adapt the reflow split relative to the beginning of 
the
+// content.
 // Note that we don't need a penalty for this break, since it doesn't 
change
 // the total number of lines.
+Split BreakSplit = SplitBefore;
+BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
 unsigned ReflownColumn =
 getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
-if (ReflownColumn > ColumnLimit)
-  insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
+if (ReflownColumn > ColumnLimit) {
+  insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
+}
 return;
   }
 

Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=311566&r1=311565&r2=311566&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp Wed Aug 23 08:58:10 2017
@@ -2803,23 +2803,6 @@ TEST_F(FormatTestComments, NonTrailingBl
"A = B;",
getLLVMStyleWithColumns(40)));
 }
-
-TEST_F(FormatTestComments, NoCrush_Bug34236) {
-  // This is a test case from a crasher reported in:
-  // https://bugs.llvm.org/show_bug.cgi?id=34236
-  EXPECT_EQ(
-  R"(
-/**/ /*
-  *   a
-  * b c
-  * d*/)",
-  format(
-  R"(
-/**/ /*
- *   a b
- *   c d*/)",
-  getLLVMStyleWithColumns(80)));
-}
 } // 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] D36914: Implement CFG construction for __try / __except / __leave.

2017-08-23 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: test/Sema/warn-unreachable-ms.c:42
+  }
+}

rnk wrote:
> rnk wrote:
> > Can we add a test to exercise that this builds the right CFG?
> > ```
> > __try {
> >   __try {
> > f();
> >   } __except(1) {
> > __leave; // should exit outer try
> >   }
> >   __leave;
> >   f(); // expected-warning{{never be executed}}
> > } __except(1) {
> > }
> > ```
> > Sure. Did you intentionally put two __leaves in there, or do you only want 
> > the one in the inner __except?
> 
> I think both are required to trigger the warning in case f() doesn't throw, 
> but I could be wrong.
I woke up this morning and realized what you meant. Is there another way we can 
check that __leave in __except exits the outer __try?


https://reviews.llvm.org/D36914



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


[PATCH] D37066: [clang-tidy] A follow-up fix of braced-init-list constructors in make-unique check.

2017-08-23 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tidy/modernize/MakeSmartPtrCheck.cpp:279
 if (const auto *CE = New->getConstructExpr()) {
-  for (const auto *Arg : CE->arguments()) {
-if (llvm::isa(Arg)) {
-  return false;
-}
+  if (!ast_matchers::match(findAll(cxxStdInitializerListExpr()), *CE,
+   CE->getConstructor()->getASTContext())

I wonder whether this exception can be too broad, e.g. if the initializer list 
is a part of a more deeply nested expression inside the CXXConstructExpr?


https://reviews.llvm.org/D37066



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


r311569 - [analyzer] Make StmtDataCollector customizable

2017-08-23 Thread Johannes Altmanninger via cfe-commits
Author: krobelus
Date: Wed Aug 23 09:28:26 2017
New Revision: 311569

URL: http://llvm.org/viewvc/llvm-project?rev=311569&view=rev
Log:
[analyzer] Make StmtDataCollector customizable

Summary:
This moves the data collection macro calls for Stmt nodes
to lib/AST/StmtDataCollectors.inc

Users can subclass ConstStmtVisitor and include StmtDataCollectors.inc
to define visitor methods for each Stmt subclass. This makes it also
possible to customize the visit methods as exemplified in
lib/Analysis/CloneDetection.cpp.

Move helper methods for data collection to a new module,
AST/DataCollection.

Add data collection for DeclRefExpr, MemberExpr and some literals.

Reviewers: arphaman, teemperor!

Subscribers: mgorny, xazax.hun, cfe-commits

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

Added:
cfe/trunk/include/clang/AST/DataCollection.h
cfe/trunk/lib/AST/DataCollection.cpp
cfe/trunk/lib/AST/StmtDataCollectors.inc
cfe/trunk/unittests/AST/DataCollectionTest.cpp
Modified:
cfe/trunk/include/clang/Analysis/CloneDetection.h
cfe/trunk/lib/AST/CMakeLists.txt
cfe/trunk/lib/Analysis/CloneDetection.cpp
cfe/trunk/unittests/AST/CMakeLists.txt

Added: cfe/trunk/include/clang/AST/DataCollection.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DataCollection.h?rev=311569&view=auto
==
--- cfe/trunk/include/clang/AST/DataCollection.h (added)
+++ cfe/trunk/include/clang/AST/DataCollection.h Wed Aug 23 09:28:26 2017
@@ -0,0 +1,65 @@
+//===--- DatatCollection.h --*- C++ 
-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+/// \file
+/// \brief This file declares helper methods for collecting data from AST 
nodes.
+///
+/// To collect data from Stmt nodes, subclass ConstStmtVisitor and include
+/// StmtDataCollectors.inc after defining the macros that you need. This
+/// provides data collection implementations for most Stmt kinds. Note
+/// that that code requires some conditions to be met:
+///
+///   - There must be a method addData(const T &Data) that accepts strings,
+/// integral types as well as QualType. All data is forwarded using
+/// to this method.
+///   - The ASTContext of the Stmt must be accessible by the name Context.
+///
+/// It is also possible to override individual visit methods. Have a look at
+/// the DataCollector in lib/Analysis/CloneDetection.cpp for a usage example.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_AST_DATACOLLECTION_H
+#define LLVM_CLANG_AST_DATACOLLECTION_H
+
+#include "clang/AST/ASTContext.h"
+
+namespace clang {
+namespace data_collection {
+
+/// Returns a string that represents all macro expansions that expanded into 
the
+/// given SourceLocation.
+///
+/// If 'getMacroStack(A) == getMacroStack(B)' is true, then the SourceLocations
+/// A and B are expanded from the same macros in the same order.
+std::string getMacroStack(SourceLocation Loc, ASTContext &Context);
+
+/// Utility functions for implementing addData() for a consumer that has a
+/// method update(StringRef)
+template 
+void addDataToConsumer(T &DataConsumer, llvm::StringRef Str) {
+  DataConsumer.update(Str);
+}
+
+template  void addDataToConsumer(T &DataConsumer, const QualType &QT) 
{
+  addDataToConsumer(DataConsumer, QT.getAsString());
+}
+
+template 
+typename std::enable_if<
+std::is_integral::value || std::is_enum::value ||
+std::is_convertible::value // for llvm::hash_code
+>::type
+addDataToConsumer(T &DataConsumer, Type Data) {
+  DataConsumer.update(StringRef(reinterpret_cast(&Data), 
sizeof(Data)));
+}
+
+} // end namespace data_collection
+} // end namespace clang
+
+#endif // LLVM_CLANG_AST_DATACOLLECTION_H

Modified: cfe/trunk/include/clang/Analysis/CloneDetection.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/CloneDetection.h?rev=311569&r1=311568&r2=311569&view=diff
==
--- cfe/trunk/include/clang/Analysis/CloneDetection.h (original)
+++ cfe/trunk/include/clang/Analysis/CloneDetection.h Wed Aug 23 09:28:26 2017
@@ -15,11 +15,7 @@
 #ifndef LLVM_CLANG_AST_CLONEDETECTION_H
 #define LLVM_CLANG_AST_CLONEDETECTION_H
 
-#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/StmtVisitor.h"
-#include "clang/Basic/SourceLocation.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Regex.h"
 #include 
 
@@ -31,192 +27,6 @@ class VarDecl;
 class ASTContext;
 class CompoundStmt;
 
-namespace clone_detection {
-
-/// Returns a string that represents all macro expansions that expanded into 
the
-/// give

[PATCH] D36664: [analyzer] Make StmtDataCollector customizable

2017-08-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311569: [analyzer] Make StmtDataCollector customizable 
(authored by krobelus).

Changed prior to commit:
  https://reviews.llvm.org/D36664?vs=111317&id=112388#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D36664

Files:
  cfe/trunk/include/clang/AST/DataCollection.h
  cfe/trunk/include/clang/Analysis/CloneDetection.h
  cfe/trunk/lib/AST/CMakeLists.txt
  cfe/trunk/lib/AST/DataCollection.cpp
  cfe/trunk/lib/AST/StmtDataCollectors.inc
  cfe/trunk/lib/Analysis/CloneDetection.cpp
  cfe/trunk/unittests/AST/CMakeLists.txt
  cfe/trunk/unittests/AST/DataCollectionTest.cpp

Index: cfe/trunk/lib/AST/StmtDataCollectors.inc
===
--- cfe/trunk/lib/AST/StmtDataCollectors.inc
+++ cfe/trunk/lib/AST/StmtDataCollectors.inc
@@ -0,0 +1,141 @@
+// The functions below collect the class specific data of each Stmt subclass.
+
+DEF_ADD_DATA(Stmt, {
+  addData(S->getStmtClass());
+  // This ensures that non-macro-generated code isn't identical to
+  // macro-generated code.
+  addData(data_collection::getMacroStack(S->getLocStart(), Context));
+  addData(data_collection::getMacroStack(S->getLocEnd(), Context));
+})
+DEF_ADD_DATA(Expr, { addData(S->getType()); })
+
+//--- Builtin functionality --//
+DEF_ADD_DATA(ArrayTypeTraitExpr, { addData(S->getTrait()); })
+DEF_ADD_DATA(ExpressionTraitExpr, { addData(S->getTrait()); })
+DEF_ADD_DATA(PredefinedExpr, { addData(S->getIdentType()); })
+DEF_ADD_DATA(TypeTraitExpr, {
+  addData(S->getTrait());
+  for (unsigned i = 0; i < S->getNumArgs(); ++i)
+addData(S->getArg(i)->getType());
+})
+
+//--- Calls --//
+DEF_ADD_DATA(CallExpr, {
+  // Function pointers don't have a callee and we just skip hashing it.
+  if (const FunctionDecl *D = S->getDirectCallee()) {
+// If the function is a template specialization, we also need to handle
+// the template arguments as they are not included in the qualified name.
+if (auto Args = D->getTemplateSpecializationArgs()) {
+  std::string ArgString;
+
+  // Print all template arguments into ArgString
+  llvm::raw_string_ostream OS(ArgString);
+  for (unsigned i = 0; i < Args->size(); ++i) {
+Args->get(i).print(Context.getLangOpts(), OS);
+// Add a padding character so that 'foo()' != 'foo()'.
+OS << '\n';
+  }
+  OS.flush();
+
+  addData(ArgString);
+}
+addData(D->getQualifiedNameAsString());
+  }
+})
+
+//--- Value references ---//
+DEF_ADD_DATA(DeclRefExpr,
+ { addData(S->getDecl()->getQualifiedNameAsString()); })
+DEF_ADD_DATA(MemberExpr,
+ { addData(S->getMemberDecl()->getName()); })
+
+//--- Literals ---//
+DEF_ADD_DATA(IntegerLiteral, { addData(llvm::hash_value(S->getValue())); })
+DEF_ADD_DATA(FloatingLiteral, { addData(llvm::hash_value(S->getValue())); })
+DEF_ADD_DATA(StringLiteral, { addData(S->getString()); })
+DEF_ADD_DATA(CXXBoolLiteralExpr, { addData(S->getValue()); })
+DEF_ADD_DATA(CharacterLiteral, { addData(S->getValue()); })
+
+//--- Exceptions -//
+DEF_ADD_DATA(CXXCatchStmt, { addData(S->getCaughtType()); })
+
+//--- C++ OOP Stmts --//
+DEF_ADD_DATA(CXXDeleteExpr, {
+  addData(S->isArrayFormAsWritten());
+  addData(S->isGlobalDelete());
+})
+
+//--- Casts --//
+DEF_ADD_DATA(ObjCBridgedCastExpr, { addData(S->getBridgeKind()); })
+
+//--- Miscellaneous Exprs //
+DEF_ADD_DATA(BinaryOperator, { addData(S->getOpcode()); })
+DEF_ADD_DATA(UnaryOperator, { addData(S->getOpcode()); })
+
+//--- Control flow ---//
+DEF_ADD_DATA(GotoStmt, { addData(S->getLabel()->getName()); })
+DEF_ADD_DATA(IndirectGotoStmt, {
+  if (S->getConstantTarget())
+addData(S->getConstantTarget()->getName());
+})
+DEF_ADD_DATA(LabelStmt, { addData(S->getDecl()->getName()); })
+DEF_ADD_DATA(MSDependentExistsStmt, { addData(S->isIfExists()); })
+DEF_ADD_DATA(AddrLabelExpr, { addData(S->getLabel()->getName()); })
+
+//--- Objective-C //
+DEF_ADD_DATA(ObjCIndirectCopyRestoreExpr, { addData(S->shouldCopy()); })
+DEF_ADD_DATA(ObjCPropertyRefExpr, {
+  addData(S->isSuperReceiver());
+  addData(S->isImplicitProperty());
+})
+DEF_ADD_DATA(ObjCAtCatchStmt, { addData(S->hasEllipsis()); })
+
+//--- Miscellaneous Stmts //
+DEF_ADD_DATA(CXXFoldExpr, {
+  addData(S->isRightFold());
+  addData(S->getOperator());
+})
+DEF_ADD_DATA(GenericSelectionExpr, {
+  for

r311570 - [clang-diff] HTML diff navigation

2017-08-23 Thread Johannes Altmanninger via cfe-commits
Author: krobelus
Date: Wed Aug 23 09:32:13 2017
New Revision: 311570

URL: http://llvm.org/viewvc/llvm-project?rev=311570&view=rev
Log:
[clang-diff] HTML diff navigation

Summary:
This adds shortcuts j and k to jump between changes.
It is especially useful in diffs with few changes.

Reviewers: arphaman

Subscribers: cfe-commits

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

Modified:
cfe/trunk/tools/clang-diff/ClangDiff.cpp

Modified: cfe/trunk/tools/clang-diff/ClangDiff.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-diff/ClangDiff.cpp?rev=311570&r1=311569&r2=311570&view=diff
==
--- cfe/trunk/tools/clang-diff/ClangDiff.cpp (original)
+++ cfe/trunk/tools/clang-diff/ClangDiff.cpp Wed Aug 23 09:32:13 2017
@@ -139,13 +139,14 @@ div.code {
 highlightStack = []
 function clearHighlight() {
   while (highlightStack.length) {
-let [l, r] = highlightStack.pop()
+var [l, r] = highlightStack.pop()
 document.getElementById(l).style.backgroundColor = 'white'
-document.getElementById(r).style.backgroundColor = 'white'
+if (r[1] != '-')
+  document.getElementById(r).style.backgroundColor = 'white'
   }
 }
 function highlight(event) {
-  id = event.target['id']
+  var id = event.target['id']
   doHighlight(id)
 }
 function doHighlight(id) {
@@ -153,20 +154,66 @@ function doHighlight(id) {
   source = document.getElementById(id)
   if (!source.attributes['tid'])
 return
-  tid = source.attributes['tid'].value
-  target = document.getElementById(tid)
-  if (!target || source.parentElement && 
source.parentElement.classList.contains('code'))
+  var mapped = source
+  while (mapped && mapped.parentElement && 
mapped.attributes['tid'].value.substr(1) === '-1')
+mapped = mapped.parentElement
+  var tid = null, target = null
+  if (mapped) {
+tid = mapped.attributes['tid'].value
+target = document.getElementById(tid)
+  }
+  if (source.parentElement && source.parentElement.classList.contains('code'))
 return
-  source.style.backgroundColor = target.style.backgroundColor = 'lightgrey'
-  highlightStack.push([id, tid])
+  source.style.backgroundColor = 'lightgrey'
   source.scrollIntoView()
-  target.scrollIntoView()
+  if (target) {
+if (mapped === source)
+  target.style.backgroundColor = 'lightgrey'
+target.scrollIntoView()
+  }
+  highlightStack.push([id, tid])
   location.hash = '#' + id
 }
 function scrollToBoth() {
   doHighlight(location.hash.substr(1))
 }
+function changed(elem) {
+  return elem.classList.length == 0
+}
+function nextChangedNode(prefix, increment, number) {
+  do {
+number += increment
+var elem = document.getElementById(prefix + number)
+  } while(elem && !changed(elem))
+  return elem ? number : null
+}
+function handleKey(e) {
+  var down = e.code === "KeyJ"
+  var up = e.code === "KeyK"
+  if (!down && !up)
+return
+  var id = highlightStack[0] ? highlightStack[0][0] : 'R0'
+  var oldelem = document.getElementById(id)
+  var number = parseInt(id.substr(1))
+  var increment = down ? 1 : -1
+  var lastnumber = number
+  var prefix = id[0]
+  do {
+number = nextChangedNode(prefix, increment, number)
+var elem = document.getElementById(prefix + number)
+if (up && elem) {
+  while (elem.parentElement && changed(elem.parentElement))
+elem = elem.parentElement
+  number = elem.id.substr(1)
+}
+  } while ((down && id !== 'R0' && oldelem.contains(elem)))
+  if (!number)
+number = lastnumber
+  elem = document.getElementById(prefix + number)
+  doHighlight(prefix + number)
+}
 window.onload = scrollToBoth
+window.onkeydown = handleKey
 
 
 


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


r311571 - [clang-diff] Reformat test, NFC

2017-08-23 Thread Johannes Altmanninger via cfe-commits
Author: krobelus
Date: Wed Aug 23 09:32:35 2017
New Revision: 311571

URL: http://llvm.org/viewvc/llvm-project?rev=311571&view=rev
Log:
[clang-diff] Reformat test, NFC

Modified:
cfe/trunk/test/Tooling/clang-diff-html.test

Modified: cfe/trunk/test/Tooling/clang-diff-html.test
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Tooling/clang-diff-html.test?rev=311571&r1=311570&r2=311571&view=diff
==
--- cfe/trunk/test/Tooling/clang-diff-html.test (original)
+++ cfe/trunk/test/Tooling/clang-diff-html.test Wed Aug 23 09:32:35 2017
@@ -1,36 +1,36 @@
-// RUN: clang-diff -html %S/Inputs/clang-diff-basic-src.cpp 
%S/clang-diff-basic.cpp -- | FileCheck %s
+RUN: clang-diff -html %S/Inputs/clang-diff-basic-src.cpp 
%S/clang-diff-basic.cpp -- | FileCheck %s
 
-// CHECK: 
+CHECK: 
 
-// match, update
-// CHECK: namespace src {
-
-// match, move
-// CHECK: void foo()
-
-// match
-// CHECK: void main()
-
-// deletion
-// CHECK: 4
-
-// update + move
-// CHECK: 2' class='u m'>2
-
-// insertion
-// CHECK: "Bar"
-
-// comments
-// CHECK: // CHECK: Insert IfStmt{{.*}} into IfStmt
-// CHECK: // CHECK: Delete AccessSpecDecl: public
+match, update
+CHECK: namespace src {
+
+match, move
+CHECK: void foo()
+
+match
+CHECK: void main()
+
+deletion
+CHECK: 4
+
+update + move
+CHECK: 2' class='u m'>2
+
+insertion
+CHECK: "Bar"
+
+comments
+CHECK: // CHECK: Insert IfStmt{{.*}} into IfStmt
+CHECK: // CHECK: Delete AccessSpecDecl: public


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


[PATCH] D36685: [clang-diff] HTML diff navigation

2017-08-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311570: [clang-diff] HTML diff navigation (authored by 
krobelus).

Repository:
  rL LLVM

https://reviews.llvm.org/D36685

Files:
  cfe/trunk/tools/clang-diff/ClangDiff.cpp


Index: cfe/trunk/tools/clang-diff/ClangDiff.cpp
===
--- cfe/trunk/tools/clang-diff/ClangDiff.cpp
+++ cfe/trunk/tools/clang-diff/ClangDiff.cpp
@@ -139,34 +139,81 @@
 highlightStack = []
 function clearHighlight() {
   while (highlightStack.length) {
-let [l, r] = highlightStack.pop()
+var [l, r] = highlightStack.pop()
 document.getElementById(l).style.backgroundColor = 'white'
-document.getElementById(r).style.backgroundColor = 'white'
+if (r[1] != '-')
+  document.getElementById(r).style.backgroundColor = 'white'
   }
 }
 function highlight(event) {
-  id = event.target['id']
+  var id = event.target['id']
   doHighlight(id)
 }
 function doHighlight(id) {
   clearHighlight()
   source = document.getElementById(id)
   if (!source.attributes['tid'])
 return
-  tid = source.attributes['tid'].value
-  target = document.getElementById(tid)
-  if (!target || source.parentElement && 
source.parentElement.classList.contains('code'))
+  var mapped = source
+  while (mapped && mapped.parentElement && 
mapped.attributes['tid'].value.substr(1) === '-1')
+mapped = mapped.parentElement
+  var tid = null, target = null
+  if (mapped) {
+tid = mapped.attributes['tid'].value
+target = document.getElementById(tid)
+  }
+  if (source.parentElement && source.parentElement.classList.contains('code'))
 return
-  source.style.backgroundColor = target.style.backgroundColor = 'lightgrey'
-  highlightStack.push([id, tid])
+  source.style.backgroundColor = 'lightgrey'
   source.scrollIntoView()
-  target.scrollIntoView()
+  if (target) {
+if (mapped === source)
+  target.style.backgroundColor = 'lightgrey'
+target.scrollIntoView()
+  }
+  highlightStack.push([id, tid])
   location.hash = '#' + id
 }
 function scrollToBoth() {
   doHighlight(location.hash.substr(1))
 }
+function changed(elem) {
+  return elem.classList.length == 0
+}
+function nextChangedNode(prefix, increment, number) {
+  do {
+number += increment
+var elem = document.getElementById(prefix + number)
+  } while(elem && !changed(elem))
+  return elem ? number : null
+}
+function handleKey(e) {
+  var down = e.code === "KeyJ"
+  var up = e.code === "KeyK"
+  if (!down && !up)
+return
+  var id = highlightStack[0] ? highlightStack[0][0] : 'R0'
+  var oldelem = document.getElementById(id)
+  var number = parseInt(id.substr(1))
+  var increment = down ? 1 : -1
+  var lastnumber = number
+  var prefix = id[0]
+  do {
+number = nextChangedNode(prefix, increment, number)
+var elem = document.getElementById(prefix + number)
+if (up && elem) {
+  while (elem.parentElement && changed(elem.parentElement))
+elem = elem.parentElement
+  number = elem.id.substr(1)
+}
+  } while ((down && id !== 'R0' && oldelem.contains(elem)))
+  if (!number)
+number = lastnumber
+  elem = document.getElementById(prefix + number)
+  doHighlight(prefix + number)
+}
 window.onload = scrollToBoth
+window.onkeydown = handleKey
 
 
 


Index: cfe/trunk/tools/clang-diff/ClangDiff.cpp
===
--- cfe/trunk/tools/clang-diff/ClangDiff.cpp
+++ cfe/trunk/tools/clang-diff/ClangDiff.cpp
@@ -139,34 +139,81 @@
 highlightStack = []
 function clearHighlight() {
   while (highlightStack.length) {
-let [l, r] = highlightStack.pop()
+var [l, r] = highlightStack.pop()
 document.getElementById(l).style.backgroundColor = 'white'
-document.getElementById(r).style.backgroundColor = 'white'
+if (r[1] != '-')
+  document.getElementById(r).style.backgroundColor = 'white'
   }
 }
 function highlight(event) {
-  id = event.target['id']
+  var id = event.target['id']
   doHighlight(id)
 }
 function doHighlight(id) {
   clearHighlight()
   source = document.getElementById(id)
   if (!source.attributes['tid'])
 return
-  tid = source.attributes['tid'].value
-  target = document.getElementById(tid)
-  if (!target || source.parentElement && source.parentElement.classList.contains('code'))
+  var mapped = source
+  while (mapped && mapped.parentElement && mapped.attributes['tid'].value.substr(1) === '-1')
+mapped = mapped.parentElement
+  var tid = null, target = null
+  if (mapped) {
+tid = mapped.attributes['tid'].value
+target = document.getElementById(tid)
+  }
+  if (source.parentElement && source.parentElement.classList.contains('code'))
 return
-  source.style.backgroundColor = target.style.backgroundColor = 'lightgrey'
-  highlightStack.push([id, tid])
+  source.style.backgroundColor = 'lightgrey'
   source.scrollIntoView()
-  target.scrollIntoView()
+  if (target) {
+if (mapped === source)

[PATCH] D37072: [clang-diff] Properly clear the selection in HTML diff

2017-08-23 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes created this revision.

https://reviews.llvm.org/D37072

Files:
  tools/clang-diff/ClangDiff.cpp


Index: tools/clang-diff/ClangDiff.cpp
===
--- tools/clang-diff/ClangDiff.cpp
+++ tools/clang-diff/ClangDiff.cpp
@@ -140,9 +140,9 @@
 function clearHighlight() {
   while (highlightStack.length) {
 var [l, r] = highlightStack.pop()
-document.getElementById(l).style.backgroundColor = 'white'
+document.getElementById(l).style.backgroundColor = 'inherit'
 if (r[1] != '-')
-  document.getElementById(r).style.backgroundColor = 'white'
+  document.getElementById(r).style.backgroundColor = 'inherit'
   }
 }
 function highlight(event) {


Index: tools/clang-diff/ClangDiff.cpp
===
--- tools/clang-diff/ClangDiff.cpp
+++ tools/clang-diff/ClangDiff.cpp
@@ -140,9 +140,9 @@
 function clearHighlight() {
   while (highlightStack.length) {
 var [l, r] = highlightStack.pop()
-document.getElementById(l).style.backgroundColor = 'white'
+document.getElementById(l).style.backgroundColor = 'inherit'
 if (r[1] != '-')
-  document.getElementById(r).style.backgroundColor = 'white'
+  document.getElementById(r).style.backgroundColor = 'inherit'
   }
 }
 function highlight(event) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D36969: [Basic] Add a DiagnosticError llvm::ErrorInfo subclass

2017-08-23 Thread Vedant Kumar via Phabricator via cfe-commits
vsk accepted this revision.
vsk added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rL LLVM

https://reviews.llvm.org/D36969



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


[PATCH] D37072: [clang-diff] Properly clear the selection in HTML diff

2017-08-23 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


https://reviews.llvm.org/D37072



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


Re: r311532 - [clang-format] Align trailing comments if ColumnLimit is 0

2017-08-23 Thread Hans Wennborg via cfe-commits
Merged to 5.0 in r311573.

On Wed, Aug 23, 2017 at 12:18 AM, Krasimir Georgiev via cfe-commits
 wrote:
> Author: krasimir
> Date: Wed Aug 23 00:18:36 2017
> New Revision: 311532
>
> URL: http://llvm.org/viewvc/llvm-project?rev=311532&view=rev
> Log:
> [clang-format] Align trailing comments if ColumnLimit is 0
>
> Summary:
> ColumnLimit = 0 means no limit, so comment should always be aligned if 
> requested. This was broken with
>
>   https://llvm.org/svn/llvm-project/cfe/trunk@304687
>
> introduced via
>
>   https://reviews.llvm.org/D33830
>
> and is included in 5.0.0-rc2. This commit fixes it and adds a unittest for 
> this property.
>
> Should go into clang-5.0 IMHO.
>
> Contributed by @pboettch!
>
> Reviewers: djasper, krasimir
>
> Reviewed By: djasper, krasimir
>
> Subscribers: hans, klimek
>
> Differential Revision: https://reviews.llvm.org/D36967
>
> Modified:
> cfe/trunk/lib/Format/WhitespaceManager.cpp
> cfe/trunk/unittests/Format/FormatTestComments.cpp
>
> Modified: cfe/trunk/lib/Format/WhitespaceManager.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/WhitespaceManager.cpp?rev=311532&r1=311531&r2=311532&view=diff
> ==
> --- cfe/trunk/lib/Format/WhitespaceManager.cpp (original)
> +++ cfe/trunk/lib/Format/WhitespaceManager.cpp Wed Aug 23 00:18:36 2017
> @@ -472,9 +472,14 @@ void WhitespaceManager::alignTrailingCom
>continue;
>
>  unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
> -unsigned ChangeMaxColumn = Style.ColumnLimit >= Changes[i].TokenLength
> -   ? Style.ColumnLimit - 
> Changes[i].TokenLength
> -   : ChangeMinColumn;
> +unsigned ChangeMaxColumn;
> +
> +if (Style.ColumnLimit == 0)
> +  ChangeMaxColumn = UINT_MAX;
> +else if (Style.ColumnLimit >= Changes[i].TokenLength)
> +  ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
> +else
> +  ChangeMaxColumn = ChangeMinColumn;
>
>  // If we don't create a replacement for this change, we have to consider
>  // it to be immovable.
>
> Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=311532&r1=311531&r2=311532&view=diff
> ==
> --- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
> +++ cfe/trunk/unittests/Format/FormatTestComments.cpp Wed Aug 23 00:18:36 2017
> @@ -2476,6 +2476,13 @@ TEST_F(FormatTestComments, AlignTrailing
> "int k; // line longg long",
> getLLVMStyleWithColumns(20)));
>
> +  // Always align if ColumnLimit = 0
> +  EXPECT_EQ("int i, j; // line 1\n"
> +"int k;// line longg long",
> +format("int i, j; // line 1\n"
> +   "int k; // line longg long",
> +   getLLVMStyleWithColumns(0)));
> +
>// Align comment line sections aligned with the next token with the next
>// token.
>EXPECT_EQ("class A {\n"
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] r311574 - ARM: explicitly specify the 8-byte alignment

2017-08-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Wed Aug 23 09:50:27 2017
New Revision: 311574

URL: http://llvm.org/viewvc/llvm-project?rev=311574&view=rev
Log:
ARM: explicitly specify the 8-byte alignment

It seems that GCC interprets `__attribute__((__aligned__))` as 8-byte
alignment on ARM, but clang does not.  Explicitly specify the
double-word alignment value to ensure that the structure is properly
aligned.

Modified:
libunwind/trunk/include/unwind.h
libunwind/trunk/test/alignment.pass.cpp

Modified: libunwind/trunk/include/unwind.h
URL: 
http://llvm.org/viewvc/llvm-project/libunwind/trunk/include/unwind.h?rev=311574&r1=311573&r2=311574&view=diff
==
--- libunwind/trunk/include/unwind.h (original)
+++ libunwind/trunk/include/unwind.h Wed Aug 23 09:50:27 2017
@@ -100,7 +100,7 @@ struct _Unwind_Control_Block {
   } pr_cache;
 
   long long int :0; /* Enforce the 8-byte alignment */
-} __attribute__((__aligned__));
+} __attribute__((__aligned__(8)));
 
 typedef _Unwind_Reason_Code (*_Unwind_Stop_Fn)
   (_Unwind_State state,

Modified: libunwind/trunk/test/alignment.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libunwind/trunk/test/alignment.pass.cpp?rev=311574&r1=311573&r2=311574&view=diff
==
--- libunwind/trunk/test/alignment.pass.cpp (original)
+++ libunwind/trunk/test/alignment.pass.cpp Wed Aug 23 09:50:27 2017
@@ -13,8 +13,16 @@
 
 #include 
 
-struct MaxAligned {} __attribute__((aligned));
-static_assert(alignof(_Unwind_Exception) == alignof(MaxAligned), "");
+// EHABI  : 8-byte aligned
+// itanium: largest supported alignment for the system
+#if defined(_LIBUNWIND_ARM_EHABI)
+static_assert(alignof(_Unwind_Control_Block) == 8,
+  "_Unwind_Control_Block must be double-word aligned");
+#else
+struct MaxAligned {} __attribute__((__aligned__));
+static_assert(alignof(_Unwind_Exception) == alignof(MaxAligned),
+  "_Unwind_Exception must be maximally aligned");
+#endif
 
 int main()
 {


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


r311575 - [clang-diff] Properly clear the selection in HTML diff

2017-08-23 Thread Johannes Altmanninger via cfe-commits
Author: krobelus
Date: Wed Aug 23 09:52:15 2017
New Revision: 311575

URL: http://llvm.org/viewvc/llvm-project?rev=311575&view=rev
Log:
[clang-diff] Properly clear the selection in HTML diff

Reviewers: arphaman

Subscribers: cfe-commits

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

Modified:
cfe/trunk/tools/clang-diff/ClangDiff.cpp

Modified: cfe/trunk/tools/clang-diff/ClangDiff.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-diff/ClangDiff.cpp?rev=311575&r1=311574&r2=311575&view=diff
==
--- cfe/trunk/tools/clang-diff/ClangDiff.cpp (original)
+++ cfe/trunk/tools/clang-diff/ClangDiff.cpp Wed Aug 23 09:52:15 2017
@@ -140,9 +140,9 @@ highlightStack = []
 function clearHighlight() {
   while (highlightStack.length) {
 var [l, r] = highlightStack.pop()
-document.getElementById(l).style.backgroundColor = 'white'
+document.getElementById(l).style.backgroundColor = 'inherit'
 if (r[1] != '-')
-  document.getElementById(r).style.backgroundColor = 'white'
+  document.getElementById(r).style.backgroundColor = 'inherit'
   }
 }
 function highlight(event) {


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


[PATCH] D37072: [clang-diff] Properly clear the selection in HTML diff

2017-08-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311575: [clang-diff] Properly clear the selection in HTML 
diff (authored by krobelus).

Repository:
  rL LLVM

https://reviews.llvm.org/D37072

Files:
  cfe/trunk/tools/clang-diff/ClangDiff.cpp


Index: cfe/trunk/tools/clang-diff/ClangDiff.cpp
===
--- cfe/trunk/tools/clang-diff/ClangDiff.cpp
+++ cfe/trunk/tools/clang-diff/ClangDiff.cpp
@@ -140,9 +140,9 @@
 function clearHighlight() {
   while (highlightStack.length) {
 var [l, r] = highlightStack.pop()
-document.getElementById(l).style.backgroundColor = 'white'
+document.getElementById(l).style.backgroundColor = 'inherit'
 if (r[1] != '-')
-  document.getElementById(r).style.backgroundColor = 'white'
+  document.getElementById(r).style.backgroundColor = 'inherit'
   }
 }
 function highlight(event) {


Index: cfe/trunk/tools/clang-diff/ClangDiff.cpp
===
--- cfe/trunk/tools/clang-diff/ClangDiff.cpp
+++ cfe/trunk/tools/clang-diff/ClangDiff.cpp
@@ -140,9 +140,9 @@
 function clearHighlight() {
   while (highlightStack.length) {
 var [l, r] = highlightStack.pop()
-document.getElementById(l).style.backgroundColor = 'white'
+document.getElementById(l).style.backgroundColor = 'inherit'
 if (r[1] != '-')
-  document.getElementById(r).style.backgroundColor = 'white'
+  document.getElementById(r).style.backgroundColor = 'inherit'
   }
 }
 function highlight(event) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r311576 - Headers: explicitly specify double-word alignment

2017-08-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Wed Aug 23 09:57:55 2017
New Revision: 311576

URL: http://llvm.org/viewvc/llvm-project?rev=311576&view=rev
Log:
Headers: explicitly specify double-word alignment

GCC will interpret `__attribute__((__aligned__))` as 8-byte alignment on
ARM, but clang will not.  Explicitly specify the alignment.  This
mirrors the declaration in libunwind.

Modified:
cfe/trunk/lib/Headers/unwind.h

Modified: cfe/trunk/lib/Headers/unwind.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/unwind.h?rev=311576&r1=311575&r2=311576&view=diff
==
--- cfe/trunk/lib/Headers/unwind.h (original)
+++ cfe/trunk/lib/Headers/unwind.h Wed Aug 23 09:57:55 2017
@@ -149,7 +149,7 @@ struct _Unwind_Control_Block {
 uint32_t reserved1;
   } pr_cache;
   long long int : 0; /* force alignment of next item to 8-byte boundary */
-} __attribute__((__aligned__));
+} __attribute__((__aligned__(8)));
 #else
 struct _Unwind_Exception {
   _Unwind_Exception_Class exception_class;


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


[PATCH] D36876: [IRGen] Evaluate constant static variables referenced through member expressions

2017-08-23 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Looks great, thanks.


Repository:
  rL LLVM

https://reviews.llvm.org/D36876



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


[PATCH] D36492: [time-report] Add preprocessor timer

2017-08-23 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added inline comments.



Comment at: lib/Lex/Preprocessor.cpp:746
 void Preprocessor::Lex(Token &Result) {
+  llvm::TimeRegion(PPOpts->getTimer());
+

MatzeB wrote:
> modocache wrote:
> > erik.pilkington wrote:
> > > Doesn't this just start a timer and immediately end the timer? Shouldn't 
> > > we do: `llvm::TimeRegion LexTime(PPOpts->getTimer())` so that the dtor 
> > > gets called when this function returns and we track the time spent in 
> > > this function?
> > > 
> > > Also: this is a pretty hot function, and it looks like TimeRegion does 
> > > some non-trivial work if time is being tracked. Have you tried testing 
> > > this on a big c++ file with and without this patch and seeing what the 
> > > difference in compile time looks like?
> > Ah, yes you're right! Sorry about that. Actually keeping the timer alive 
> > for the duration of the method also reveals that the method is called 
> > recursively, which causes an assert, because timers can't be started twice.
> > 
> > Another spot in Clang works around this with a "reference counted" timer: 
> > https://github.com/llvm-mirror/clang/blob/6ac9c51ede0a50cca13dd4ac03562c036f7a3f48/lib/CodeGen/CodeGenAction.cpp#L130-L134.
> >  I have a more generic version of this "reference counting timer" that I've 
> > been using for some of the other timers I've been adding; maybe I'll use it 
> > here as well.
> FWIF: I share Eriks concerns about compiletime. Timers are enabled in 
> optimized builds, and querying them is not free. So putting one into a 
> function that is called a lot and is time critical seems like a bad idea (do 
> benchmarking to prove or disprove this!).
The  timer is not started or queried unless -ftime-report is enabled. In the 
common case the overhead amounts to one extra null-check. And when we're 
collecting timing information, some performance degradation (say, within 5%) 
should be acceptable. I agree that we should get a sense for what the overhead 
is, but am not convinced that this should be a blocking issue.


https://reviews.llvm.org/D36492



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


[PATCH] D35271: Fix printing policy for AST context loaded from file

2017-08-23 Thread Vedant Kumar via Phabricator via cfe-commits
vsk accepted this revision.
vsk added a comment.
This revision is now accepted and ready to land.

Thanks, LGTM! This seems like a pretty straightforward bug fix. Since it's not 
my usual area maybe it'd be worth waiting a day or so for more feedback.


https://reviews.llvm.org/D35271



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


Re: r311330 - Fixed a crash on replaying Preamble's PP conditional stack.

2017-08-23 Thread Hans Wennborg via cfe-commits
Richard: ping?

On Mon, Aug 21, 2017 at 1:00 PM, Hans Wennborg  wrote:
> Nikolai suggested this should be merged to 5.0. Richard, what do you think?
>
> On Mon, Aug 21, 2017 at 5:03 AM, Ilya Biryukov via cfe-commits
>  wrote:
>> Author: ibiryukov
>> Date: Mon Aug 21 05:03:08 2017
>> New Revision: 311330
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=311330&view=rev
>> Log:
>> Fixed a crash on replaying Preamble's PP conditional stack.
>>
>> Summary:
>> The crash occurs when the first token after a preamble is a macro
>> expansion.
>> Fixed by moving replayPreambleConditionalStack from Parser into
>> Preprocessor. It is now called right after the predefines file is
>> processed.
>>
>> Reviewers: erikjv, bkramer, klimek, yvvan
>>
>> Reviewed By: bkramer
>>
>> Subscribers: cfe-commits
>>
>> Differential Revision: https://reviews.llvm.org/D36872
>>
>> Added:
>> cfe/trunk/test/Index/preamble-conditionals-crash.cpp
>> cfe/trunk/test/Index/preamble-conditionals.cpp
>> Modified:
>> cfe/trunk/include/clang/Lex/Preprocessor.h
>> cfe/trunk/lib/Lex/PPLexerChange.cpp
>> cfe/trunk/lib/Lex/Preprocessor.cpp
>> cfe/trunk/lib/Parse/Parser.cpp
>>
>> Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Preprocessor.h?rev=311330&r1=311329&r2=311330&view=diff
>> ==
>> --- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
>> +++ cfe/trunk/include/clang/Lex/Preprocessor.h Mon Aug 21 05:03:08 2017
>> @@ -1049,10 +1049,6 @@ public:
>>/// which implicitly adds the builtin defines etc.
>>void EnterMainSourceFile();
>>
>> -  /// \brief After parser warm-up, initialize the conditional stack from
>> -  /// the preamble.
>> -  void replayPreambleConditionalStack();
>> -
>>/// \brief Inform the preprocessor callbacks that processing is complete.
>>void EndSourceFile();
>>
>> @@ -2026,6 +2022,10 @@ public:
>>}
>>
>>  private:
>> +  /// \brief After processing predefined file, initialize the conditional 
>> stack from
>> +  /// the preamble.
>> +  void replayPreambleConditionalStack();
>> +
>>// Macro handling.
>>void HandleDefineDirective(Token &Tok, bool 
>> ImmediatelyAfterTopLevelIfndef);
>>void HandleUndefDirective();
>>
>> Modified: cfe/trunk/lib/Lex/PPLexerChange.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPLexerChange.cpp?rev=311330&r1=311329&r2=311330&view=diff
>> ==
>> --- cfe/trunk/lib/Lex/PPLexerChange.cpp (original)
>> +++ cfe/trunk/lib/Lex/PPLexerChange.cpp Mon Aug 21 05:03:08 2017
>> @@ -458,10 +458,16 @@ bool Preprocessor::HandleEndOfFile(Token
>>SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), 
>> NumFIDs);
>>  }
>>
>> +bool ExitedFromPredefinesFile = false;
>>  FileID ExitedFID;
>> -if (Callbacks && !isEndOfMacro && CurPPLexer)
>> +if (!isEndOfMacro && CurPPLexer) {
>>ExitedFID = CurPPLexer->getFileID();
>>
>> +  assert(PredefinesFileID.isValid() &&
>> + "HandleEndOfFile is called before PredefinesFileId is set");
>> +  ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
>> +}
>> +
>>  if (LeavingSubmodule) {
>>// We're done with this submodule.
>>Module *M = LeaveSubmodule(/*ForPragma*/false);
>> @@ -489,6 +495,11 @@ bool Preprocessor::HandleEndOfFile(Token
>>   PPCallbacks::ExitFile, FileType, ExitedFID);
>>  }
>>
>> +// Restore conditional stack from the preamble right after exiting from 
>> the
>> +// predefines file.
>> +if (ExitedFromPredefinesFile)
>> +  replayPreambleConditionalStack();
>> +
>>  // Client should lex another token unless we generated an EOM.
>>  return LeavingSubmodule;
>>}
>>
>> Modified: cfe/trunk/lib/Lex/Preprocessor.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/Preprocessor.cpp?rev=311330&r1=311329&r2=311330&view=diff
>> ==
>> --- cfe/trunk/lib/Lex/Preprocessor.cpp (original)
>> +++ cfe/trunk/lib/Lex/Preprocessor.cpp Mon Aug 21 05:03:08 2017
>> @@ -540,6 +540,8 @@ void Preprocessor::EnterMainSourceFile()
>>  void Preprocessor::replayPreambleConditionalStack() {
>>// Restore the conditional stack from the preamble, if there is one.
>>if (PreambleConditionalStack.isReplaying()) {
>> +assert(CurPPLexer &&
>> +   "CurPPLexer is null when calling 
>> replayPreambleConditionalStack.");
>>  CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
>>  PreambleConditionalStack.doneReplaying();
>>}
>>
>> Modified: cfe/trunk/lib/Parse/Parser.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/Parser.cpp?rev=311330&r1=311329&r2=311330&view=diff
>> ==

[PATCH] D34984: Store token literal data in PCH. Avoids disk read on PreProc expansion.

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

Seems reasonable to store this with the token. Do you have performance data?




Comment at: include/clang/Serialization/ASTReader.h:616
+  /// \brief Token literal data loaded and owned by us.
+  std::vector TokenLiteralDataLoaded;
+

Remove this use pointers directly into blob data from the token record (or 
BumpPtrAllocate the strings using the preprocessor's allocator if there's some 
reason you can't use blob data).



Comment at: lib/Serialization/ASTWriter.cpp:4360
 
   // FIXME: When reading literal tokens, reconstruct the literal pointer
   // if it is needed.

Remove this FIXME


https://reviews.llvm.org/D34984



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


[PATCH] D37004: [clang-diff] Fix the html output for CXXOperatorCallExpr

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

provide a test
need to update the maxsize parameter to -s=200 here because the test file is
expected to fit within this size


https://reviews.llvm.org/D37004

Files:
  test/Tooling/Inputs/clang-diff-basic-src.cpp
  test/Tooling/clang-diff-basic.cpp
  test/Tooling/clang-diff-html.test
  tools/clang-diff/CMakeLists.txt
  tools/clang-diff/ClangDiff.cpp

Index: tools/clang-diff/ClangDiff.cpp
===
--- tools/clang-diff/ClangDiff.cpp
+++ tools/clang-diff/ClangDiff.cpp
@@ -12,6 +12,7 @@
 //
 //===--===//
 
+#include "clang/AST/ExprCXX.h"
 #include "clang/Tooling/ASTDiff/ASTDiff.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
@@ -310,8 +311,17 @@
 OS << " class='" << getChangeKindAbbr(Node.Change) << "'";
   OS << ">";
 
-  for (diff::NodeId Child : Node.Children)
-Offset = printHtmlForNode(OS, Diff, Tree, IsLeft, Child, Offset);
+  const auto &Children = Node.Children;
+  auto *OpCall = Node.ASTNode.get();
+  if (OpCall && OpCall->isInfixBinaryOp()) {
+assert(Children.size() == 3 &&
+   "A Binary operator is supposed to have two arguments.");
+for (int I : {1, 0, 2})
+  Offset = printHtmlForNode(OS, Diff, Tree, IsLeft, Children[I], Offset);
+  } else {
+for (diff::NodeId Child : Children)
+  Offset = printHtmlForNode(OS, Diff, Tree, IsLeft, Child, Offset);
+  }
 
   for (; Offset < End; ++Offset)
 printHtml(OS, Code[Offset]);
Index: tools/clang-diff/CMakeLists.txt
===
--- tools/clang-diff/CMakeLists.txt
+++ tools/clang-diff/CMakeLists.txt
@@ -7,6 +7,7 @@
   )
 
 target_link_libraries(clang-diff
+  clangAST
   clangBasic
   clangFrontend
   clangTooling
Index: test/Tooling/clang-diff-html.test
===
--- test/Tooling/clang-diff-html.test
+++ test/Tooling/clang-diff-html.test
@@ -1,4 +1,4 @@
-RUN: clang-diff -html %S/Inputs/clang-diff-basic-src.cpp %S/clang-diff-basic.cpp -- -std=c++11 | FileCheck %s
+RUN: clang-diff -html %S/Inputs/clang-diff-basic-src.cpp %S/clang-diff-basic.cpp -s=200 -- -std=c++11 | FileCheck %s
 
 CHECK: 
@@ -31,6 +31,13 @@
 CHECK-NEXT: -1 -> [[R]]
 CHECK-NEXT: Bar' class='i'>"Bar"
 
+CHECK: CXXOperatorCallExpr
+CHECK: CXXOperatorCallExpr
+CHECK: s1
+CHECK: str::operator+
+CHECK: s2
+CHECK: str::operator-
+CHECK: s3
+
 comments
-CHECK: // CHECK: Insert IfStmt{{.*}} into IfStmt
 CHECK: // CHECK: Delete AccessSpecDecl: public
Index: test/Tooling/clang-diff-basic.cpp
===
--- test/Tooling/clang-diff-basic.cpp
+++ test/Tooling/clang-diff-basic.cpp
@@ -1,4 +1,4 @@
-// RUN: clang-diff -dump-matches %S/Inputs/clang-diff-basic-src.cpp %s -- -std=c++11 | FileCheck %s
+// RUN: clang-diff -dump-matches %S/Inputs/clang-diff-basic-src.cpp %s -s=200 -- -std=c++11 | FileCheck %s
 
 // CHECK: Match TranslationUnitDecl{{.*}} to TranslationUnitDecl
 // CHECK: Match NamespaceDecl: src{{.*}} to NamespaceDecl: dst
@@ -81,5 +81,21 @@
   visit(x);
 }
 
+struct str {
+  str& operator+(const str&);
+  str& operator-(const str&);
+  str& operator++();
+  str operator++(int);
+} s1, s2, s3;
+
+// CHECK: Match CXXOperatorCallExpr
+// CHECK-NEXT: Match DeclRefExpr: str::operator-{{.*}} to DeclRefExpr: str::operator-
+// CHECK-NEXT: Match CXXOperatorCallExpr
+// CHECK-NEXT: Match DeclRefExpr: str::operator+{{.*}} to DeclRefExpr: str::operator+
+// CHECK-NEXT: Match DeclRefExpr: s1
+// CHECK-NEXT: Match DeclRefExpr: s2
+// CHECK-NEXT: Match DeclRefExpr: s3
+str x = s1 + s2 - s3;
+
 // CHECK: Delete AccessSpecDecl: public
 // CHECK: Delete CXXMethodDecl
Index: test/Tooling/Inputs/clang-diff-basic-src.cpp
===
--- test/Tooling/Inputs/clang-diff-basic-src.cpp
+++ test/Tooling/Inputs/clang-diff-basic-src.cpp
@@ -53,4 +53,11 @@
   visit(x);
 }
 
-int x = 1;
+struct str {
+  str& operator+(const str&);
+  str& operator-(const str&);
+  str& operator++();
+  str operator++(int);
+} s1, s2, s3;
+
+str x = s1 + s2 - s3;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r311589 - [ubsan] PR34266: When sanitizing the 'this' value for a member function that happens to be a lambda call operator, use the lambda's 'this' pointer, not the captured enclosing 'this' pointer

2017-08-23 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Aug 23 12:39:04 2017
New Revision: 311589

URL: http://llvm.org/viewvc/llvm-project?rev=311589&view=rev
Log:
[ubsan] PR34266: When sanitizing the 'this' value for a member function that 
happens to be a lambda call operator, use the lambda's 'this' pointer, not the 
captured enclosing 'this' pointer (if any).

Modified:
cfe/trunk/include/clang/AST/DeclCXX.h
cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp

Modified: cfe/trunk/include/clang/AST/DeclCXX.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclCXX.h?rev=311589&r1=311588&r2=311589&view=diff
==
--- cfe/trunk/include/clang/AST/DeclCXX.h (original)
+++ cfe/trunk/include/clang/AST/DeclCXX.h Wed Aug 23 12:39:04 2017
@@ -2027,7 +2027,10 @@ public:
 
   /// \brief Returns the type of the \c this pointer.
   ///
-  /// Should only be called for instance (i.e., non-static) methods.
+  /// Should only be called for instance (i.e., non-static) methods. Note
+  /// that for the call operator of a lambda closure type, this returns the
+  /// desugared 'this' type (a pointer to the closure type), not the captured
+  /// 'this' type.
   QualType getThisType(ASTContext &C) const;
 
   unsigned getTypeQualifiers() const {

Modified: cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenFunction.cpp?rev=311589&r1=311588&r2=311589&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenFunction.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenFunction.cpp Wed Aug 23 12:39:04 2017
@@ -1014,11 +1014,11 @@ void CodeGenFunction::StartFunction(Glob
 }
 
 // Check the 'this' pointer once per function, if it's available.
-if (CXXThisValue) {
+if (CXXABIThisValue) {
   SanitizerSet SkippedChecks;
   SkippedChecks.set(SanitizerKind::ObjectSize, true);
   QualType ThisTy = MD->getThisType(getContext());
-  EmitTypeCheck(TCK_Load, Loc, CXXThisValue, ThisTy,
+  EmitTypeCheck(TCK_Load, Loc, CXXABIThisValue, ThisTy,
 getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
 SkippedChecks);
 }

Modified: cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp?rev=311589&r1=311588&r2=311589&view=diff
==
--- cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp Wed Aug 23 12:39:04 2017
@@ -449,6 +449,27 @@ void upcast_to_vbase() {
 }
 }
 
+struct ThisAlign {
+  void this_align_lambda();
+};
+void ThisAlign::this_align_lambda() {
+  // CHECK-LABEL: define 
{{.*}}@"_ZZN9ThisAlign17this_align_lambdaEvENK3$_0clEv"
+  // CHECK-SAME: (%{{.*}}* %[[this:[^)]*]])
+  // CHECK: %[[this_addr:.*]] = alloca
+  // CHECK: store %{{.*}}* %[[this]], %{{.*}}** %[[this_addr]],
+  // CHECK: %[[this_inner:.*]] = load %{{.*}}*, %{{.*}}** %[[this_addr]],
+  // CHECK: %[[this_outer_addr:.*]] = getelementptr inbounds %{{.*}}, %{{.*}}* 
%[[this_inner]], i32 0, i32 0
+  // CHECK: %[[this_outer:.*]] = load %{{.*}}*, %{{.*}}** %[[this_outer_addr]],
+  //
+  // CHECK: %[[this_inner_isnonnull:.*]] = icmp ne %{{.*}}* %[[this_inner]], 
null
+  // CHECK: %[[this_inner_asint:.*]] = ptrtoint %{{.*}}* %[[this_inner]] to i
+  // CHECK: %[[this_inner_misalignment:.*]] = and i{{32|64}} 
%[[this_inner_asint]], {{3|7}},
+  // CHECK: %[[this_inner_isaligned:.*]] = icmp eq i{{32|64}} 
%[[this_inner_misalignment]], 0
+  // CHECK: %[[this_inner_valid:.*]] = and i1 %[[this_inner_isnonnull]], 
%[[this_inner_isaligned]],
+  // CHECK: br i1 %[[this_inner_valid:.*]]
+  [&] { return this; } ();
+}
+
 namespace CopyValueRepresentation {
   // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S3aSERKS0_
   // CHECK-NOT: call {{.*}} @__ubsan_handle_load_invalid_value


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


Re: r311330 - Fixed a crash on replaying Preamble's PP conditional stack.

2017-08-23 Thread Richard Smith via cfe-commits
LG for branch.

On 23 August 2017 at 11:04, Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Richard: ping?
>
> On Mon, Aug 21, 2017 at 1:00 PM, Hans Wennborg  wrote:
> > Nikolai suggested this should be merged to 5.0. Richard, what do you
> think?
> >
> > On Mon, Aug 21, 2017 at 5:03 AM, Ilya Biryukov via cfe-commits
> >  wrote:
> >> Author: ibiryukov
> >> Date: Mon Aug 21 05:03:08 2017
> >> New Revision: 311330
> >>
> >> URL: http://llvm.org/viewvc/llvm-project?rev=311330&view=rev
> >> Log:
> >> Fixed a crash on replaying Preamble's PP conditional stack.
> >>
> >> Summary:
> >> The crash occurs when the first token after a preamble is a macro
> >> expansion.
> >> Fixed by moving replayPreambleConditionalStack from Parser into
> >> Preprocessor. It is now called right after the predefines file is
> >> processed.
> >>
> >> Reviewers: erikjv, bkramer, klimek, yvvan
> >>
> >> Reviewed By: bkramer
> >>
> >> Subscribers: cfe-commits
> >>
> >> Differential Revision: https://reviews.llvm.org/D36872
> >>
> >> Added:
> >> cfe/trunk/test/Index/preamble-conditionals-crash.cpp
> >> cfe/trunk/test/Index/preamble-conditionals.cpp
> >> Modified:
> >> cfe/trunk/include/clang/Lex/Preprocessor.h
> >> cfe/trunk/lib/Lex/PPLexerChange.cpp
> >> cfe/trunk/lib/Lex/Preprocessor.cpp
> >> cfe/trunk/lib/Parse/Parser.cpp
> >>
> >> Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
> >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/
> clang/Lex/Preprocessor.h?rev=311330&r1=311329&r2=311330&view=diff
> >> 
> ==
> >> --- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
> >> +++ cfe/trunk/include/clang/Lex/Preprocessor.h Mon Aug 21 05:03:08 2017
> >> @@ -1049,10 +1049,6 @@ public:
> >>/// which implicitly adds the builtin defines etc.
> >>void EnterMainSourceFile();
> >>
> >> -  /// \brief After parser warm-up, initialize the conditional stack
> from
> >> -  /// the preamble.
> >> -  void replayPreambleConditionalStack();
> >> -
> >>/// \brief Inform the preprocessor callbacks that processing is
> complete.
> >>void EndSourceFile();
> >>
> >> @@ -2026,6 +2022,10 @@ public:
> >>}
> >>
> >>  private:
> >> +  /// \brief After processing predefined file, initialize the
> conditional stack from
> >> +  /// the preamble.
> >> +  void replayPreambleConditionalStack();
> >> +
> >>// Macro handling.
> >>void HandleDefineDirective(Token &Tok, bool
> ImmediatelyAfterTopLevelIfndef);
> >>void HandleUndefDirective();
> >>
> >> Modified: cfe/trunk/lib/Lex/PPLexerChange.cpp
> >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/
> PPLexerChange.cpp?rev=311330&r1=311329&r2=311330&view=diff
> >> 
> ==
> >> --- cfe/trunk/lib/Lex/PPLexerChange.cpp (original)
> >> +++ cfe/trunk/lib/Lex/PPLexerChange.cpp Mon Aug 21 05:03:08 2017
> >> @@ -458,10 +458,16 @@ bool Preprocessor::HandleEndOfFile(Token
> >>SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(),
> NumFIDs);
> >>  }
> >>
> >> +bool ExitedFromPredefinesFile = false;
> >>  FileID ExitedFID;
> >> -if (Callbacks && !isEndOfMacro && CurPPLexer)
> >> +if (!isEndOfMacro && CurPPLexer) {
> >>ExitedFID = CurPPLexer->getFileID();
> >>
> >> +  assert(PredefinesFileID.isValid() &&
> >> + "HandleEndOfFile is called before PredefinesFileId is
> set");
> >> +  ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
> >> +}
> >> +
> >>  if (LeavingSubmodule) {
> >>// We're done with this submodule.
> >>Module *M = LeaveSubmodule(/*ForPragma*/false);
> >> @@ -489,6 +495,11 @@ bool Preprocessor::HandleEndOfFile(Token
> >>   PPCallbacks::ExitFile, FileType,
> ExitedFID);
> >>  }
> >>
> >> +// Restore conditional stack from the preamble right after exiting
> from the
> >> +// predefines file.
> >> +if (ExitedFromPredefinesFile)
> >> +  replayPreambleConditionalStack();
> >> +
> >>  // Client should lex another token unless we generated an EOM.
> >>  return LeavingSubmodule;
> >>}
> >>
> >> Modified: cfe/trunk/lib/Lex/Preprocessor.cpp
> >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/
> Preprocessor.cpp?rev=311330&r1=311329&r2=311330&view=diff
> >> 
> ==
> >> --- cfe/trunk/lib/Lex/Preprocessor.cpp (original)
> >> +++ cfe/trunk/lib/Lex/Preprocessor.cpp Mon Aug 21 05:03:08 2017
> >> @@ -540,6 +540,8 @@ void Preprocessor::EnterMainSourceFile()
> >>  void Preprocessor::replayPreambleConditionalStack() {
> >>// Restore the conditional stack from the preamble, if there is one.
> >>if (PreambleConditionalStack.isReplaying()) {
> >> +assert(CurPPLexer &&
> >> +   "CurPPLexer is null when calling
> replayPreambleCondition

[PATCH] D36712: Emit section information for extern variables

2017-08-23 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

> If there is no section given explicitly, there is function 
> SelectSectionForGlobal that will determine the section based on the 
> properties of the global. If there is code that only sees the declaration, 
> but needs to know the section, it will get it from that function.

SelectSectionForGlobal takes a SectionKind, and in general you can't compute 
the right SectionKind without knowing the initializer.  (See 
TargetLoweringObjectFile::getKindForGlobal.)


Repository:
  rL LLVM

https://reviews.llvm.org/D36712



___
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-23 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added a comment.

My intention here was to make this as strict/limited as possible while still 
handling the cases of interest.  There are two different implementations I want 
to handle.  You can see the first variation in the __BPTR_ALIGN definition 
being added here:

https://github.com/lattera/glibc/commit/2fd4de4b15a66f821057af90714145d2c034a609#diff-cd0c2b2693d632ad8843ae58a6ea7ffaR125

You can see the other in the __INT_TO_PTR definition that was being deleted in 
the same change set here:

https://github.com/lattera/glibc/commit/2fd4de4b15a66f821057af90714145d2c034a609#diff-cd0c2b2693d632ad8843ae58a6ea7ffaL122

This second case shows up in some benchmark code, so it's important even though 
glibc phased it out.

I'm really not sure what this looks like in the front end, but it seems like it 
could be relatively open-ended as to where the value came from.

Basically, my intention is to eliminate anything I know isn't what I'm looking 
for and then handle whatever remains being added to a null pointer.  Given that 
adding to a null pointer is undefined behavior, whatever we do should be 
acceptable in all cases.  What I found in practice was that even with the 
existing handling of this it took an awful lot of optimizations before the 
null-based GEP and the load associated with it got close enough together for us 
to recognize that we could optimize it away, so I don't think we'd be losing 
much by tolerating additional cases in the way this patch proposes.


https://reviews.llvm.org/D37042



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


Re: r311330 - Fixed a crash on replaying Preamble's PP conditional stack.

2017-08-23 Thread Hans Wennborg via cfe-commits
Thanks! r311591.

On Wed, Aug 23, 2017 at 12:42 PM, Richard Smith  wrote:
> LG for branch.
>
> On 23 August 2017 at 11:04, Hans Wennborg via cfe-commits
>  wrote:
>>
>> Richard: ping?
>>
>> On Mon, Aug 21, 2017 at 1:00 PM, Hans Wennborg  wrote:
>> > Nikolai suggested this should be merged to 5.0. Richard, what do you
>> > think?
>> >
>> > On Mon, Aug 21, 2017 at 5:03 AM, Ilya Biryukov via cfe-commits
>> >  wrote:
>> >> Author: ibiryukov
>> >> Date: Mon Aug 21 05:03:08 2017
>> >> New Revision: 311330
>> >>
>> >> URL: http://llvm.org/viewvc/llvm-project?rev=311330&view=rev
>> >> Log:
>> >> Fixed a crash on replaying Preamble's PP conditional stack.
>> >>
>> >> Summary:
>> >> The crash occurs when the first token after a preamble is a macro
>> >> expansion.
>> >> Fixed by moving replayPreambleConditionalStack from Parser into
>> >> Preprocessor. It is now called right after the predefines file is
>> >> processed.
>> >>
>> >> Reviewers: erikjv, bkramer, klimek, yvvan
>> >>
>> >> Reviewed By: bkramer
>> >>
>> >> Subscribers: cfe-commits
>> >>
>> >> Differential Revision: https://reviews.llvm.org/D36872
>> >>
>> >> Added:
>> >> cfe/trunk/test/Index/preamble-conditionals-crash.cpp
>> >> cfe/trunk/test/Index/preamble-conditionals.cpp
>> >> Modified:
>> >> cfe/trunk/include/clang/Lex/Preprocessor.h
>> >> cfe/trunk/lib/Lex/PPLexerChange.cpp
>> >> cfe/trunk/lib/Lex/Preprocessor.cpp
>> >> cfe/trunk/lib/Parse/Parser.cpp
>> >>
>> >> Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
>> >> URL:
>> >> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Preprocessor.h?rev=311330&r1=311329&r2=311330&view=diff
>> >>
>> >> ==
>> >> --- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
>> >> +++ cfe/trunk/include/clang/Lex/Preprocessor.h Mon Aug 21 05:03:08 2017
>> >> @@ -1049,10 +1049,6 @@ public:
>> >>/// which implicitly adds the builtin defines etc.
>> >>void EnterMainSourceFile();
>> >>
>> >> -  /// \brief After parser warm-up, initialize the conditional stack
>> >> from
>> >> -  /// the preamble.
>> >> -  void replayPreambleConditionalStack();
>> >> -
>> >>/// \brief Inform the preprocessor callbacks that processing is
>> >> complete.
>> >>void EndSourceFile();
>> >>
>> >> @@ -2026,6 +2022,10 @@ public:
>> >>}
>> >>
>> >>  private:
>> >> +  /// \brief After processing predefined file, initialize the
>> >> conditional stack from
>> >> +  /// the preamble.
>> >> +  void replayPreambleConditionalStack();
>> >> +
>> >>// Macro handling.
>> >>void HandleDefineDirective(Token &Tok, bool
>> >> ImmediatelyAfterTopLevelIfndef);
>> >>void HandleUndefDirective();
>> >>
>> >> Modified: cfe/trunk/lib/Lex/PPLexerChange.cpp
>> >> URL:
>> >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPLexerChange.cpp?rev=311330&r1=311329&r2=311330&view=diff
>> >>
>> >> ==
>> >> --- cfe/trunk/lib/Lex/PPLexerChange.cpp (original)
>> >> +++ cfe/trunk/lib/Lex/PPLexerChange.cpp Mon Aug 21 05:03:08 2017
>> >> @@ -458,10 +458,16 @@ bool Preprocessor::HandleEndOfFile(Token
>> >>SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(),
>> >> NumFIDs);
>> >>  }
>> >>
>> >> +bool ExitedFromPredefinesFile = false;
>> >>  FileID ExitedFID;
>> >> -if (Callbacks && !isEndOfMacro && CurPPLexer)
>> >> +if (!isEndOfMacro && CurPPLexer) {
>> >>ExitedFID = CurPPLexer->getFileID();
>> >>
>> >> +  assert(PredefinesFileID.isValid() &&
>> >> + "HandleEndOfFile is called before PredefinesFileId is
>> >> set");
>> >> +  ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
>> >> +}
>> >> +
>> >>  if (LeavingSubmodule) {
>> >>// We're done with this submodule.
>> >>Module *M = LeaveSubmodule(/*ForPragma*/false);
>> >> @@ -489,6 +495,11 @@ bool Preprocessor::HandleEndOfFile(Token
>> >>   PPCallbacks::ExitFile, FileType,
>> >> ExitedFID);
>> >>  }
>> >>
>> >> +// Restore conditional stack from the preamble right after exiting
>> >> from the
>> >> +// predefines file.
>> >> +if (ExitedFromPredefinesFile)
>> >> +  replayPreambleConditionalStack();
>> >> +
>> >>  // Client should lex another token unless we generated an EOM.
>> >>  return LeavingSubmodule;
>> >>}
>> >>
>> >> Modified: cfe/trunk/lib/Lex/Preprocessor.cpp
>> >> URL:
>> >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/Preprocessor.cpp?rev=311330&r1=311329&r2=311330&view=diff
>> >>
>> >> ==
>> >> --- cfe/trunk/lib/Lex/Preprocessor.cpp (original)
>> >> +++ cfe/trunk/lib/Lex/Preprocessor.cpp Mon Aug 21 05:03:08 2017
>> >> @@ -540,6 +540,8 @@ void Preprocessor::EnterMainSourceFile()
>> >>  void Preprocessor::replayPreambleConditionalStack() {
>> >>// Restore 

r311592 - [clang-proto-fuzzer] Fix clang-proto-to-cxx build.

2017-08-23 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Wed Aug 23 12:58:07 2017
New Revision: 311592

URL: http://llvm.org/viewvc/llvm-project?rev=311592&view=rev
Log:
[clang-proto-fuzzer] Fix clang-proto-to-cxx build.

Modified:
cfe/trunk/tools/clang-fuzzer/CMakeLists.txt
cfe/trunk/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt

Modified: cfe/trunk/tools/clang-fuzzer/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-fuzzer/CMakeLists.txt?rev=311592&r1=311591&r2=311592&view=diff
==
--- cfe/trunk/tools/clang-fuzzer/CMakeLists.txt (original)
+++ cfe/trunk/tools/clang-fuzzer/CMakeLists.txt Wed Aug 23 12:58:07 2017
@@ -1,5 +1,6 @@
 if( LLVM_USE_SANITIZE_COVERAGE )
   set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD})
+  set(CXX_FLAGS_NOFUZZ ${CMAKE_CXX_FLAGS})
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=fuzzer")
 
   if(CLANG_ENABLE_PROTO_FUZZER)

Modified: cfe/trunk/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt?rev=311592&r1=311591&r2=311592&view=diff
==
--- cfe/trunk/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt (original)
+++ cfe/trunk/tools/clang-fuzzer/proto-to-cxx/CMakeLists.txt Wed Aug 23 
12:58:07 2017
@@ -1,4 +1,5 @@
 set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD})
+set(CMAKE_CXX_FLAGS ${CXX_FLAGS_NOFUZZ})
 
 # Hack to bypass LLVM's CMake source checks so we can have both a library and
 # an executable built from this directory.


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


r311594 - Parse and print DIExpressions inline to ease IR and MIR testing

2017-08-23 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Aug 23 13:31:27 2017
New Revision: 311594

URL: http://llvm.org/viewvc/llvm-project?rev=311594&view=rev
Log:
Parse and print DIExpressions inline to ease IR and MIR testing

Summary:
Most DIExpressions are empty or very simple. When they are complex, they
tend to be unique, so checking them inline is reasonable.

This also avoids the need for CodeGen passes to append to the
llvm.dbg.mir named md node.

See also PR22780, for making DIExpression not be an MDNode.

Reviewers: aprantl, dexonsmith, dblaikie

Subscribers: qcolombet, javed.absar, eraman, hiraditya, llvm-commits

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

Modified:
cfe/trunk/test/CodeGen/2010-08-10-DbgConstant.c
cfe/trunk/test/CodeGen/debug-info-global-constant.c
cfe/trunk/test/CodeGen/debug-info-static-const-fp.c
cfe/trunk/test/CodeGen/debug-info-vla.c
cfe/trunk/test/CodeGenCXX/debug-info-inheriting-constructor.cpp
cfe/trunk/test/CodeGenCXX/debug-info.cpp
cfe/trunk/test/CodeGenOpenCL/amdgpu-debug-info-variable-expression.cl
cfe/trunk/test/OpenMP/nvptx_target_firstprivate_codegen.cpp

Modified: cfe/trunk/test/CodeGen/2010-08-10-DbgConstant.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/2010-08-10-DbgConstant.c?rev=311594&r1=311593&r2=311594&view=diff
==
--- cfe/trunk/test/CodeGen/2010-08-10-DbgConstant.c (original)
+++ cfe/trunk/test/CodeGen/2010-08-10-DbgConstant.c Wed Aug 23 13:31:27 2017
@@ -1,6 +1,5 @@
 // RUN: %clang_cc1 -S -emit-llvm -debug-info-kind=limited  %s -o - | FileCheck 
%s
-// CHECK: !DIGlobalVariableExpression(var: [[VAR:.*]], expr: [[EXPR:![0-9]+]])
-// CHECK: [[EXPR]] = !DIExpression(DW_OP_constu, 201, DW_OP_stack_value)
+// CHECK: !DIGlobalVariableExpression(var: [[VAR:.*]], expr: 
!DIExpression(DW_OP_constu, 201, DW_OP_stack_value))
 
 static const unsigned int ro = 201;
 void bar(int);

Modified: cfe/trunk/test/CodeGen/debug-info-global-constant.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/debug-info-global-constant.c?rev=311594&r1=311593&r2=311594&view=diff
==
--- cfe/trunk/test/CodeGen/debug-info-global-constant.c (original)
+++ cfe/trunk/test/CodeGen/debug-info-global-constant.c Wed Aug 23 13:31:27 2017
@@ -5,11 +5,10 @@
 // exactly once.
 
 // CHECK: @i = internal constant i32 1, align 4, !dbg ![[I:[0-9]+]]
-// CHECK: ![[I]] = !DIGlobalVariableExpression(var: ![[VAR:.*]], expr: 
![[EXPR:[0-9]+]])
+// CHECK: ![[I]] = !DIGlobalVariableExpression(var: ![[VAR:.*]], expr: 
!DIExpression(DW_OP_constu, 1, DW_OP_stack_value))
 // CHECK: ![[VAR]] = distinct !DIGlobalVariable(name: "i",
 // CHECK: !DICompileUnit({{.*}}globals: ![[GLOBALS:[0-9]+]])
 // CHECK: ![[GLOBALS]] = !{![[I]]}
-// CHECK: ![[EXPR]] = !DIExpression(DW_OP_constu, 1, DW_OP_stack_value)
 static const int i = 1;
 
 void g(const int *, int);

Modified: cfe/trunk/test/CodeGen/debug-info-static-const-fp.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/debug-info-static-const-fp.c?rev=311594&r1=311593&r2=311594&view=diff
==
--- cfe/trunk/test/CodeGen/debug-info-static-const-fp.c (original)
+++ cfe/trunk/test/CodeGen/debug-info-static-const-fp.c Wed Aug 23 13:31:27 2017
@@ -33,20 +33,17 @@ int main() {
   return hVal + fVal + dVal + ldVal;
 }
 
-// CHECK: !DIGlobalVariableExpression(var: [[HVAL:.*]], expr: [[HEXPR:.*]])
+// CHECK: !DIGlobalVariableExpression(var: [[HVAL:.*]], expr: 
!DIExpression(DW_OP_constu, 16502, DW_OP_stack_value))
 // CHECK: [[HVAL]] = distinct !DIGlobalVariable(name: "hVal",
 // CHECK-SAME:  isLocal: true, isDefinition: 
true
-// CHECK: [[HEXPR]] = !DIExpression(DW_OP_constu, 16502, DW_OP_stack_value)
 
-// CHECK: !DIGlobalVariableExpression(var: [[FVAL:.*]], expr: [[FEXPR:.*]])
+// CHECK: !DIGlobalVariableExpression(var: [[FVAL:.*]], expr: 
!DIExpression(DW_OP_constu, 3238681178, DW_OP_stack_value))
 // CHECK: [[FVAL]] = distinct !DIGlobalVariable(name: "fVal",
 // CHECK-SAME:  isLocal: true, isDefinition: 
true
-// CHECK: [[FEXPR]] = !DIExpression(DW_OP_constu, 3238681178, 
DW_OP_stack_value)
 
-// CHECK: !DIGlobalVariableExpression(var: [[DVAL:.*]], expr: [[DEXPR:.*]])
+// CHECK: !DIGlobalVariableExpression(var: [[DVAL:.*]], expr: 
!DIExpression(DW_OP_constu, 4658387303597904457, DW_OP_stack_value))
 // CHECK: [[DVAL]] = distinct !DIGlobalVariable(name: "dVal",
 // CHECK-SAME:  isLocal: true, isDefinition: 
true
-// CHECK: [[DEXPR]] = !DIExpression(DW_OP_constu, 4658387303597904457, 
DW_OP_stack_value)
 
 // CHECK-LDlg-DAG: [[LDVAL:.*]] = distinct !DIGlobalVariable(name: "ldVal", 
{{.*}}, isLocal: true, isDefinition: true)
 // CHECK-LDlg-DAG: !DIGlobalVariableExpression(var: [[LDVAL]])

Modified: cfe/

Re: [PATCH] D36914: Implement CFG construction for __try / __except / __leave.

2017-08-23 Thread Nico Weber via cfe-commits
On Wed, Aug 23, 2017 at 12:11 PM, Reid Kleckner via Phabricator via
cfe-commits  wrote:

> rnk added inline comments.
>
>
> 
> Comment at: test/Sema/warn-unreachable-ms.c:42
> +  }
> +}
> 
> rnk wrote:
> > rnk wrote:
> > > Can we add a test to exercise that this builds the right CFG?
> > > ```
> > > __try {
> > >   __try {
> > > f();
> > >   } __except(1) {
> > > __leave; // should exit outer try
> > >   }
> > >   __leave;
> > >   f(); // expected-warning{{never be executed}}
> > > } __except(1) {
> > > }
> > > ```
> > > Sure. Did you intentionally put two __leaves in there, or do you only
> want the one in the inner __except?
> >
> > I think both are required to trigger the warning in case f() doesn't
> throw, but I could be wrong.
> I woke up this morning and realized what you meant. Is there another way
> we can check that __leave in __except exits the outer __try?


How does this look?

$ svn diff test/Sema
Index: test/Sema/warn-unreachable-ms.c
===
--- test/Sema/warn-unreachable-ms.c (revision 311564)
+++ test/Sema/warn-unreachable-ms.c (working copy)
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -triple=i686-pc-win32 -fsyntax-only -verify
-fms-extensions -Wunreachable-code
+// RUN: %clang_cc1 %s -triple=i686-pc-win32 -fsyntax-only -verify
-fms-extensions -Wunreachable-code -x c++ -fcxx-exceptions -DWITH_THROW

 void f();

@@ -41,15 +42,16 @@
   }
 }

+#if defined(WITH_THROW)
 void g3() {
   __try {
 __try {
-  f();
+  throw 1;
 } __except (1) {
   __leave; // should exit outer try
 }
-__leave;
 f(); // expected-warning{{never be executed}}
   } __except (1) {
   }
 }
+#endif
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D36642: [Lexer] Report more precise skipped regions (PR34166)

2017-08-23 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I'd like to see someone more familiar with indexing comment on the effect 
there; otherwise LGTM.


https://reviews.llvm.org/D36642



___
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-23 Thread Hal Finkel via Phabricator via cfe-commits
hfinkel added a comment.

I'd really like to see this done in some way such that we can issue a warning 
along with generating well-defined code. The warning can specifically state 
that the code is using an extension, etc.


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] D36371: [Clang][x86][Inline Asm] support for GCC style inline asm - Y constraints

2017-08-23 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rL LLVM

https://reviews.llvm.org/D36371



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


[PATCH] D36794: Fixups to FE tests affected by D36793

2017-08-23 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

These all look good


Repository:
  rL LLVM

https://reviews.llvm.org/D36794



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


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

2017-08-23 Thread Erik Uhlmann via Phabricator via cfe-commits
euhlmann updated this revision to Diff 112432.
euhlmann marked 7 inline comments as done.
euhlmann added a comment.

- Swapped checks in ContinuationIndenter
- Renamed `PPMaybeIncludeGuard` to `IfNdefCondition` and added comment
- Added another bool member that tracks if include guard detection was rejected 
once. If the bool gets set, the loop checking previous lines doesn't run again.
- Set lower ColumnLimit in tests
- Fixed incorrect column for `\` in multi-line macros
- Resolved comment in FormatTestUtils


https://reviews.llvm.org/D35955

Files:
  docs/ClangFormatStyleOptions.rst
  include/clang/Format/Format.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/Format.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  lib/Format/UnwrappedLineParser.h
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestUtils.h

Index: unittests/Format/FormatTestUtils.h
===
--- unittests/Format/FormatTestUtils.h
+++ unittests/Format/FormatTestUtils.h
@@ -30,7 +30,8 @@
   if (JustReplacedNewline)
 MessedUp[i - 1] = '\n';
   InComment = true;
-} else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) {
+} else if (MessedUp[i] == '#' &&
+   (JustReplacedNewline || i == 0 || MessedUp[i - 1] == '\n')) {
   if (i != 0)
 MessedUp[i - 1] = '\n';
   InPreprocessorDirective = true;
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -2286,8 +2286,183 @@
getLLVMStyleWithColumns(11));
 }
 
-TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
-  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
+TEST_F(FormatTest, IndentPreprocessorDirectives) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IndentPPDirectives = FormatStyle::PPDIS_None;
+  Style.ColumnLimit = 40;
+  verifyFormat("#ifdef _WIN32\n"
+   "#define A 0\n"
+   "#ifdef VAR2\n"
+   "#define B 1\n"
+   "#include \n"
+   "#define MACRO  \\\n"
+   "  some_very_long_func_aa();\n"
+   "#endif\n"
+   "#else\n"
+   "#define A 1\n"
+   "#endif",
+   Style);
+
+  Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
+  verifyFormat("#ifdef _WIN32\n"
+   "#  define A 0\n"
+   "#  ifdef VAR2\n"
+   "#define B 1\n"
+   "#include \n"
+   "#define MACRO  \\\n"
+   "  some_very_long_func_aa();\n"
+   "#  endif\n"
+   "#else\n"
+   "#  define A 1\n"
+   "#endif",
+   Style);
+  verifyFormat("#if A\n"
+   "#  define MACRO\\\n"
+   "void a(int x) {\\\n"
+   "  b(); \\\n"
+   "  c(); \\\n"
+   "  d(); \\\n"
+   "  e(); \\\n"
+   "  f(); \\\n"
+   "}\n"
+   "#endif",
+   Style);
+  // Comments before include guard.
+  verifyFormat("// file comment\n"
+   "// file comment\n"
+   "#ifndef HEADER_H\n"
+   "#define HEADER_H\n"
+   "code();\n"
+   "#endif",
+   Style);
+  // Test with include guards.
+  // EXPECT_EQ is used because verifyFormat() calls messUp() which incorrectly
+  // merges lines.
+  verifyFormat("#ifndef HEADER_H\n"
+   "#define HEADER_H\n"
+   "code();\n"
+   "#endif",
+   Style);
+  // Include guards must have a #define with the same variable immediately
+  // after #ifndef.
+  verifyFormat("#ifndef NOT_GUARD\n"
+   "#  define FOO\n"
+   "code();\n"
+   "#endif",
+   Style);
+
+  // Include guards must cover the entire file.
+  verifyFormat("code();\n"
+   "code();\n"
+   "#ifndef NOT_GUARD\n"
+   "#  define NOT_GUARD\n"
+   "code();\n"
+   "#endif",
+   Style);
+  verifyFormat("#ifndef NOT_GUARD\n"
+   "#  define NOT_GUARD\n"
+   "code();\n"
+   "#endif\n"
+   "code();",
+   Style);
+  // Test with trailing blank lines.
+  verifyFormat("#ifndef HEADER_H\n"
+   "#define HEADER_H\n"
+   "code();\n"
+   "#endif\n",
+   Style);
+  // Include guards don't have #else.
+  verifyFormat("#ifndef NOT_GUARD\n"
+   "#  define NOT_GUARD\n"
+   

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

2017-08-23 Thread Erik Uhlmann via Phabricator via cfe-commits
euhlmann added inline comments.



Comment at: lib/Format/UnwrappedLineParser.cpp:737
+for (auto& Line : Lines) {
+  if (Line.InPPDirective && Line.Level > 0)
+--Line.Level;

krasimir wrote:
> Wouldn't this also indent lines continuing macro definitions, as in:
> ```
> #define A(x) int f(int x) { \
>   return x; \
> }
> ```
Multi-line macros look this under this patch

```
#if A
#  define MACRO\
void a(int x) {\
  b(); \
  c(); \
  d(); \
  e(); \
  f(); \
}
#endif
```

With previous clang-format, no preprocessor indentation:


```
#if A
#define MACRO  \
  void a(int x) {  \
b();   \
c();   \
d();   \
e();   \
f();   \
  }
#endif
```


https://reviews.llvm.org/D35955



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


Re: r309226 - Headers: improve ARM EHABI coverage of unwind.h

2017-08-23 Thread Hans Wennborg via cfe-commits
I've reverted this (along with r309327) from the 5.0 branch in r311597.

On Tue, Aug 22, 2017 at 11:10 AM, Hans Wennborg  wrote:
> Is there a bug filed? Since this was merged to 5.0.0, I'd like to know
> if we broke something and if that is something that needs to be fixed.
>
> On Tue, Aug 22, 2017 at 10:46 AM, Evgenii Stepanov
>  wrote:
>> As I understand, using compiler-rt as libgcc replacement on ARM is
>> currently broken because of this change, but I have not looked since
>> my last message.
>>
>> On Mon, Aug 21, 2017 at 4:56 PM, Hans Wennborg  wrote:
>>> Is there something we need for 5.0.0 here?
>>>
>>> On Sat, Aug 12, 2017 at 9:58 PM, Saleem Abdulrasool
>>>  wrote:
 Yeah, we should adjust that.  Technically, it is `_Unwind_Control_Block on
 ARM EHABI.  However, _Unwind_Exception is aliased to that, which is why we
 can use that in the personality routine.  We should adjust the sources for
 the personality routine.

 On Fri, Aug 11, 2017 at 1:12 PM, Evgenii Stepanov
  wrote:
>
> Hi,
>
> I've noticed that the code in
> compiler-rt/lib/builtins/gcc_personality_v0.c refers to
> _Unwind_Exception as "struct _Unwind_Exception". With this change, it
> is not a struct anymore on ARM. Should that code be fixed, or is it a
> problem in this change?
>
> compiler-rt/lib/builtins/gcc_personality_v0.c:153:23: error:
> declaration of 'struct _Unwind_Exception' will not be visible outside
> of this function [-Werror,-Wvisibility]
> continueUnwind(struct _Unwind_Exception *exceptionObject,
>
> On Thu, Jul 27, 2017 at 9:46 AM, Hans Wennborg via cfe-commits
>  wrote:
> > Merged to 5.0 in r309290.
> >
> > On Wed, Jul 26, 2017 at 3:55 PM, Saleem Abdulrasool via cfe-commits
> >  wrote:
> >> Author: compnerd
> >> Date: Wed Jul 26 15:55:23 2017
> >> New Revision: 309226
> >>
> >> URL: http://llvm.org/viewvc/llvm-project?rev=309226&view=rev
> >> Log:
> >> Headers: improve ARM EHABI coverage of unwind.h
> >>
> >> Ensure that we define the `_Unwind_Control_Block` structure used on ARM
> >> EHABI targets.  This is needed for building libc++abi with the unwind.h
> >> from the resource dir.  A minor fallout of this is that we needed to
> >> create a typedef for _Unwind_Exception to work across ARM EHABI and
> >> non-EHABI targets.  The structure definitions here are based originally
> >> on the documentation from ARM under the "Exception Handling ABI for the
> >> ARM® Architecture" Section 7.2.  They are then adjusted to more closely
> >> reflect the definition in libunwind from LLVM.  Those changes are
> >> compatible in layout but permit easier use in libc++abi and help
> >> maintain compatibility between libunwind and the compiler provided
> >> definition.
> >>
> >> Modified:
> >> cfe/trunk/lib/Headers/unwind.h
> >>
> >> Modified: cfe/trunk/lib/Headers/unwind.h
> >> URL:
> >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/unwind.h?rev=309226&r1=309225&r2=309226&view=diff
> >>
> >> ==
> >> --- cfe/trunk/lib/Headers/unwind.h (original)
> >> +++ cfe/trunk/lib/Headers/unwind.h Wed Jul 26 15:55:23 2017
> >> @@ -76,7 +76,13 @@ typedef intptr_t _sleb128_t;
> >>  typedef uintptr_t _uleb128_t;
> >>
> >>  struct _Unwind_Context;
> >> +#if defined(__arm__) && !(defined(__USING_SJLJ_EXCEPTIONS__) ||
> >> defined(__ARM_DWARF_EH___))
> >> +struct _Unwind_Control_Block;
> >> +typedef struct _Unwind_Control_Block _Unwind_Exception; /* Alias */
> >> +#else
> >>  struct _Unwind_Exception;
> >> +typedef struct _Unwind_Exception _Unwind_Exception;
> >> +#endif
> >>  typedef enum {
> >>_URC_NO_REASON = 0,
> >>  #if defined(__arm__) && !defined(__USING_SJLJ_EXCEPTIONS__) && \
> >> @@ -109,8 +115,42 @@ typedef enum {
> >>  } _Unwind_Action;
> >>
> >>  typedef void (*_Unwind_Exception_Cleanup_Fn)(_Unwind_Reason_Code,
> >> - struct _Unwind_Exception
> >> *);
> >> + _Unwind_Exception *);
> >>
> >> +#if defined(__arm__) && !(defined(__USING_SJLJ_EXCEPTIONS__) ||
> >> defined(__ARM_DWARF_EH___))
> >> +typedef struct _Unwind_Control_Block _Unwind_Control_Block;
> >> +typedef uint32_t _Unwind_EHT_Header;
> >> +
> >> +struct _Unwind_Control_Block {
> >> +  uint64_t exception_class;
> >> +  void (*exception_cleanup)(_Unwind_Reason_Code, _Unwind_Control_Block
> >> *);
> >> +  /* unwinder cache (private fields for the unwinder's use) */
> >> +  struct {
> >> +uint32_t reserved1; /* forced unwind stop function, 0 if not
> >> forced */
> >> +uint32_t reserved2; /* personality routine */
> >> +uin

Re: r309327 - Headers: fix _Unwind_{G,S}etGR for non-EHABI targets

2017-08-23 Thread Hans Wennborg via cfe-commits
Reverted from the 5.0 branch (together with r309226) in r311597.

On Thu, Jul 27, 2017 at 3:08 PM, Hans Wennborg  wrote:
> Merged to 5.0 in r309328.
>
> On Thu, Jul 27, 2017 at 2:56 PM, Saleem Abdulrasool via cfe-commits
>  wrote:
>> Author: compnerd
>> Date: Thu Jul 27 14:56:25 2017
>> New Revision: 309327
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=309327&view=rev
>> Log:
>> Headers: fix _Unwind_{G,S}etGR for non-EHABI targets
>>
>> The EHABI definition was being inlined into the users even when EHABI
>> was not in use.  Adjust the condition to ensure that the right version
>> is defined.
>>
>> Modified:
>> cfe/trunk/lib/Headers/unwind.h
>>
>> Modified: cfe/trunk/lib/Headers/unwind.h
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/unwind.h?rev=309327&r1=309326&r2=309327&view=diff
>> ==
>> --- cfe/trunk/lib/Headers/unwind.h (original)
>> +++ cfe/trunk/lib/Headers/unwind.h Thu Jul 27 14:56:25 2017
>> @@ -177,8 +177,7 @@ typedef _Unwind_Personality_Fn __persona
>>  typedef _Unwind_Reason_Code (*_Unwind_Trace_Fn)(struct _Unwind_Context *,
>>  void *);
>>
>> -#if defined(__arm__) && !defined(__APPLE__)
>> -
>> +#if defined(__arm__) && !(defined(__USING_SJLJ_EXCEPTIONS__) || 
>> defined(__ARM_DWARF_EH___))
>>  typedef enum {
>>_UVRSC_CORE = 0,/* integer register */
>>_UVRSC_VFP = 1, /* vfp */
>> @@ -200,14 +199,12 @@ typedef enum {
>>_UVRSR_FAILED = 2
>>  } _Unwind_VRS_Result;
>>
>> -#if !defined(__USING_SJLJ_EXCEPTIONS__) && !defined(__ARM_DWARF_EH__)
>>  typedef uint32_t _Unwind_State;
>>  #define _US_VIRTUAL_UNWIND_FRAME  ((_Unwind_State)0)
>>  #define _US_UNWIND_FRAME_STARTING ((_Unwind_State)1)
>>  #define _US_UNWIND_FRAME_RESUME   ((_Unwind_State)2)
>>  #define _US_ACTION_MASK   ((_Unwind_State)3)
>>  #define _US_FORCE_UNWIND  ((_Unwind_State)8)
>> -#endif
>>
>>  _Unwind_VRS_Result _Unwind_VRS_Get(struct _Unwind_Context *__context,
>>_Unwind_VRS_RegClass __regclass,
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D36642: [Lexer] Report more precise skipped regions (PR34166)

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



Comment at: test/Index/skipped-ranges.c:23
 // RUN: env CINDEXTEST_SHOW_SKIPPED_RANGES=1 c-index-test 
-test-annotate-tokens=%s:1:1:16:1 %s | FileCheck %s
-// CHECK: Skipping: [5:2 - 6:7]
-// CHECK: Skipping: [8:2 - 12:7]
-// CHECK: Skipping: [14:2 - 20:7]
+// CHECK: Skipping: [5:1 - 7:1]
+// CHECK: Skipping: [8:1 - 13:1]

Some editor clients might want to grey out the skipped PP ranges. The new end 
location is not ideal as we wouldn't want to grey out the trailing comments 
after the `#endif`.


https://reviews.llvm.org/D36642



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


[PATCH] D36642: [Lexer] Report more precise skipped regions (PR34166)

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



Comment at: lib/Lex/PPDirectives.cpp:564
+  if (Callbacks)
+Callbacks->SourceRangeSkipped(
+SourceRange(HashToken.getLocation(), CurPPLexer->getSourceLocation()));

You'd have to update the pp-tests in clang-tools-extra too


https://reviews.llvm.org/D36642



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


[PATCH] D37079: [Preprocessor] Correct internal token parsing of newline characters in CRLF

2017-08-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
Herald added a subscriber: javed.absar.

Discovered due to a goofy git setup, the test system-headerline-directive.c 
(and a few others)
failed because the token-consumption will consume only the '\r' in CRLF, making 
the preprocessor's
printed value give the wrong line number when returning from an include.  For 
example:

(line 1):#include \r\n

The "file exit" code causes the printer to try to print the 'returned to the 
main file' line.  It looks up
what the current line number is.  However, since the current 'token' is the 
'\n' (since only the \r was
consumed), it will give the line number as '1", not '2'.  This results in a few 
failed tests, but more importantly,
results in error messages being incorrect when compiling a previously 
preprocessed file.


https://reviews.llvm.org/D37079

Files:
  lib/Lex/Lexer.cpp
  test/Frontend/.gitattributes
  test/Frontend/system-header-line-directive-ms-lineendings.c


Index: test/Frontend/system-header-line-directive-ms-lineendings.c
===
--- /dev/null
+++ test/Frontend/system-header-line-directive-ms-lineendings.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 %s -E -o - -I %S/Inputs -isystem 
%S/Inputs/SystemHeaderPrefix | FileCheck %s
+#include 
+#include 
+
+#include "line-directive.h"
+
+// This tests that the line numbers for the current file are correctly 
outputted
+// for the include-file-completed test case.  
+
+// CHECK: # 1 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
+// CHECK: # 1 "{{.*}}noline.h" 1 3
+// CHECK: foo();
+// CHECK: # 3 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
+// CHECK: # 1 "{{.*}}line-directive-in-system.h" 1 3
+//  The "3" below indicates that "foo.h" is considered a system header.
+// CHECK: # 1 "foo.h" 3
+// CHECK: foo();
+// CHECK: # 4 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
+// CHECK: # 1 "{{.*}}line-directive.h" 1
+// CHECK: # 10 "foo.h"{{$}}
+// CHECK: # 6 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
Index: test/Frontend/.gitattributes
===
--- /dev/null
+++ test/Frontend/.gitattributes
@@ -0,0 +1,2 @@
+# Below test validates crlf line endings, so it should stay crlf.
+system-header-line-directive-ms-lineendings.c text eol=crlf
Index: lib/Lex/Lexer.cpp
===
--- lib/Lex/Lexer.cpp
+++ lib/Lex/Lexer.cpp
@@ -3073,6 +3073,8 @@
   
   case '\n':
   case '\r':
+if (CurPtr[0] != Char && (CurPtr[0] == '\n' || CurPtr[0] == '\r'))
+  Char = getAndAdvanceChar(CurPtr, Result);
 // If we are inside a preprocessor directive and we see the end of line,
 // we know we are done with the directive, so return an EOD token.
 if (ParsingPreprocessorDirective) {


Index: test/Frontend/system-header-line-directive-ms-lineendings.c
===
--- /dev/null
+++ test/Frontend/system-header-line-directive-ms-lineendings.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 %s -E -o - -I %S/Inputs -isystem %S/Inputs/SystemHeaderPrefix | FileCheck %s
+#include 
+#include 
+
+#include "line-directive.h"
+
+// This tests that the line numbers for the current file are correctly outputted
+// for the include-file-completed test case.  
+
+// CHECK: # 1 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
+// CHECK: # 1 "{{.*}}noline.h" 1 3
+// CHECK: foo();
+// CHECK: # 3 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
+// CHECK: # 1 "{{.*}}line-directive-in-system.h" 1 3
+//  The "3" below indicates that "foo.h" is considered a system header.
+// CHECK: # 1 "foo.h" 3
+// CHECK: foo();
+// CHECK: # 4 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
+// CHECK: # 1 "{{.*}}line-directive.h" 1
+// CHECK: # 10 "foo.h"{{$}}
+// CHECK: # 6 "{{.*}}system-header-line-directive-ms-lineendings.c" 2
Index: test/Frontend/.gitattributes
===
--- /dev/null
+++ test/Frontend/.gitattributes
@@ -0,0 +1,2 @@
+# Below test validates crlf line endings, so it should stay crlf.
+system-header-line-directive-ms-lineendings.c text eol=crlf
Index: lib/Lex/Lexer.cpp
===
--- lib/Lex/Lexer.cpp
+++ lib/Lex/Lexer.cpp
@@ -3073,6 +3073,8 @@
   
   case '\n':
   case '\r':
+if (CurPtr[0] != Char && (CurPtr[0] == '\n' || CurPtr[0] == '\r'))
+  Char = getAndAdvanceChar(CurPtr, Result);
 // If we are inside a preprocessor directive and we see the end of line,
 // we know we are done with the directive, so return an EOD token.
 if (ParsingPreprocessorDirective) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37079: [Preprocessor] Correct internal token parsing of newline characters in CRLF

2017-08-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: test/Frontend/system-header-line-directive-ms-lineendings.c:1
+// RUN: %clang_cc1 %s -E -o - -I %S/Inputs -isystem 
%S/Inputs/SystemHeaderPrefix | FileCheck %s
+#include 

Note: this whole file is dos line endings (preserved by the above git 
attributes, and subversion eol-style when i go to commit it).  It doesn't show 
in phab however for some reaosn.


https://reviews.llvm.org/D37079



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


r311601 - Fix a bug in CGDebugInfo::EmitInlineFunctionStart causing DILocations to be

2017-08-23 Thread Adrian Prantl via cfe-commits
Author: adrian
Date: Wed Aug 23 14:24:12 2017
New Revision: 311601

URL: http://llvm.org/viewvc/llvm-project?rev=311601&view=rev
Log:
Fix a bug in CGDebugInfo::EmitInlineFunctionStart causing DILocations to be
parented in function declarations.

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

Added:
cfe/trunk/test/CodeGenCXX/debug-info-inlined.cpp
Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=311601&r1=311600&r2=311601&view=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Wed Aug 23 14:24:12 2017
@@ -3287,7 +3287,7 @@ void CGDebugInfo::EmitInlineFunctionStar
   llvm::DISubprogram *SP = nullptr;
   if (FI != SPCache.end())
 SP = dyn_cast_or_null(FI->second);
-  if (!SP)
+  if (!SP || !SP->isDefinition())
 SP = getFunctionStub(GD);
   FnBeginRegionCount.push_back(LexicalBlockStack.size());
   LexicalBlockStack.emplace_back(SP);

Added: cfe/trunk/test/CodeGenCXX/debug-info-inlined.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/debug-info-inlined.cpp?rev=311601&view=auto
==
--- cfe/trunk/test/CodeGenCXX/debug-info-inlined.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/debug-info-inlined.cpp Wed Aug 23 14:24:12 2017
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -triple i686-pc-windows-msvc19.0.24213 
-gcodeview -debug-info-kind=limited -std=c++14 %s -o - | FileCheck %s
+// PR33997.
+struct already_AddRefed {
+  ~already_AddRefed();
+};
+struct RefPtr {
+  operator int *();
+};
+struct ServoCssRulesStrong {
+  already_AddRefed Consume();
+};
+struct GroupRule {
+  GroupRule(already_AddRefed);
+};
+class ConditionRule : GroupRule {
+  using GroupRule::GroupRule;
+};
+class CSSMediaRule : ConditionRule {
+  using ConditionRule::ConditionRule;
+};
+class CSSMozDocumentRule : ConditionRule {
+  using ConditionRule::ConditionRule;
+};
+class ServoDocumentRule : CSSMozDocumentRule {
+  ServoDocumentRule(RefPtr);
+};
+class ServoMediaRule : CSSMediaRule {
+  ServoMediaRule(RefPtr);
+};
+ServoCssRulesStrong Servo_MediaRule_GetRules(int *);
+ServoCssRulesStrong Servo_DocumentRule_GetRules(int *);
+ServoDocumentRule::ServoDocumentRule(RefPtr aRawRule)
+: CSSMozDocumentRule(Servo_DocumentRule_GetRules(aRawRule).Consume()) {}
+
+ServoMediaRule::ServoMediaRule(RefPtr aRawRule)
+: CSSMediaRule(Servo_MediaRule_GetRules(aRawRule).Consume()) {}
+
+// CHECK: define{{.*}}ServoMediaRule
+// CHECK-NOT: {{ ret }}
+// CHECK: store %class.ConditionRule* %
+// CHECK-SAME: %class.ConditionRule** %
+// CHECK-SAME: !dbg ![[INL:[0-9]+]]
+
+// CHECK: ![[INL]] = !DILocation(line: 16, scope: ![[SP:[0-9]+]], inlinedAt:
+// CHECK: ![[SP]] = distinct !DISubprogram(name: "GroupRule", 
{{.*}}isDefinition: true


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


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

2017-08-23 Thread Mark Zeren via Phabricator via cfe-commits
mzeren-vmw added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:383
+  Current.Previous->is(tok::hash) && State.FirstIndent > 0) {
+// subtract 1 so indent lines up with non-preprocessor code
+Spaces += State.FirstIndent;

djasper wrote:
> euhlmann wrote:
> > djasper wrote:
> > > Same here and use full sentences.
> > > 
> > > Also, this does not seem to be what the example in the style option 
> > > suggests and I'd rather not do it (subtracting 1).
> > I apologize, the style option documentation was a typo. The patch summary 
> > has the intended behavior, and I mentioned there that I count the hash as a 
> > column. Part of the reasoning for this is because it would look the same 
> > visually with spaces or tabs.
> Do you know of a coding style that writes something about this? I think the 
> similarity of spaces vs. tabs is not a strong reason because a source file 
> will either use one or the other. To me:
> 
>   #if a == 1
>   # define X
>   # if b == 2
>   #   define Y
>   ...
> 
> Would look weird. I'd prefer if we kept this simpler and more consistent.
@djasper I just noticed that the [[ 
https://google.github.io/styleguide/cppguide.html#Preprocessor_Directives | 
Google Style Guide  ]] has:
```
#if DISASTER_PENDING  // Correct -- Starts at beginning of line
DropEverything();
# if NOTIFY   // OK but not required -- Spaces after #
NotifyClient();
# endif
#endif
```
Note the single space in `# if NOTIFY`. Can we correct the Guide to match what 
we have here?



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] D34224: [NFC] remove trailing WS

2017-08-23 Thread Aditya Kumar via Phabricator via cfe-commits
hiraditya closed this revision.
hiraditya added a comment.

Closed by commit: https://reviews.llvm.org/rL311283


https://reviews.llvm.org/D34224



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


r311612 - Fix mangling for dependent "type { expr-list }" expressions, and add mangling for designated initializers matching recent cxx-abi-dev discussion.

2017-08-23 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Aug 23 15:12:08 2017
New Revision: 311612

URL: http://llvm.org/viewvc/llvm-project?rev=311612&view=rev
Log:
Fix mangling for dependent "type { expr-list }" expressions, and add mangling 
for designated initializers matching recent cxx-abi-dev discussion.

Modified:
cfe/trunk/include/clang/AST/ExprCXX.h
cfe/trunk/lib/AST/ASTDumper.cpp
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/lib/AST/StmtProfile.cpp
cfe/trunk/test/CodeGenCXX/mangle-exprs.cpp
cfe/trunk/test/CodeGenCXX/mangle-fail.cpp

Modified: cfe/trunk/include/clang/AST/ExprCXX.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ExprCXX.h?rev=311612&r1=311611&r2=311612&view=diff
==
--- cfe/trunk/include/clang/AST/ExprCXX.h (original)
+++ cfe/trunk/include/clang/AST/ExprCXX.h Wed Aug 23 15:12:08 2017
@@ -3056,6 +3056,11 @@ public:
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
 
+  /// Determine whether this expression models list-initialization.
+  /// If so, there will be exactly one subexpression, which will be
+  /// an InitListExpr.
+  bool isListInitialization() const { return LParenLoc.isInvalid(); }
+
   /// \brief Retrieve the number of arguments.
   unsigned arg_size() const { return NumArgs; }
 

Modified: cfe/trunk/lib/AST/ASTDumper.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTDumper.cpp?rev=311612&r1=311611&r2=311612&view=diff
==
--- cfe/trunk/lib/AST/ASTDumper.cpp (original)
+++ cfe/trunk/lib/AST/ASTDumper.cpp Wed Aug 23 15:12:08 2017
@@ -537,6 +537,7 @@ namespace  {
 void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node);
 void VisitCXXThisExpr(const CXXThisExpr *Node);
 void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *Node);
+void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr 
*Node);
 void VisitCXXConstructExpr(const CXXConstructExpr *Node);
 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node);
 void VisitCXXNewExpr(const CXXNewExpr *Node);
@@ -2169,12 +2170,24 @@ void ASTDumper::VisitCXXFunctionalCastEx
  << " <" << Node->getCastKindName() << ">";
 }
 
+void ASTDumper::VisitCXXUnresolvedConstructExpr(
+const CXXUnresolvedConstructExpr *Node) {
+  VisitExpr(Node);
+  dumpType(Node->getTypeAsWritten());
+  if (Node->isListInitialization())
+OS << " list";
+}
+
 void ASTDumper::VisitCXXConstructExpr(const CXXConstructExpr *Node) {
   VisitExpr(Node);
   CXXConstructorDecl *Ctor = Node->getConstructor();
   dumpType(Ctor->getType());
   if (Node->isElidable())
 OS << " elidable";
+  if (Node->isListInitialization())
+OS << " list";
+  if (Node->isStdInitListInitialization())
+OS << " std::initializer_list";
   if (Node->requiresZeroInitialization())
 OS << " zeroing";
 }

Modified: cfe/trunk/lib/AST/ItaniumMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ItaniumMangle.cpp?rev=311612&r1=311611&r2=311612&view=diff
==
--- cfe/trunk/lib/AST/ItaniumMangle.cpp (original)
+++ cfe/trunk/lib/AST/ItaniumMangle.cpp Wed Aug 23 15:12:08 2017
@@ -3343,7 +3343,6 @@ recurse:
   case Expr::BlockExprClass:
   case Expr::ChooseExprClass:
   case Expr::CompoundLiteralExprClass:
-  case Expr::DesignatedInitExprClass:
   case Expr::ExtVectorElementExprClass:
   case Expr::GenericSelectionExprClass:
   case Expr::ObjCEncodeExprClass:
@@ -3421,6 +3420,27 @@ recurse:
 break;
   }
 
+  case Expr::DesignatedInitExprClass: {
+auto *DIE = cast(E);
+for (const auto &Designator : DIE->designators()) {
+  if (Designator.isFieldDesignator()) {
+Out << "di";
+mangleSourceName(Designator.getFieldName());
+  } else if (Designator.isArrayDesignator()) {
+Out << "dx";
+mangleExpression(DIE->getArrayIndex(Designator));
+  } else {
+assert(Designator.isArrayRangeDesignator() &&
+   "unknown designator kind");
+Out << "dX";
+mangleExpression(DIE->getArrayRangeStart(Designator));
+mangleExpression(DIE->getArrayRangeEnd(Designator));
+  }
+}
+mangleExpression(DIE->getInit());
+break;
+  }
+
   case Expr::CXXDefaultArgExprClass:
 mangleExpression(cast(E)->getExpr(), Arity);
 break;
@@ -3578,6 +3598,16 @@ recurse:
 const CXXUnresolvedConstructExpr *CE = cast(E);
 unsigned N = CE->arg_size();
 
+if (CE->isListInitialization()) {
+  assert(N == 1 && "unexpected form for list initialization");
+  auto *IL = cast(CE->getArg(0));
+  Out << "tl";
+  mangleType(CE->getType());
+  mangleInitListElements(IL);
+  Out << "E";
+  return;
+}
+
 Out << "cv";
 mangleType(CE->getType());
 if (N != 1) Out << '_';

r311617 - ObjC++: decorate ObjC interfaces in MSABI properly

2017-08-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Wed Aug 23 15:38:58 2017
New Revision: 311617

URL: http://llvm.org/viewvc/llvm-project?rev=311617&view=rev
Log:
ObjC++: decorate ObjC interfaces in MSABI properly

`id` needs to be handled specially since it is a `TypedefType` which is
sugar for an `ObjCObjectPointerType` whose pointee is an
`ObjCObjectType` with base `BuiltinType::ObjCIdType` and no protocols
and the first level of pointer gets it own type implementation.  `Class`
is similar with the `ObjCClassType` as the base instead.

The qualifiers on the base type of the `ObjCObjectType` need to be
dropped because the innermost `mangleType` will handle the qualifiers
itself.

`id` is desugared to `struct objc_object *` which should be encoded as
`PAUobjc_object@@`.  `Class` is desugared to `struct objc_class *` which
should be encoded as `PAUobjc_class@@`.

We were previously applying an extra modifier `A` which will be handled
during the recursive call.

This now properly decorates interface types as well as `Class` and `id`.
This corrects the interactions between C++ and ObjC++ for the type
specifier decoration.

Added:
cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm
Modified:
cfe/trunk/lib/AST/MicrosoftMangle.cpp
cfe/trunk/test/CodeGenObjCXX/microsoft-abi-arc-param-order.mm

Modified: cfe/trunk/lib/AST/MicrosoftMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/MicrosoftMangle.cpp?rev=311617&r1=311616&r2=311617&view=diff
==
--- cfe/trunk/lib/AST/MicrosoftMangle.cpp (original)
+++ cfe/trunk/lib/AST/MicrosoftMangle.cpp Wed Aug 23 15:38:58 2017
@@ -2324,13 +2324,15 @@ void MicrosoftCXXNameMangler::mangleType
   manglePointerExtQualifiers(Quals, PointeeType);
   mangleType(PointeeType, Range);
 }
+
 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
  Qualifiers Quals, SourceRange Range) {
+  if (T->isObjCIdType() || T->isObjCClassType())
+return mangleType(T->getPointeeType(), Range, QMM_Drop);
+
   QualType PointeeType = T->getPointeeType();
   manglePointerCVQualifiers(Quals);
   manglePointerExtQualifiers(Quals, PointeeType);
-  // Object pointers never have qualifiers.
-  Out << 'A';
   mangleType(PointeeType, Range);
 }
 
@@ -2438,7 +2440,7 @@ void MicrosoftCXXNameMangler::mangleType
  SourceRange Range) {
   // We don't allow overloading by different protocol qualification,
   // so mangling them isn't necessary.
-  mangleType(T->getBaseType(), Range);
+  mangleType(T->getBaseType(), Range, QMM_Drop);
 }
 
 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,

Modified: cfe/trunk/test/CodeGenObjCXX/microsoft-abi-arc-param-order.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/microsoft-abi-arc-param-order.mm?rev=311617&r1=311616&r2=311617&view=diff
==
--- cfe/trunk/test/CodeGenObjCXX/microsoft-abi-arc-param-order.mm (original)
+++ cfe/trunk/test/CodeGenObjCXX/microsoft-abi-arc-param-order.mm Wed Aug 23 
15:38:58 2017
@@ -9,7 +9,7 @@ struct A {
 
 // Verify that we destruct things from left to right in the MS C++ ABI: a, b, 
c, d.
 //
-// CHECK-LABEL: define void 
@"\01?test_arc_order@@YAXUA@@PAAAPAUobjc_object@@01@Z"
+// CHECK-LABEL: define void @"\01?test_arc_order@@YAXUA@@PAUobjc_object@@01@Z"
 // CHECK:   (<{ %struct.A, i8*, %struct.A, i8* }>* 
inalloca)
 void test_arc_order(A a, id __attribute__((ns_consumed)) b , A c, id 
__attribute__((ns_consumed)) d) {
   // CHECK: call x86_thiscallcc void @"\01??1A@@QAE@XZ"(%struct.A* %{{.*}})

Added: cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm?rev=311617&view=auto
==
--- cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm (added)
+++ cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm Wed Aug 23 15:38:58 2017
@@ -0,0 +1,122 @@
+// RUN: %clang_cc1 -triple thumbv7-windows-msvc -fdeclspec -std=c++11 
-fobjc-runtime=ios-6.0 -o - -emit-llvm %s | FileCheck %s
+
+@class I;
+
+id kid;
+// CHECK: @"\01?kid@@3PAUobjc_object@@A" = global
+
+Class klass;
+// CHECK: @"\01?klass@@3PAUobjc_class@@A" = global
+
+I *kI;
+// CHECK: @"\01?kI@@3PAUI@@A" = global
+
+void f(I *) {}
+// CHECK-LABEL: "\01?f@@YAXPAUI@@@Z"
+
+void f(const I *) {}
+// CHECK-LABEL: "\01?f@@YAXPBUI@@@Z"
+
+void f(I &) {}
+// CHECK-LABEL: "\01?f@@YAXAAUI@@@Z"
+
+void f(const I &) {}
+// CHECK-LABEL: "\01?f@@YAXABUI@@@Z"
+
+void f(const I &&) {}
+// CHECK-LABEL: "\01?f@@YAX$$QBUI@@@Z"
+
+void g(id) {}
+// CHECK-LABEL: "\01?g@@YAXPAUobjc_object@@@Z"
+
+void g(id &) {}
+// CHECK-LABEL: "\01?g@@YAXAAPAUobjc_object@@@Z"
+
+void g(const id &) {}
+// CHECK-LABEL: "\01?g@@YAXABPAUobjc_object@@@Z"
+
+void g(id &&) {}
+// CHEC

Re: r284549 - DR1330: instantiate exception-specifications when "needed". We previously did

2017-08-23 Thread Richard Smith via cfe-commits
On 23 August 2017 at 08:01, Alex L via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Hi Richard,
>
> It looks like this commit caused PR34298 (https://bugs.llvm.org/show_bu
> g.cgi?id=34298). Now Clang fails to compile a libc++ std::function member
> variable with an incomplete return type. Libstdc++ works though, so I
> assume that the right way to fix this is to change libc++?
>

I've added some thoughts to the bug. It appears that the rejected code is
not required to work per the C++ standard rules, but it really ought to,
and this looks like a libc++ bug rather than a Clang bug. (Though the notes
we produce aren't particularly clear as to how we got there, sadly.)


> Cheers,
> Alex
>
> On 19 October 2016 at 00:39, Richard Smith via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: rsmith
>> Date: Tue Oct 18 18:39:12 2016
>> New Revision: 284549
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=284549&view=rev
>> Log:
>> DR1330: instantiate exception-specifications when "needed". We previously
>> did
>> not instantiate exception specifications of functions if they were only
>> used in
>> unevaluated contexts (other than 'noexcept' expressions).
>>
>> In C++17 onwards, this becomes essential since the exception
>> specification is
>> now part of the function's type.
>>
>> Note that this means that constructs like the following no longer work:
>>
>>   struct A {
>> static T f() noexcept(...);
>> decltype(f()) *p;
>>   };
>>
>> ... because the decltype expression now needs the exception specification
>> of
>> 'f', which has not yet been parsed.
>>
>> Modified:
>> cfe/trunk/lib/Sema/SemaExpr.cpp
>> cfe/trunk/lib/Sema/SemaOverload.cpp
>> cfe/trunk/test/CXX/drs/dr13xx.cpp
>> cfe/trunk/test/SemaCXX/constant-expression-cxx1z.cpp
>> cfe/trunk/test/SemaCXX/cxx0x-defaulted-functions.cpp
>> cfe/trunk/test/SemaCXX/libstdcxx_pair_swap_hack.cpp
>> cfe/trunk/test/SemaTemplate/instantiate-exception-spec-cxx11.cpp
>> cfe/trunk/www/cxx_dr_status.html
>>
>> Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaE
>> xpr.cpp?rev=284549&r1=284548&r2=284549&view=diff
>> 
>> ==
>> --- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaExpr.cpp Tue Oct 18 18:39:12 2016
>> @@ -2889,6 +2889,14 @@ ExprResult Sema::BuildDeclarationNameExp
>>
>>{
>>  QualType type = VD->getType();
>> +if (auto *FPT = type->getAs()) {
>> +  // C++ [except.spec]p17:
>> +  //   An exception-specification is considered to be needed when:
>> +  //   - in an expression, the function is the unique lookup result
>> or
>> +  // the selected member of a set of overloaded functions.
>> +  ResolveExceptionSpec(Loc, FPT);
>> +  type = VD->getType();
>> +}
>>  ExprValueKind valueKind = VK_RValue;
>>
>>  switch (D->getKind()) {
>> @@ -13138,6 +13146,19 @@ void Sema::MarkFunctionReferenced(Source
>> Func->getMemberSpecializationInfo()))
>>  checkSpecializationVisibility(Loc, Func);
>>
>> +  // C++14 [except.spec]p17:
>> +  //   An exception-specification is considered to be needed when:
>> +  //   - the function is odr-used or, if it appears in an unevaluated
>> operand,
>> +  // would be odr-used if the expression were potentially-evaluated;
>> +  //
>> +  // Note, we do this even if MightBeOdrUse is false. That indicates
>> that the
>> +  // function is a pure virtual function we're calling, and in that case
>> the
>> +  // function was selected by overload resolution and we need to resolve
>> its
>> +  // exception specification for a different reason.
>> +  const FunctionProtoType *FPT = Func->getType()->getAs> nProtoType>();
>> +  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
>> +ResolveExceptionSpec(Loc, FPT);
>> +
>>// If we don't need to mark the function as used, and we don't need to
>>// try to provide a definition, there's nothing more to do.
>>if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
>> @@ -13196,12 +13217,6 @@ void Sema::MarkFunctionReferenced(Source
>>// FIXME: Is this really right?
>>if (CurContext == Func) return;
>>
>> -  // Resolve the exception specification for any function which is
>> -  // used: CodeGen will need it.
>> -  const FunctionProtoType *FPT = Func->getType()->getAs> nProtoType>();
>> -  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
>> -ResolveExceptionSpec(Loc, FPT);
>> -
>>// Implicit instantiation of function templates and member functions of
>>// class templates.
>>if (Func->isImplicitlyInstantiable()) {
>>
>> Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaO
>> verload.cpp?rev=284549&r1=284548&r2=284549&view=diff
>> 
>> 

[PATCH] D35782: [C++2a][Preprocessor] Implement p0306 __VA_OPT__ (Comma omission and comma deletion)

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

This generally looks good. I have some specific ideas about moving more of the 
recognition of the `__VA_OPT__` `(` ... `)` pattern into 
`VAOptDefinitionContext`, so if you prefer you can go ahead with something like 
this patch and I'll do the refactoring afterwards.




Comment at: include/clang/Basic/DiagnosticLexKinds.td:360
+
+def err_vaopt_paste_at_end : Error<"'##' cannot appear at end within 
__VA_OPT__">;
+

`'##' cannot appear at end of __VA_OPT__ argument` please, to match the change 
to the previous diagnostic.



Comment at: include/clang/Lex/VariadicMacroSupport.h:1
+//===- VariadicMacroSupport.h - state-machines and scope-gaurds -*- C++ 
-*-===//
+//

rsmith wrote:
> Typo "gaurds".
nit: "state machines" and "scope guards" should not be hyphenated



Comment at: include/clang/Lex/VariadicMacroSupport.h:69
 
+  class VAOptDefinitionContext {
+Preprocessor &PP;

Please add a documentation comment explaining what this is. Maybe something 
like:

"A class for tracking whether we're inside a __VA_OPT__ during a traversal of 
the tokens of a variadic macro."



Comment at: include/clang/Lex/VariadicMacroSupport.h:119
+
+  class VAOptExpansionContext : VAOptDefinitionContext {
+

And here:

"A class for tracking whether we're inside a __VA_OPT__ during traversal of the 
tokens of a macro as part of macro expansion."



Comment at: lib/Lex/PPDirectives.cpp:2384-2418
+if (VAOCtx.isVAOptToken(Tok)) {
+  // If we're already within a VAOPT, emit an error.
+  if (VAOCtx.isInVAOpt()) {
+Diag(Tok, diag::err_pp_vaopt_nested_use);
+return nullptr;
+  }
+  // Ensure VAOPT is followed by a '(' .

I think I would be inclined to move more of this logic into 
`VAOptDefinitionContext`, maybe a `TokenState process(const Token&)` member 
that returns an enum saying whether the token should be handled normally, 
skipped, diagnosed due to missing lparen, diagnosed due to nested va_opt, ...



Comment at: lib/Lex/Preprocessor.cpp:130
+  if (getLangOpts().CPlusPlus2a) {
+(Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
+SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);

Have you considered allowing this as an extension in other language modes?



Comment at: lib/Lex/TokenLexer.cpp:189-195
+  const bool CalledWithVariadicArguments = [this] {
+if (Macro->isVariadic()) {
+  const int VariadicArgIndex = Macro->getNumParams() - 1;
+  const Token *VarArgs = ActualArgs->getUnexpArgument(VariadicArgIndex);
+  return VarArgs->isNot(tok::eof);
+}
+return false;

Please make this a member function of `MacroArgs` (passing in the `MacroInfo*`).



Comment at: lib/Lex/TokenLexer.cpp:275-284
+// If VAOPT had a hashhash before it (that was itself not preceded
+// by a placemarker token and therefore added to ResultToks) and 
if 
+// VAOPT reduces to a placemarker, remove that hashhash.
+// 
+// #define F(a,...) a ## __VA_OPT__(x)
+//   F()  <-- ResultToks does not contain preceding hashhash.
+//   F(1) <-- ResultToks does contain the preceding hashhash.

Is this extra check really necessary? We only set `PasteBefore` to `true` if 
there was a `hashhash` token in the token stream prior to the `__VA_OPT__`, so 
it seems like we should be able to assume the token is still there now.



Comment at: lib/Lex/TokenLexer.cpp:285
+  ResultToks.pop_back();
+  } else if (HasPasteAfter && !VCtx.hasStringifyOrCharifyBefore()) {
+++I; // Skip the hashhash if the empty tokens are not stringified

I think it might be more obvious to move this `hasStringifyOrCharifyBefore` 
check upwards, and define a `bool IsPlacemarkerToken = !NumVAOptTokens && 
!VCtx.hasStringifyOrCharifyBefore();`, then conditionalize these special cases 
on `IsPlacemarkerToken` not `!NumVAOptTokens`.



Comment at: lib/Lex/TokenLexer.cpp:321-322
+  // Replace the token prior to the first ## in this iteration.
+  ConcatenatedVAOPTResultToks[ConcatenatedVAOPTResultToks.size() -
+  1] = LHS;
+  if (CurTokenIdx == NumVAOptTokens)

`ConcatenatedVAOPTResultToks.back() = LHS;`



Comment at: lib/Lex/TokenLexer.cpp:357
+break /*out of inner loop*/;
+  } while (!CalledWithVariadicArguments && I != E);  
+  

The first part of this `while` condition has no effect. The second part has an 
effect, but it's tremendously confusing to put this check here, when it 
corresponds only to the `con

r311621 - Fix ClangFormatFuzzer.

2017-08-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 23 17:30:28 2017
New Revision: 311621

URL: http://llvm.org/viewvc/llvm-project?rev=311621&view=rev
Log:
Fix ClangFormatFuzzer.

Modified:
cfe/trunk/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp

Modified: cfe/trunk/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp?rev=311621&r1=311620&r2=311621&view=diff
==
--- cfe/trunk/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp (original)
+++ cfe/trunk/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp Wed Aug 23 
17:30:28 2017
@@ -20,7 +20,10 @@ extern "C" int LLVMFuzzerTestOneInput(ui
   std::string s((const char *)data, size);
   auto Style = getGoogleStyle(clang::format::FormatStyle::LK_Cpp);
   Style.ColumnLimit = 60;
-  applyAllReplacements(s, clang::format::reformat(
-  Style, s, {clang::tooling::Range(0, s.size())}));
+  auto Replaces = reformat(Style, s, clang::tooling::Range(0, s.size()));
+  auto Result = applyAllReplacements(s, Replaces);
+
+  // Output must be checked, as otherwise we crash.
+  if (!Result) {}
   return 0;
 }


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


[PATCH] D37089: [Sema] Error out early for tags defined inside an enumeration.

2017-08-23 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.

This fixes PR28903 by avoiding access check for inner enum constant. We
are performing access check because one enum constant references another
and because enum is defined in CXXRecordDecl. But access check doesn't
work because FindDeclaringClass doesn't expect more than one EnumDecl
and because inner enum has access AS_none due to not being an immediate
child of a record.

The change detects an enum is defined in wrong place and allows to skip
parsing its body. Access check is skipped together with body parsing.
There was no crash in C, added test case to cover the new error.

rdar://problem/28530809


https://reviews.llvm.org/D37089

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/enum.c
  clang/test/SemaCXX/enum.cpp


Index: clang/test/SemaCXX/enum.cpp
===
--- clang/test/SemaCXX/enum.cpp
+++ clang/test/SemaCXX/enum.cpp
@@ -110,3 +110,13 @@
 // expected-warning@-2 {{not an integral constant expression}}
 // expected-note@-3 {{value 28958703552 is outside the range of representable 
values}}
 #endif
+
+// PR28903
+struct PR28903 {
+  enum {
+PR28903_A = (enum { // expected-error-re {{'PR28903::(anonymous enum at 
{{.*}})' cannot be defined in an enumeration}}
+  PR28903_B,
+  PR28903_C = PR28903_B
+})
+  };
+};
Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -123,3 +123,13 @@
 // PR24610
 enum Color { Red, Green, Blue }; // expected-note{{previous use is here}}
 typedef struct Color NewColor; // expected-error {{use of 'Color' with tag 
type that does not match previous declaration}}
+
+// PR28903
+struct PR28903 { // expected-warning {{empty struct is a GNU extension}}
+  enum {
+PR28903_A = (enum { // expected-error-re {{'enum PR28903::(anonymous at 
{{.*}})' cannot be defined in an enumeration}}
+  PR28903_B,
+  PR28903_C = PR28903_B
+})
+  };  // expected-error {{expected expression}}
+};
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -13929,6 +13929,12 @@
 Invalid = true;
   }
 
+  if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) {
+Diag(New->getLocation(), diag::err_type_defined_in_enum)
+  << Context.getTagDeclType(New);
+Invalid = true;
+  }
+
   // Maybe add qualifier info.
   if (SS.isNotEmpty()) {
 if (SS.isSet()) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1329,6 +1329,8 @@
   "%0 cannot be defined in a type alias template">;
 def err_type_defined_in_condition : Error<
   "%0 cannot be defined in a condition">;
+def err_type_defined_in_enum : Error<
+  "%0 cannot be defined in an enumeration">;
 
 def note_pure_virtual_function : Note<
   "unimplemented pure virtual method %0 in %1">;


Index: clang/test/SemaCXX/enum.cpp
===
--- clang/test/SemaCXX/enum.cpp
+++ clang/test/SemaCXX/enum.cpp
@@ -110,3 +110,13 @@
 // expected-warning@-2 {{not an integral constant expression}}
 // expected-note@-3 {{value 28958703552 is outside the range of representable values}}
 #endif
+
+// PR28903
+struct PR28903 {
+  enum {
+PR28903_A = (enum { // expected-error-re {{'PR28903::(anonymous enum at {{.*}})' cannot be defined in an enumeration}}
+  PR28903_B,
+  PR28903_C = PR28903_B
+})
+  };
+};
Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -123,3 +123,13 @@
 // PR24610
 enum Color { Red, Green, Blue }; // expected-note{{previous use is here}}
 typedef struct Color NewColor; // expected-error {{use of 'Color' with tag type that does not match previous declaration}}
+
+// PR28903
+struct PR28903 { // expected-warning {{empty struct is a GNU extension}}
+  enum {
+PR28903_A = (enum { // expected-error-re {{'enum PR28903::(anonymous at {{.*}})' cannot be defined in an enumeration}}
+  PR28903_B,
+  PR28903_C = PR28903_B
+})
+  };  // expected-error {{expected expression}}
+};
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -13929,6 +13929,12 @@
 Invalid = true;
   }
 
+  if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) {
+Diag(New->getLocation(), diag::err_type_defined_in_enum)
+  << Context.getTagDeclType(New);
+Invalid = true;
+  }
+
   // Maybe add qualifier info.
   if (SS.isNotEmpty()) {
 if (SS.isSet()) 

[PATCH] D15465: [git-clang-format]: New option to perform formatting against staged changes only

2017-08-23 Thread Jason Newton via Phabricator via cfe-commits
nevion added a comment.

Hi - I'm coming here from Alexander's post on stackoverflow 

  and I'm interested to see both how this solution is progressing (no replies 
for 1.5 years is not a good sign), verify it still works, and to check if there 
are better options available hedging if this is stuck in limbo and out of 
usability date.


Repository:
  rL LLVM

https://reviews.llvm.org/D15465



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


[PATCH] D37089: [Sema] Error out early for tags defined inside an enumeration.

2017-08-23 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

I have also considered adding tests for structs and unions defined inside an 
enumeration but decided it doesn't add much value, given the code is working 
for all TagDecl.

Another option I had in mind is having a note pointing to outer enum. But the 
nesting is done in the same file so the outer enum shouldn't be hard to find. 
So I decided that complexity outweighs the added value.

If anybody thinks the aforementioned changes are valuable, please tell so.


https://reviews.llvm.org/D37089



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


[PATCH] D37090: Implement CFG construction for __finally.

2017-08-23 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.

This completes CFG construction for SEH AST nodes.

Also tweak test `g3` to explicitly check that `__leave` in an `__except` leaves 
the outer `__try`.


https://reviews.llvm.org/D37090

Files:
  lib/Analysis/CFG.cpp
  test/Sema/warn-unreachable-ms.c

Index: test/Sema/warn-unreachable-ms.c
===
--- test/Sema/warn-unreachable-ms.c
+++ test/Sema/warn-unreachable-ms.c
@@ -1,25 +1,26 @@
 // RUN: %clang_cc1 %s -triple=i686-pc-win32 -fsyntax-only -verify -fms-extensions -Wunreachable-code
+// RUN: %clang_cc1 %s -triple=i686-pc-win32 -fsyntax-only -verify -fms-extensions -Wunreachable-code -x c++ -fcxx-exceptions -DWITH_THROW
 
 void f();
 
 void g1() {
   __try {
 f();
 __leave;
 f();  // expected-warning{{will never be executed}}
-  } __except(1) {
+  } __except (1) {
 f();
   }
 
   // Completely empty.
   __try {
-  } __except(1) {
+  } __except (1) {
   }
 
   __try {
 f();
 return;
-  } __except(1) {  // Filter expression should not be marked as unreachable.
+  } __except (1) { // Filter expression should not be marked as unreachable.
 // Empty __except body.
   }
 }
@@ -31,25 +32,91 @@
   f();
   __leave;
   f(); // expected-warning{{will never be executed}}
-} __except(2) {
+} __except (2) {
 }
 f();
 __leave;
 f(); // expected-warning{{will never be executed}}
-  } __except(1) {
+  } __except (1) {
 f();
   }
 }
 
+#if defined(WITH_THROW)
 void g3() {
   __try {
 __try {
-  f();
+  throw 1;
 } __except (1) {
   __leave; // should exit outer try
 }
-__leave;
 f(); // expected-warning{{never be executed}}
   } __except (1) {
   }
 }
+#endif
+
+void g4() {
+  __try {
+f();
+__leave;
+f();  // expected-warning{{will never be executed}}
+  } __finally {
+f();
+  }
+
+  // Completely empty.
+  __try {
+  } __finally {
+  }
+
+  __try {
+f();
+return;  // Shouldn't make __finally body unreachable.
+  } __finally {
+f();
+  }
+}
+
+void g5() {
+  __try {
+// Nested __try.
+__try {
+  f();
+  __leave;
+  f(); // expected-warning{{will never be executed}}
+} __finally {
+}
+f();
+__leave;
+f(); // expected-warning{{will never be executed}}
+  } __finally {
+f();
+  }
+}
+
+// Jumps out of __finally have undefined behavior, but they're useful for
+// checking that the generated CFG looks right.
+
+#if defined(WITH_THROW)
+void g6() {
+  __try {
+__try {
+  throw 1;
+} __finally {
+  __leave; // should exit outer try expected-warning {{jump out of __finally block has undefined behavior}}
+}
+f(); // expected-warning{{never be executed}}
+  } __finally {
+  }
+}
+#endif
+
+void g7() {
+  f();
+  __try {
+  } __finally {
+return; // expected-warning {{jump out of __finally block has undefined behavior}}
+  }
+  f(); // expected-warning{{never be executed}}
+}
Index: lib/Analysis/CFG.cpp
===
--- lib/Analysis/CFG.cpp
+++ lib/Analysis/CFG.cpp
@@ -2539,57 +2539,83 @@
   // processing the current block.
   CFGBlock *SEHTrySuccessor = nullptr;
 
+  // We create a block for the __try (NewTryTerminatedBlock below).  This block
+  // is entered on exceptional control flow, and for a __try / __except either
+  // goes to the __except block (if the __except catches the exception) or to
+  // the end of the function (or the containing __try if it exists) if this
+  // exception isn't caught. The contents of the __try block are emitted as
+  // a regular block not connected to NewTryTerminatedBlock.  The __except
+  // block goes to the block after the __try / __except.
+  // For a __try / __finally, the __try goes to the __finally on exceptional
+  // control flow.  The __finally block connects to the block after they
+  // __try / __finally (for regular control flow) and to the end of the
+  // function (or the containing __try if it exists) on exceptional control
+  // flow.
+
   if (Block) {
 if (badCFG)
   return nullptr;
 SEHTrySuccessor = Block;
   } else SEHTrySuccessor = Succ;
 
-  // FIXME: Implement __finally support.
-  if (Terminator->getFinallyHandler())
-return NYS();
-
   CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
 
   // Create a new block that will contain the __try statement.
   CFGBlock *NewTryTerminatedBlock = createBlock(false);
+  CFGBlock *EndOfTry = NewTryTerminatedBlock;
 
   // Add the terminator in the __try block.
   NewTryTerminatedBlock->setTerminator(Terminator);
 
-  if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
-// The code after the try is the implicit successor if there's an __except.
-Succ = SEHTrySuccessor;
-Block = nullptr;
-CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
-if (!ExceptBlock)
-  return nullptr;
-// Add this block to the list of successors for the bl

[PATCH] D37091: Expose -mllvm -accurate-sample-profile to clang.

2017-08-23 Thread Dehao Chen via Phabricator via cfe-commits
danielcdh created this revision.
Herald added a subscriber: sanjoy.

With accurate sample profile, we can do more aggressive size optimization. For 
some size-critical application, this can reduce the text size by 20%


https://reviews.llvm.org/D37091

Files:
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Clang.cpp


Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -2340,6 +2340,12 @@
 true))
 CmdArgs.push_back("-fno-jump-tables");
 
+  if (Args.hasFlag(options::OPT_faccurate_sample_profile,
+   options::OPT_fno_accurate_sample_profile, false)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-accurate-sample-profile");
+  }
+
   if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
 options::OPT_fno_preserve_as_comments, true))
 CmdArgs.push_back("-fno-preserve-as-comments");
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -587,6 +587,14 @@
 def fPIE : Flag<["-"], "fPIE">, Group;
 def fno_PIE : Flag<["-"], "fno-PIE">, Group;
 def faccess_control : Flag<["-"], "faccess-control">, Group;
+def faccurate_sample_profile : Flag<["-"], "faccurate-sample-profile">,
+  Group, Flags<[DriverOption]>,
+  HelpText<"If sample profile is accurate, we will mark all un-sampled "
+   "callsite as cold. Otherwise, treat un-sampled callsites as if "
+   "we have no profile">;
+def fno_accurate_sample_profile : Flag<["-"], "fno-accurate-sample-profile">,
+  Group, Flags<[DriverOption]>;
+
 def fallow_unsupported : Flag<["-"], "fallow-unsupported">, Group;
 def fapple_kext : Flag<["-"], "fapple-kext">, Group, 
Flags<[CC1Option]>,
   HelpText<"Use Apple's kernel extensions ABI">;
@@ -643,6 +651,10 @@
 Alias;
 def fauto_profile_EQ : Joined<["-"], "fauto-profile=">,
 Alias;
+def fauto_profile_accurate : Flag<["-"], "fauto-profile-accurate">,
+Group, Alias;
+def fno_auto_profile_accurate : Flag<["-"], "fno-auto-profile-accurate">,
+Group, Alias;
 def fdebug_info_for_profiling : Flag<["-"], "fdebug-info-for-profiling">, 
Group,
 Flags<[CC1Option]>,
 HelpText<"Emit extra debug info to make sample profile more accurate.">;


Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -2340,6 +2340,12 @@
 true))
 CmdArgs.push_back("-fno-jump-tables");
 
+  if (Args.hasFlag(options::OPT_faccurate_sample_profile,
+   options::OPT_fno_accurate_sample_profile, false)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-accurate-sample-profile");
+  }
+
   if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
 options::OPT_fno_preserve_as_comments, true))
 CmdArgs.push_back("-fno-preserve-as-comments");
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -587,6 +587,14 @@
 def fPIE : Flag<["-"], "fPIE">, Group;
 def fno_PIE : Flag<["-"], "fno-PIE">, Group;
 def faccess_control : Flag<["-"], "faccess-control">, Group;
+def faccurate_sample_profile : Flag<["-"], "faccurate-sample-profile">,
+  Group, Flags<[DriverOption]>,
+  HelpText<"If sample profile is accurate, we will mark all un-sampled "
+   "callsite as cold. Otherwise, treat un-sampled callsites as if "
+   "we have no profile">;
+def fno_accurate_sample_profile : Flag<["-"], "fno-accurate-sample-profile">,
+  Group, Flags<[DriverOption]>;
+
 def fallow_unsupported : Flag<["-"], "fallow-unsupported">, Group;
 def fapple_kext : Flag<["-"], "fapple-kext">, Group, Flags<[CC1Option]>,
   HelpText<"Use Apple's kernel extensions ABI">;
@@ -643,6 +651,10 @@
 Alias;
 def fauto_profile_EQ : Joined<["-"], "fauto-profile=">,
 Alias;
+def fauto_profile_accurate : Flag<["-"], "fauto-profile-accurate">,
+Group, Alias;
+def fno_auto_profile_accurate : Flag<["-"], "fno-auto-profile-accurate">,
+Group, Alias;
 def fdebug_info_for_profiling : Flag<["-"], "fdebug-info-for-profiling">, Group,
 Flags<[CC1Option]>,
 HelpText<"Emit extra debug info to make sample profile more accurate.">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >