[PATCH] D37413: [X86][MS-InlineAsm] Extended support for variables / identifiers on memory / immediate expressions

2017-09-11 Thread coby via Phabricator via cfe-commits
coby updated this revision to Diff 114536.
coby added reviewers: myatsina, m_zuckerman.

Repository:
  rL LLVM

https://reviews.llvm.org/D37413

Files:
  include/clang/Parse/Parser.h
  include/clang/Sema/Sema.h
  lib/Parse/ParseStmtAsm.cpp
  lib/Sema/SemaStmtAsm.cpp
  test/CodeGen/ms-inline-asm-enums.cpp
  test/CodeGen/ms-inline-asm-variables.c

Index: lib/Parse/ParseStmtAsm.cpp
===
--- lib/Parse/ParseStmtAsm.cpp
+++ lib/Parse/ParseStmtAsm.cpp
@@ -54,17 +54,17 @@
 assert(AsmToks.size() == AsmTokOffsets.size());
   }
 
-  void *LookupInlineAsmIdentifier(StringRef &LineBuf,
-  llvm::InlineAsmIdentifierInfo &Info,
-  bool IsUnevaluatedContext) override {
+  void LookupInlineAsmIdentifier(StringRef &LineBuf,
+ llvm::InlineAsmIdentifierInfo &Info,
+ bool IsUnevaluatedContext) override {
 // Collect the desired tokens.
 SmallVector LineToks;
 const Token *FirstOrigToken = nullptr;
 findTokensForString(LineBuf, LineToks, FirstOrigToken);
 
 unsigned NumConsumedToks;
 ExprResult Result = TheParser.ParseMSAsmIdentifier(
-LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
+LineToks, NumConsumedToks, IsUnevaluatedContext);
 
 // If we consumed the entire line, tell MC that.
 // Also do this if we consumed nothing as a way of reporting failure.
@@ -89,9 +89,10 @@
   LineBuf = LineBuf.substr(0, TotalOffset);
 }
 
-// Initialize the "decl" with the lookup result.
-Info.OpDecl = static_cast(Result.get());
-return Info.OpDecl;
+// Initialize Info with the lookup result.
+if (!Result.isUsable())
+  return;
+TheParser.getActions().FillInlineAsmIdentifierInfo(Result.get(), Info);
   }
 
   StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
@@ -178,16 +179,9 @@
 }
 
 /// Parse an identifier in an MS-style inline assembly block.
-///
-/// \param CastInfo - a void* so that we don't have to teach Parser.h
-///   about the actual type.
 ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl &LineToks,
 unsigned &NumLineToksConsumed,
-void *CastInfo,
 bool IsUnevaluatedContext) {
-  llvm::InlineAsmIdentifierInfo &Info =
-  *(llvm::InlineAsmIdentifierInfo *)CastInfo;
-
   // Push a fake token on the end so that we don't overrun the token
   // stream.  We use ';' because it expression-parsing should never
   // overrun it.
@@ -227,7 +221,7 @@
  /*AllowDeductionGuide=*/false,
  /*ObjectType=*/nullptr, TemplateKWLoc, Id);
 // Perform the lookup.
-Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
+Result = Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id,
IsUnevaluatedContext);
   }
   // While the next two tokens are 'period' 'identifier', repeatedly parse it as
@@ -241,7 +235,7 @@
 IdentifierInfo *Id = Tok.getIdentifierInfo();
 ConsumeToken(); // Consume the identifier.
 Result = Actions.LookupInlineAsmVarDeclField(Result.get(), Id->getName(),
- Info, Tok.getLocation());
+ Tok.getLocation());
   }
 
   // Figure out how many tokens we are into LineToks.
Index: lib/Sema/SemaStmtAsm.cpp
===
--- lib/Sema/SemaStmtAsm.cpp
+++ lib/Sema/SemaStmtAsm.cpp
@@ -48,10 +48,10 @@
   if (E != E2 && E2->isLValue()) {
 if (!S.getLangOpts().HeinousExtensions)
   S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
-<< E->getSourceRange();
+  << E->getSourceRange();
 else
   S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
-<< E->getSourceRange();
+  << E->getSourceRange();
 // Accept, even if we emitted an error diagnostic.
 return false;
   }
@@ -607,23 +607,33 @@
   return NS;
 }
 
-static void fillInlineAsmTypeInfo(const ASTContext &Context, QualType T,
-  llvm::InlineAsmIdentifierInfo &Info) {
-  // Compute the type size (and array length if applicable?).
-  Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
-  if (T->isArrayType()) {
-const ArrayType *ATy = Context.getAsArrayType(T);
-Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
-Info.Length = Info.Size / Info.Type;
-  }
+void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
+   llvm::InlineAsmIdentifierInfo &Info) {
+  QualType T = Res->getType();
+  Expr::EvalResult Eval;
+  if (T->isFunctionType() || T->isDependentType()) {
+Info.setLabel(

[PATCH] D37566: [clang-tidy] fixed misc-unused-parameters omitting parameters default value

2017-09-11 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee updated this revision to Diff 114538.
PriMee added a comment.

Done :) Could you please commit this for me?


https://reviews.llvm.org/D37566

Files:
  clang-tidy/misc/UnusedParametersCheck.cpp
  test/clang-tidy/misc-unused-parameters.cpp


Index: test/clang-tidy/misc-unused-parameters.cpp
===
--- test/clang-tidy/misc-unused-parameters.cpp
+++ test/clang-tidy/misc-unused-parameters.cpp
@@ -14,15 +14,16 @@
 
 void b(int i = 1) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: parameter 'i' is unused 
[misc-unused-parameters]
-// CHECK-FIXES: {{^}}void b(int  /*i*/) {}{{$}}
+// CHECK-FIXES: {{^}}void b(int  /*i*/ = 1) {}{{$}}
 
 void c(int *i) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: parameter 'i' is unused 
[misc-unused-parameters]
 // CHECK-FIXES: {{^}}void c(int * /*i*/) {}{{$}}
 
 // Unchanged cases
 // ===
-void g(int i); // Don't remove stuff in declarations
+void f(int i); // Don't remove stuff in declarations
+void g(int i = 1);
 void h(int i) { (void)i; } // Don't remove used parameters
 
 bool useLambda(int (*fn)(int));
@@ -52,6 +53,11 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:33: warning
 // CHECK-FIXES: {{^}}static void staticFunctionE()
 
+static void staticFunctionF(int i = 4);
+// CHECK-FIXES: {{^}}static void staticFunctionF();
+static void staticFunctionF(int i) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:33: warning
+// CHECK-FIXES: {{^}}static void staticFunctionF()
 
 static void someCallSites() {
   staticFunctionA(1);
@@ -62,7 +68,12 @@
 // CHECK-FIXES: staticFunctionC(2);
   staticFunctionD(1, 2, 3);
 // CHECK-FIXES: staticFunctionD(1, 3);
-  staticFunctionE();
+  staticFunctionE(1);
+// CHECK-FIXES: staticFunctionE();
+  staticFunctionF(1);
+// CHECK-FIXES: staticFunctionF();
+  staticFunctionF();
+// CHECK-FIXES: staticFunctionF();
 }
 
 /*
@@ -95,6 +106,9 @@
   static void f(int i) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:21: warning
 // CHECK-FIXES: static void f(int  /*i*/) {}
+  static void g(int i = 1) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning
+// CHECK-FIXES: static void g(int  /*i*/ = 1) {}
 };
 
 namespace {
@@ -108,6 +122,9 @@
   void h(int i) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning
 // CHECK-FIXES: void h(int  /*i*/) {}
+  void s(int i = 1) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:14: warning
+// CHECK-FIXES: void s(int  /*i*/ = 1) {}
 };
 
 void C::f(int i) {}
@@ -125,6 +142,7 @@
 // CHECK-FIXES: c.g();
 
   useFunction(&C::h);
+  useFunction(&C::s);;
 }
 
 class Base {
Index: clang-tidy/misc/UnusedParametersCheck.cpp
===
--- clang-tidy/misc/UnusedParametersCheck.cpp
+++ clang-tidy/misc/UnusedParametersCheck.cpp
@@ -138,7 +138,8 @@
   if (Function->isExternallyVisible() ||
   !Result.SourceManager->isInMainFile(Function->getLocation()) ||
   !Indexer->getOtherRefs(Function).empty() || isOverrideMethod(Function)) {
-SourceRange RemovalRange(Param->getLocation(), Param->getLocEnd());
+SourceRange RemovalRange(Param->getLocation(),
+ Param->DeclaratorDecl::getSourceRange().getEnd());
 // Note: We always add a space before the '/*' to not accidentally create a
 // '*/*' for pointer types, which doesn't start a comment. clang-format 
will
 // clean this up afterwards.


Index: test/clang-tidy/misc-unused-parameters.cpp
===
--- test/clang-tidy/misc-unused-parameters.cpp
+++ test/clang-tidy/misc-unused-parameters.cpp
@@ -14,15 +14,16 @@
 
 void b(int i = 1) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: parameter 'i' is unused [misc-unused-parameters]
-// CHECK-FIXES: {{^}}void b(int  /*i*/) {}{{$}}
+// CHECK-FIXES: {{^}}void b(int  /*i*/ = 1) {}{{$}}
 
 void c(int *i) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: parameter 'i' is unused [misc-unused-parameters]
 // CHECK-FIXES: {{^}}void c(int * /*i*/) {}{{$}}
 
 // Unchanged cases
 // ===
-void g(int i); // Don't remove stuff in declarations
+void f(int i); // Don't remove stuff in declarations
+void g(int i = 1);
 void h(int i) { (void)i; } // Don't remove used parameters
 
 bool useLambda(int (*fn)(int));
@@ -52,6 +53,11 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:33: warning
 // CHECK-FIXES: {{^}}static void staticFunctionE()
 
+static void staticFunctionF(int i = 4);
+// CHECK-FIXES: {{^}}static void staticFunctionF();
+static void staticFunctionF(int i) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:33: warning
+// CHECK-FIXES: {{^}}static void staticFunctionF()
 
 static void someCallSites() {
   staticFunctionA(1);
@@ -62,7 +68,12 @@
 // CHECK-FIXES: staticFunctionC(2);
   staticFunctionD(1, 2, 3);
 // CHECK-FIXES: staticFunctionD(1, 3);
-  staticFunctionE();
+  staticFunctionE(1);
+// CHECK-FIXES: staticFunctionE();
+  staticFunctionF(1);
+// CHECK-FIXES: staticFunctionF();
+  staticFunctionF();
+// CHECK-FIXES: staticFunctionF();
 }
 
 /*

r312897 - Revert r312830: "Reinstall the patch "Use EmitPointerWithAlignment to get alignment information of the pointer used in atomic expr"."

2017-09-11 Thread Daniel Jasper via cfe-commits
Author: djasper
Date: Mon Sep 11 00:35:01 2017
New Revision: 312897

URL: http://llvm.org/viewvc/llvm-project?rev=312897&view=rev
Log:
Revert r312830: "Reinstall the patch "Use EmitPointerWithAlignment to get 
alignment information of the pointer used in atomic expr"."

This triggers llvm.org/PR31620 in several of our internal builds. I'll
forward reproduction instructions to the original author.

Removed:
cfe/trunk/test/CodeGenCXX/atomic-align.cpp
Modified:
cfe/trunk/lib/CodeGen/CGAtomic.cpp

Modified: cfe/trunk/lib/CodeGen/CGAtomic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGAtomic.cpp?rev=312897&r1=312896&r2=312897&view=diff
==
--- cfe/trunk/lib/CodeGen/CGAtomic.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGAtomic.cpp Mon Sep 11 00:35:01 2017
@@ -745,20 +745,20 @@ RValue CodeGenFunction::EmitAtomicExpr(A
   QualType MemTy = AtomicTy;
   if (const AtomicType *AT = AtomicTy->getAs())
 MemTy = AT->getValueType();
-  llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
-
-  Address Val1 = Address::invalid();
-  Address Val2 = Address::invalid();
-  Address Dest = Address::invalid();
-  Address Ptr = EmitPointerWithAlignment(E->getPtr());
-
   CharUnits sizeChars, alignChars;
   std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
   uint64_t Size = sizeChars.getQuantity();
   unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
-  bool UseLibcall = ((Ptr.getAlignment() % sizeChars) != 0 ||
+  bool UseLibcall = (sizeChars != alignChars ||
  getContext().toBits(sizeChars) > MaxInlineWidthInBits);
 
+  llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
+
+  Address Val1 = Address::invalid();
+  Address Val2 = Address::invalid();
+  Address Dest = Address::invalid();
+  Address Ptr(EmitScalarExpr(E->getPtr()), alignChars);
+
   if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
   E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);

Removed: cfe/trunk/test/CodeGenCXX/atomic-align.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/atomic-align.cpp?rev=312896&view=auto
==
--- cfe/trunk/test/CodeGenCXX/atomic-align.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/atomic-align.cpp (removed)
@@ -1,30 +0,0 @@
-// RUN: %clang_cc1 %s -std=c++11 -emit-llvm -o - -triple=x86_64-linux-gnu | 
FileCheck %s
-
-struct AM {
-  int f1, f2;
-};
-alignas(8) AM m;
-AM load1() {
-  AM am;
-  // m is declared to align to 8bytes, so generate load atomic instead
-  // of libcall.
-  // CHECK-LABEL: @_Z5load1v
-  // CHECK: load atomic {{.*}} monotonic
-  __atomic_load(&m, &am, 0);
-  return am;
-}
-
-struct BM {
-  int f1;
-  alignas(8) AM f2;
-};
-BM bm;
-AM load2() {
-  AM am;
-  // BM::f2 is declared to align to 8bytes, so generate load atomic instead
-  // of libcall.
-  // CHECK-LABEL: @_Z5load2v
-  // CHECK: load atomic {{.*}} monotonic
-  __atomic_load(&bm.f2, &am, 0);
-  return am;
-}


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


[PATCH] D37662: [AST] Make RecursiveASTVisitor visit TemplateDecls in source order

2017-09-11 Thread Manuel Klimek via Phabricator via cfe-commits
klimek accepted this revision.
klimek added a comment.
This revision is now accepted and ready to land.

LG


https://reviews.llvm.org/D37662



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


[PATCH] D37663: [AST] Make RecursiveASTVisitor visit CXXOperatorCallExpr in source order

2017-09-11 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added inline comments.



Comment at: include/clang/AST/RecursiveASTVisitor.h:334
+case OO_Arrow:
+case OO_Call:
+case OO_Subscript:

Why do we need to swap for calls?


https://reviews.llvm.org/D37663



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


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls added inline comments.



Comment at: lib/Driver/ToolChains/Arch/ARM.cpp:145-146
+  // choose soft mode.
+  if (ThreadPointer == ReadTPMode::Invalid)
+ThreadPointer = ReadTPMode::Soft;
+  return ThreadPointer;

spetrovic wrote:
> kristof.beyls wrote:
> >  and always give an error if an invalid mtp command line option was 
> > given, rather than default back to soft mode?
> If 'mtp' takes invalid value, error is always provided. This is the case when 
> there is no -mtp option in command line, you can see how the case of invalid 
> mtp argument is handled in the code above.
Right.
I just thought that the function would be ever so slightly simpler if it had 
the following structure roughly:

```
if (Arg *A = ...) {
  ThreadPointer = llvm::StringSwitch... ;
  if (!Invalid)
return ThreadPointer;
  if (empty)
D.Diag();
  else
D.Diag();
  return Invalid;
}
return ReadTPMode::Soft;
```

And probably is also slightly closer to the coding standard described in 
https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code
But this is a really minor comment.




https://reviews.llvm.org/D34878



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


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

2017-09-11 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added inline comments.



Comment at: clangd/GlobalCompilationDatabase.cpp:98-100
+if (CDB)
+  return CDB;
+return nullptr;

Isn't that the same as "return CDB"?


https://reviews.llvm.org/D37150



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


[PATCH] D37634: clang-rename: let -force handle multiple renames

2017-09-11 Thread Manuel Klimek via Phabricator via cfe-commits
klimek accepted this revision.
klimek added a comment.
This revision is now accepted and ready to land.

LG


https://reviews.llvm.org/D37634



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


[PATCH] D33826: [clang-tidy] avoid pointer cast to more strict alignment check

2017-09-11 Thread Eniko Donatella Toth via Phabricator via cfe-commits
NorenaLeonetti marked an inline comment as done.
NorenaLeonetti added a comment.

In https://reviews.llvm.org/D33826#861226, @aaron.ballman wrote:

> Have you run this check over any large code bases to see what the quality of 
> the diagnostics are?


`-checks=-*,cert-exp36-c,modernize-unary-static-assert`

the result:

real52m6.886s
user298m8.824s
sys 7m29.292s

`-checks=-*,modernize-unary-static-assert`

the result:

real52m5.305s
user302m38.508s
sys 8m53.008s


Repository:
  rL LLVM

https://reviews.llvm.org/D33826



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


[PATCH] D33826: [clang-tidy] avoid pointer cast to more strict alignment check

2017-09-11 Thread Eniko Donatella Toth via Phabricator via cfe-commits
NorenaLeonetti updated this revision to Diff 114544.

Repository:
  rL LLVM

https://reviews.llvm.org/D33826

Files:
  clang-tidy/cert/AvoidPointerCastToMoreStrictAlignmentCheck.cpp
  clang-tidy/cert/AvoidPointerCastToMoreStrictAlignmentCheck.h
  clang-tidy/cert/CERTTidyModule.cpp
  clang-tidy/cert/CMakeLists.txt
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cert-exp36-c.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.c
  test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.cpp

Index: test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.cpp
===
--- /dev/null
+++ test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.cpp
@@ -0,0 +1,7 @@
+// RUN: %check_clang_tidy %s cert-exp36-c %t
+
+void function(void) {
+  char c = 'x';
+  int *ip = reinterpret_cast(&c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c] 
+}
Index: test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.c
===
--- /dev/null
+++ test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.c
@@ -0,0 +1,122 @@
+// RUN: %check_clang_tidy %s cert-exp36-c %t -- -- -std=c11
+
+void function(void) {
+  char c = 'x';
+  int *ip = (int *)&c;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c] 
+}
+
+struct foo_header {
+  int len;
+};
+ 
+void function2(char *data, unsigned offset) {
+  struct foo_header *tmp;
+  struct foo_header header;
+ 
+  tmp = (struct foo_header *)(data + offset);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c] 
+}
+
+// Test from -Wcast-align check:
+
+// Simple casts.
+void test0(char *P) {
+  char *a  = (char*)  P;
+  short *b = (short*) P;
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+  int *c   = (int*)   P;
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+}
+
+// Casts from void* are a special case.
+void test1(void *P) {
+  char *a  = (char*)  P;
+  short *b = (short*) P;
+  int *c   = (int*)   P;
+
+  const volatile void *P2 = P;
+  char *d  = (char*)  P2;
+  short *e = (short*) P2;
+  int *f   = (int*)   P2;
+
+  const char *g  = (const char*)  P2;
+  const short *h = (const short*) P2;
+  const int *i   = (const int*)   P2;
+
+  const volatile char *j  = (const volatile char*)  P2;
+  const volatile short *k = (const volatile short*) P2;
+  const volatile int *l   = (const volatile int*)   P2;
+}
+
+// Aligned struct.
+struct __attribute__((aligned(16))) A {
+  char buffer[16];
+};
+void test2(char *P) {
+  struct A *a = (struct A*) P;
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+}
+
+// Incomplete type.
+void test3(char *P) {
+  struct B *b = (struct B*) P;
+}
+
+// Do not issue a warning. The aligned attribute changes the alignment of the
+// variables and fields.
+char __attribute__((aligned(4))) a[16];
+
+struct S0 {
+  char a[16];
+};
+
+struct S {
+  char __attribute__((aligned(4))) a[16];
+  struct S0 __attribute__((aligned(4))) s0;
+};
+
+// same FIXME as in line 120
+void test4() {
+  struct S s;
+  int *i = (int *)s.a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+  i = (int *)&s.s0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+  i = (int *)a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+}
+
+// No warnings.
+typedef int (*FnTy)(void);
+unsigned int func5(void);
+
+FnTy test5(void) {
+  return (FnTy)&func5;
+}
+
+
+// Something that does not trigger the check:
+
+struct w;
+
+void function3(struct w *v) {
+  int *ip = (int *)v;
+  struct w *u = (struct w *)ip;
+}
+
+struct x {
+   _Alignas(int) char c;
+};
+
+void function4(void) {
+  struct x c = {'x'};
+  int *ip = (int *)&c;
+}
+
+// FIXME: we do not want a warning for this
+void function5(void) {
+  _Alignas(int) char c = 'x';
+  int *ip = (int *)&c;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not cast pointers into more strictly aligned pointer types [cert-exp36-c]
+}
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -20,6 +20,7 @@
bugprone-integer-division
bugprone-suspicious-memset-usage
bugprone-undefined-memory-manipulation
+   cert-exp36-c
cert-dcl03-c (redirects to misc-sta

[PATCH] D33826: [clang-tidy] avoid pointer cast to more strict alignment check

2017-09-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D33826#866133, @NorenaLeonetti wrote:

> In https://reviews.llvm.org/D33826#861226, @aaron.ballman wrote:
>
> > Have you run this check over any large code bases to see what the quality 
> > of the diagnostics are?
>
>
> `-checks=-*,cert-exp36-c,modernize-unary-static-assert`
>
> the result:
>
> real52m6.886s
>  user298m8.824s
>  sys 7m29.292s
>
> `-checks=-*,modernize-unary-static-assert`
>
> the result:
>
> real52m5.305s
>  user302m38.508s
>  sys 8m53.008s


What was meant is, run the check over some large codebase (e.g. all of the LLVM 
itself), and upload the results somewhere.
Then analyze the results. Are there any obvious false-positives?
If yes, then minimize the testcase, add it into 
`test/clang-tidy/cert-avoid-pointer-cast-to-more-strict-alignment.cpp` and fix 
it's handling.
Are there clear bugs in the analyzed code?


Repository:
  rL LLVM

https://reviews.llvm.org/D33826



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


[PATCH] D37474: [PCH] Allow VFS to be used for tests that generate PCH files

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

Looks good, just a few minor style comments.




Comment at: include/clang/Frontend/PrecompiledPreamble.h:100
 
   /// PreambleBounds used to build the preamble
   PreambleBounds getBounds() const;

Not introduced by this change, but could you also add a full stop here for 
constistency?



Comment at: include/clang/Frontend/PrecompiledPreamble.h:103
 
+  /// The temporary file path at which the preamble PCH was placed
+  StringRef GetPCHPath() const { return PCHFile.getFilePath(); }

NIT: comment should end with a full stop.



Comment at: lib/Frontend/ASTUnit.cpp:1021
+  if (Buf)
+PCHFS->addFile(PCHFilename, 0, std::move(*Buf));
+  IntrusiveRefCntPtr

Maybe return original `VFS` if `PCHFilename` could not be read and not create 
any empty overlays?



Comment at: lib/Frontend/ASTUnit.cpp:1053
+  IntrusiveRefCntPtr RealFS = vfs::getRealFileSystem();
+  if (OverrideMainBuffer && VFS && RealFS && VFS != RealFS &&
+  !VFS->exists(Preamble->GetPCHPath())) {

The check `&& RealFS` is redundant and can be removed.


https://reviews.llvm.org/D37474



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


[PATCH] D33826: [clang-tidy] avoid pointer cast to more strict alignment check

2017-09-11 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

There is an exception to the general rule (EXP36-C-EX2), stating that the 
result of `malloc` and friends is allowed to be casted to stricter alignments, 
since the pointer is known to be of correct alignment.
Could you add a testcase for this case, i think there would currenlty be a 
false positive.

And is there a general way of knowing when the pointer is of correct alignment, 
or is it necessary to keep a list of functions like `malloc` that are just 
known? 
If yes, i think it would be nice if this list is configurable (maybe like in 
cppcoreguidelines-no-malloc, where that functionality could be refactored out).


Repository:
  rL LLVM

https://reviews.llvm.org/D33826



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


[PATCH] D37416: Use the VFS from the CompilerInvocation by default

2017-09-11 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev accepted this revision.
v.g.vassilev added a comment.
This revision is now accepted and ready to land.

This patch can rely on a post commit review if necessary.


https://reviews.llvm.org/D37416



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


[PATCH] D37677: [libc++] implement future synchronization using atomic_flag

2017-09-11 Thread Dennis Luxen via Phabricator via cfe-commits
dennis.luxen created this revision.

This task is listed in TODO.txt. The implementation swaps mutex against a 
spinlock based on atomic_flag. The spin lock itself is implemented as a nested 
class in a protected context of the associated state.


https://reviews.llvm.org/D37677

Files:
  include/future
  src/future.cpp

Index: src/future.cpp
===
--- src/future.cpp
+++ src/future.cpp
@@ -91,7 +91,7 @@
 void
 __assoc_sub_state::set_value()
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 #ifndef _LIBCPP_NO_EXCEPTIONS
 if (__has_value())
 throw future_error(make_error_code(future_errc::promise_already_satisfied));
@@ -103,7 +103,7 @@
 void
 __assoc_sub_state::set_value_at_thread_exit()
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 #ifndef _LIBCPP_NO_EXCEPTIONS
 if (__has_value())
 throw future_error(make_error_code(future_errc::promise_already_satisfied));
@@ -115,7 +115,7 @@
 void
 __assoc_sub_state::set_exception(exception_ptr __p)
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 #ifndef _LIBCPP_NO_EXCEPTIONS
 if (__has_value())
 throw future_error(make_error_code(future_errc::promise_already_satisfied));
@@ -128,7 +128,7 @@
 void
 __assoc_sub_state::set_exception_at_thread_exit(exception_ptr __p)
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 #ifndef _LIBCPP_NO_EXCEPTIONS
 if (__has_value())
 throw future_error(make_error_code(future_errc::promise_already_satisfied));
@@ -140,29 +140,29 @@
 void
 __assoc_sub_state::__make_ready()
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 __state_ |= ready;
 __cv_.notify_all();
 }
 
 void
 __assoc_sub_state::copy()
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 __sub_wait(__lk);
 if (__exception_ != nullptr)
 rethrow_exception(__exception_);
 }
 
 void
 __assoc_sub_state::wait()
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 __sub_wait(__lk);
 }
 
 void
-__assoc_sub_state::__sub_wait(unique_lock& __lk)
+__assoc_sub_state::__sub_wait(unique_lock<__spin_lock>& __lk)
 {
 if (!__is_ready())
 {
Index: include/future
===
--- include/future
+++ include/future
@@ -367,7 +367,8 @@
 #include 
 #include 
 #include 
-#include 
+#include 
+#include 
 #include 
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -533,12 +534,24 @@
 {
 protected:
 exception_ptr __exception_;
-mutable mutex __mut_;
-mutable condition_variable __cv_;
+
+mutable class __spin_lock
+{
+atomic_flag __locked_ = ATOMIC_FLAG_INIT ;
+public:
+void lock() {
+while (__locked_.test_and_set(memory_order_acquire)) { ; }
+}
+void unlock() {
+__locked_.clear(memory_order_release);
+}
+} __mut_;
+
+mutable condition_variable_any __cv_;
 unsigned __state_;
 
 virtual void __on_zero_shared() _NOEXCEPT;
-void __sub_wait(unique_lock& __lk);
+void __sub_wait(unique_lock<__spin_lock>& __lk);
 public:
 enum
 {
@@ -558,7 +571,7 @@
 _LIBCPP_INLINE_VISIBILITY
 void __set_future_attached()
 {
-lock_guard __lk(__mut_);
+lock_guard<__spin_lock> __lk(__mut_);
 __state_ |= __future_attached;
 }
 _LIBCPP_INLINE_VISIBILITY
@@ -596,7 +609,7 @@
 future_status
 __assoc_sub_state::wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const
 {
-unique_lock __lk(__mut_);
+unique_lock<__spin_lock> __lk(__mut_);
 if (__state_ & deferred)
 return future_status::deferred;
 while (!(__state_ & ready) && _Clock::now() < __abs_time)
@@ -663,7 +676,7 @@
 __assoc_state<_Rp>::set_value(_Arg& __arg)
 #endif
 {
-unique_lock __lk(this->__mut_);
+unique_lock<__spin_lock> __lk(this->__mut_);
 if (this->__has_value())
 __throw_future_error(future_errc::promise_already_satisfied);
 ::new(&__value_) _Rp(_VSTD::forward<_Arg>(__arg));
@@ -680,7 +693,7 @@
 __assoc_state<_Rp>::set_value_at_thread_exit(_Arg& __arg)
 #endif
 {
-unique_lock __lk(this->__mut_);
+unique_lock<__spin_lock> __lk(this->__mut_);
 if (this->__has_value())
 __throw_future_error(future_errc::promise_already_satisfied);
 ::new(&__value_) _Rp(_VSTD::forward<_Arg>(__arg));
@@ -692,7 +705,7 @@
 _Rp
 __assoc_state<_Rp>::move()
 {
-unique_lock __lk(this->__mut_);
+unique_lock<__spin_lock> __lk(this->__mut_);
 this->__sub_wait(__lk);
 if (this->__exception_ != nullptr)
 rethrow_exception(this->__exception_);
@@ -703,7 +716,7 @@
 typename add_lvalue_reference<_Rp>::type
 __assoc_state<_Rp>::copy()
 {
-unique_lock __lk(this->__mut_);
+unique_lock<__spin_lock> __lk(this->__mut_);
 this->__su

[PATCH] D37101: [clangd] Add support for snippet completions

2017-09-11 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

@rwols, do you have access to svn repo? If not, I can submit this change for 
you.


https://reviews.llvm.org/D37101



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


[PATCH] D33826: [clang-tidy] avoid pointer cast to more strict alignment check

2017-09-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D33826#866161, @JonasToth wrote:

> There is an exception to the general rule (EXP36-C-EX2), stating that the 
> result of `malloc` and friends is allowed to be casted to stricter 
> alignments, since the pointer is known to be of correct alignment.


Quote for the reference:

> EXP36-C-EX2: If a pointer is known to be correctly aligned to the target 
> type, then a cast to that type is permitted. There are several cases where a 
> pointer is known to be correctly aligned to the target type. The pointer 
> could point to an object declared with a suitable alignment specifier. It 
> could point to an object returned by aligned_alloc(), calloc(), malloc(), or 
> realloc(), as per the C standard, section 7.22.3, paragraph 1  [ISO/IEC 
> 9899:2011].

For plain `calloc(), malloc(), or realloc()`, i would guess it's related to 
`max_align_t` / `std::max_align_t` / `__STDCPP_DEFAULT_NEW_ALIGNMENT__`, which 
is generally just `16` bytes.

> Could you add a testcase for this case, i think there would currenlty be a 
> false positive.
> 
> And is there a general way of knowing when the pointer is of correct 
> alignment, or is it necessary to keep a list of functions like `malloc` that 
> are just known? 
>  If yes, i think it would be nice if this list is configurable (maybe like in 
> cppcoreguidelines-no-malloc, where that functionality could be refactored 
> out).




Repository:
  rL LLVM

https://reviews.llvm.org/D33826



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


[clang-tools-extra] r312901 - [clang-tidy] add more aliases for the hicpp module

2017-09-11 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Mon Sep 11 02:20:07 2017
New Revision: 312901

URL: http://llvm.org/viewvc/llvm-project?rev=312901&view=rev
Log:
[clang-tidy] add more aliases for the hicpp module

This patch will introduce even more aliases for the hicpp-module to already 
existing
checks and is a follow up for D30383 finishing the other sections.
It fixes a forgotten highlight in hicpp-braces-around-statements.rst, too.

Added:
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-deprecated-headers.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-move-const-arg.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-no-array-decay.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-no-malloc.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-static-assert.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-auto.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-emplace.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-noexcept.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-use-nullptr.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-vararg.rst
Modified:
clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/hicpp-braces-around-statements.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp?rev=312901&r1=312900&r2=312901&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/hicpp/HICPPTidyModule.cpp Mon Sep 11 
02:20:07 2017
@@ -10,16 +10,26 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "../cppcoreguidelines/NoMallocCheck.h"
+#include "../cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.h"
 #include "../cppcoreguidelines/ProTypeMemberInitCheck.h"
+#include "../cppcoreguidelines/ProTypeVarargCheck.h"
 #include "../cppcoreguidelines/SpecialMemberFunctionsCheck.h"
 #include "../google/DefaultArgumentsCheck.h"
 #include "../google/ExplicitConstructorCheck.h"
+#include "../misc/MoveConstantArgumentCheck.h"
 #include "../misc/NewDeleteOverloadsCheck.h"
 #include "../misc/NoexceptMoveConstructorCheck.h"
+#include "../misc/StaticAssertCheck.h"
 #include "../misc/UndelegatedConstructor.h"
 #include "../misc/UseAfterMoveCheck.h"
+#include "../modernize/DeprecatedHeadersCheck.h"
+#include "../modernize/UseAutoCheck.h"
+#include "../modernize/UseEmplaceCheck.h"
 #include "../modernize/UseEqualsDefaultCheck.h"
 #include "../modernize/UseEqualsDeleteCheck.h"
+#include "../modernize/UseNoexceptCheck.h"
+#include "../modernize/UseNullptrCheck.h"
 #include "../modernize/UseOverrideCheck.h"
 #include "../readability/BracesAroundStatementsCheck.h"
 #include "../readability/FunctionSizeCheck.h"
@@ -37,6 +47,8 @@ public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
 CheckFactories.registerCheck(
 "hicpp-braces-around-statements");
+CheckFactories.registerCheck(
+"hicpp-deprecated-headers");
 CheckFactories.registerCheck(
 "hicpp-exception-baseclass");
 CheckFactories.registerCheck(
@@ -51,22 +63,40 @@ public:
 "hicpp-invalid-access-moved");
 CheckFactories.registerCheck(
 "hicpp-member-init");
+CheckFactories.registerCheck(
+"hicpp-move-const-arg");
 CheckFactories.registerCheck(
 "hicpp-new-delete-operators");
 CheckFactories.registerCheck(
 "hicpp-noexcept-move");
+CheckFactories
+.registerCheck(
+"hicpp-no-array-decay");
 CheckFactories.registerCheck("hicpp-no-assembler");
+CheckFactories.registerCheck(
+"hicpp-no-malloc");
 CheckFactories
 .registerCheck(
 "hicpp-special-member-functions");
+CheckFactories.registerCheck(
+"hicpp-static-assert");
+CheckFactories.registerCheck("hicpp-use-auto");
 CheckFactories.registerCheck(
 "hicpp-undelegated-constructor");
+CheckFactories.registerCheck(
+"hicpp-use-emplace");
 CheckFactories.registerCheck(
 "hicpp-use-equals-default");
 CheckFactories.registerCheck(
 "hicpp-use-equals-delete");
+CheckFactories.registerCheck(
+"hicpp-use-noexcept");
+CheckFactories.registerCheck(
+"hicpp-use-nullptr");
 CheckFactories.registerCheck(
 "hicpp-use-override");
+CheckFactories.registerCheck(
+"hicpp-vararg");
   }
 };
 

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=312901&r1=312900&r2=3

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

2017-09-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 114549.
lebedev.ri added a comment.

@alexfh et al: friendly ping :)


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/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-complexity]
+  if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+  } else if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:10: note: +1, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:14: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+  } else {
+// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, nesting level increased to 1{{$}}
+  }
+}
+
+void unittest_b1_01() {
+// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_01' has cognitive complexity of 2 (threshold 0) [readability-function-cognitive-complexity]
+  int i = (1 ? 1 : 0) ? 1 : 0;
+// CHECK-NOTES: :[[@LINE-1]]:11: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:12: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+// FIXME: would be nice to point at the '?' symbol. does not seem to be possible
+}
+
+void unittest_b1_02(int x) {
+// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_02' has cognitive complexity of 5 (threshold 0) [readability-function-cognitive-complexity]
+  switch (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:11: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+  case -1:
+return;
+  case 1 ? 1 : 0:
+// CHECK-NOTES: :[[@LINE-1]]:8: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+return;
+  case (1 ? 2 : 0) ... (1 ? 3 : 0):
+// CHECK-NOTES: :[[@LINE-1]]:9: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:25: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+return;
+  default:
+break;
+  }
+}
+
+void unittest_b1_03(int x) {
+// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_03' has cognitive complexity of 4 (threshold 0) [readability-function-cognitive-complexity]
+  for (x = 1 ? 1 : 0; x < (1 ?

[PATCH] D36527: Implemented P0428R2 - Familiar template syntax for generic lambdas

2017-09-11 Thread Hamza Sood via Phabricator via cfe-commits
hamzasood updated this revision to Diff 114550.
hamzasood added a comment.

- Replaced an unneeded `STLExtras.h` include with ``.
- Assert that the lambda template scope has a parent before accessing it.
- Added an equals in a braced init as per the LLVM coding standards.

Thanks @Rakete


https://reviews.llvm.org/D36527

Files:
  include/clang/AST/DeclTemplate.h
  include/clang/AST/ExprCXX.h
  include/clang/AST/RecursiveASTVisitor.h
  include/clang/Basic/DiagnosticParseKinds.td
  include/clang/Sema/ScopeInfo.h
  include/clang/Sema/Sema.h
  lib/AST/DeclPrinter.cpp
  lib/AST/ExprCXX.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/TypePrinter.cpp
  lib/Parse/ParseExprCXX.cpp
  lib/Sema/Sema.cpp
  lib/Sema/SemaLambda.cpp
  lib/Sema/SemaType.cpp
  test/CXX/temp/temp.decls/temp.variadic/p4.cpp
  test/PCH/cxx11-lambdas.mm
  test/PCH/cxx1y-lambdas.mm
  test/PCH/cxx2a-template-lambdas.cpp
  test/Parser/cxx2a-template-lambdas.cpp
  test/SemaCXX/cxx2a-template-lambdas.cpp
  unittests/AST/StmtPrinterTest.cpp
  unittests/Tooling/RecursiveASTVisitorTest.cpp
  unittests/Tooling/TestVisitor.h
  www/cxx_status.html

Index: www/cxx_status.html
===
--- www/cxx_status.html
+++ www/cxx_status.html
@@ -823,7 +823,7 @@
 
   template-parameter-list for generic lambdas
   http://wg21.link/p0428r2";>P0428R2
-  No
+  SVN
 
 
   Initializer list constructors in class template argument deduction
Index: unittests/Tooling/TestVisitor.h
===
--- unittests/Tooling/TestVisitor.h
+++ unittests/Tooling/TestVisitor.h
@@ -44,6 +44,8 @@
 Lang_CXX98,
 Lang_CXX11,
 Lang_CXX14,
+Lang_CXX17,
+Lang_CXX2a,
 Lang_OBJC,
 Lang_OBJCXX11,
 Lang_CXX = Lang_CXX98
@@ -60,6 +62,8 @@
   case Lang_CXX98: Args.push_back("-std=c++98"); break;
   case Lang_CXX11: Args.push_back("-std=c++11"); break;
   case Lang_CXX14: Args.push_back("-std=c++14"); break;
+  case Lang_CXX17: Args.push_back("-std=c++17"); break;
+  case Lang_CXX2a: Args.push_back("-std=c++2a"); break;
   case Lang_OBJC:
 Args.push_back("-ObjC");
 Args.push_back("-fobjc-runtime=macosx-10.12.0");
Index: unittests/Tooling/RecursiveASTVisitorTest.cpp
===
--- unittests/Tooling/RecursiveASTVisitorTest.cpp
+++ unittests/Tooling/RecursiveASTVisitorTest.cpp
@@ -79,6 +79,41 @@
   LambdaDefaultCaptureVisitor::Lang_CXX11));
 }
 
+// Matches (optional) explicit template parameters.
+class LambdaTemplateParametersVisitor
+  : public ExpectedLocationVisitor {
+public:
+  bool shouldVisitImplicitCode() const { return false; }
+
+  bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
+EXPECT_FALSE(D->isImplicit());
+Match(D->getName(), D->getLocStart());
+return true;
+  }
+  bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
+EXPECT_FALSE(D->isImplicit());
+Match(D->getName(), D->getLocStart());
+return true;
+  }
+  bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
+EXPECT_FALSE(D->isImplicit());
+Match(D->getName(), D->getLocStart());
+return true;
+  }
+};
+
+TEST(RecursiveASTVisitor, VisitsLambdaExplicitTemplateParameters) {
+  LambdaTemplateParametersVisitor Visitor;
+  Visitor.ExpectMatch("T",  2, 15);
+  Visitor.ExpectMatch("I",  2, 24);
+  Visitor.ExpectMatch("TT", 2, 31);
+  EXPECT_TRUE(Visitor.runOver(
+  "void f() { \n"
+  "  auto l = [] class TT>(auto p) { }; \n"
+  "}",
+  LambdaTemplateParametersVisitor::Lang_CXX2a));
+}
+
 // Checks for lambda classes that are not marked as implicitly-generated.
 // (There should be none.)
 class ClassVisitor : public ExpectedLocationVisitor {
Index: unittests/AST/StmtPrinterTest.cpp
===
--- unittests/AST/StmtPrinterTest.cpp
+++ unittests/AST/StmtPrinterTest.cpp
@@ -67,9 +67,8 @@
 
 template 
 ::testing::AssertionResult
-PrintedStmtMatches(StringRef Code, const std::vector &Args,
-   const T &NodeMatch, StringRef ExpectedPrinted) {
-
+PrintedStmtMatchesInternal(StringRef Code, const std::vector &Args,
+   const T &NodeMatch, StringRef ExpectedPrinted) {
   PrintMatch Printer;
   MatchFinder Finder;
   Finder.addMatcher(NodeMatch, &Printer);
@@ -97,65 +96,52 @@
   return ::testing::AssertionSuccess();
 }
 
+enum class StdVer { CXX98, CXX11, CXX14, CXX17, CXX2a };
+
+DeclarationMatcher FunctionBodyMatcher(StringRef ContainingFunction) {
+  return functionDecl(hasName(ContainingFunction),
+  has(compoundStmt(has(stmt().bind("id");
+}
+
+template 
 ::testing::AssertionResult
-PrintedStmtCXX98Matches(StringRef Code, const StatementMatcher &NodeMatch,
-StringRef ExpectedPrinted) {
-  std::vector Args;
-  Args.push_back("-std

r312904 - [clang-format] Fixed one-line if statement

2017-09-11 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Sep 11 03:12:16 2017
New Revision: 312904

URL: http://llvm.org/viewvc/llvm-project?rev=312904&view=rev
Log:
[clang-format] Fixed one-line if statement

Summary:
**Short overview:**

Fixed bug: https://bugs.llvm.org/show_bug.cgi?id=34001
Clang-format bug resulting in a strange behavior of control statements short 
blocks. Different flags combinations do not guarantee expected result. Turned 
on option AllowShortBlocksOnASingleLine does not work as intended.

**Description of the problem:**

Cpp source file UnwrappedLineFormatter does not handle 
AllowShortBlocksOnASingleLine flag as it should. Putting a single-line control 
statement without any braces, clang-format works as expected (depending on 
AllowShortIfStatementOnASingleLine or AllowShortLoopsOnASingleLine value). 
Putting a single-line control statement in braces, we can observe strange and 
incorrect behavior.
Our short block is intercepted by tryFitMultipleLinesInOne function. The 
function returns a number of lines to be merged. Unfortunately, our control 
statement block is not covered properly. There are several if-return 
statements, but none of them handles our block. A block is identified by the 
line first token and by left and right braces. A function block works as 
expected, there is such an if-return statement doing proper job. A control 
statement block, from the other hand, falls into strange conditional construct, 
which depends on BraceWrapping.AfterFunction flag (with condition that the 
line’s last token is left brace, what is possible in our case) or goes even 
further. That should definitely not happen.

**Description of the patch:**

By adding three different if statements, we guarantee that our short control 
statement block, however it looks like (different brace wrapping flags may be 
turned on), is handled properly and does not fall into wrong conditional 
construct. Depending on appropriate options we return either 0 (when something 
disturbs our merging attempt) or let another function (tryMergeSimpleBlock) 
take the responsibility of returned result (number of merged lines). 
Nevertheless, one more correction is required in mentioned tryMergeSimpleBlock 
function. The function, previously, returned either 0 or 2. The problem was 
that this did not handle the case when our block had the left brace in a 
separate line, not the header one. After change, after adding condition, we 
return the result compatible with block’s structure. In case of left brace in 
the header’s line we do everything as before the patch. In case of left brace 
in a separate line we do the job similar to the one we do in case of a 
“non-header left brace” function short block. To be precise, we try to merge 
the block ignoring the header line. Then, if success, we increment our returned 
result.

**After fix:**

**CONFIG:**
```
AllowShortBlocksOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
BreakBeforeBraces: Custom
BraceWrapping: {
AfterClass: true, AfterControlStatement: true, AfterEnum: true, AfterFunction: 
true, AfterNamespace: false, AfterStruct: true, AfterUnion: true, BeforeCatch: 
true, BeforeElse: true
}
```
**BEFORE:**
```
if (statement) doSomething();
if (statement) { doSomething(); }
if (statement) {
doSomething();
}
if (statement)
{
doSomething();
}
if (statement)
doSomething();
if (statement) {
doSomething1();
doSomething2();
}
```
**AFTER:**
```
if (statement) doSomething();
if (statement) { doSomething(); }
if (statement) { doSomething(); }
if (statement) { doSomething(); }
if (statement) doSomething();
if (statement)
{
  doSomething1();
  doSomething2();
}
```

Contributed by @PriMee!

Reviewers: krasimir, djasper

Reviewed By: krasimir

Subscribers: cfe-commits, klimek

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

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

Modified: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp?rev=312904&r1=312903&r2=312904&view=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp Mon Sep 11 03:12:16 2017
@@ -279,15 +279,43 @@ private:
   }
 }
 
+// Try to merge a function block with left brace unwrapped
 if (TheLine->Last->is(TT_FunctionLBrace) &&
 TheLine->First != TheLine->Last) {
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 }
+// Try to merge a control statement block with left brace unwrapped
+if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
+  return Style.AllowShortBlocksOnASingleLine
+ ? tryMergeSimpleBlock(I, E, Limit)
+ : 0;
+}
+

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

2017-09-11 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312904: [clang-format] Fixed one-line if statement (authored 
by krasimir).

Changed prior to commit:
  https://reviews.llvm.org/D37140?vs=113979&id=114558#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37140

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

Index: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
===
--- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
+++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
@@ -279,15 +279,43 @@
   }
 }
 
+// Try to merge a function block with left brace unwrapped
 if (TheLine->Last->is(TT_FunctionLBrace) &&
 TheLine->First != TheLine->Last) {
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 }
+// Try to merge a control statement block with left brace unwrapped
+if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
+  return Style.AllowShortBlocksOnASingleLine
+ ? tryMergeSimpleBlock(I, E, Limit)
+ : 0;
+}
+// Try to merge a control statement block with left brace wrapped
+if (I[1]->First->is(tok::l_brace) &&
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
+  return Style.BraceWrapping.AfterControlStatement
+ ? tryMergeSimpleBlock(I, E, Limit)
+ : 0;
+}
+// Try to merge either empty or one-line block if is precedeed by control
+// statement token
+if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
+I != AnnotatedLines.begin() &&
+I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
+  return Style.AllowShortBlocksOnASingleLine
+ ? tryMergeSimpleBlock(I - 1, E, Limit)
+ : 0;
+}
+// Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
-  return !Style.BraceWrapping.AfterFunction
+  return !Style.BraceWrapping.AfterFunction ||
+ (I[1]->First->is(tok::r_brace) &&
+  !Style.BraceWrapping.SplitEmptyRecord)
  ? tryMergeSimpleBlock(I, E, Limit)
  : 0;
 }
+// Try to merge a function block with left brace wrapped
 if (I[1]->First->is(TT_FunctionLBrace) &&
 Style.BraceWrapping.AfterFunction) {
   if (I[1]->Last->is(TT_LineComment))
@@ -437,18 +465,35 @@
 // Check that the current line allows merging. This depends on whether we
 // are in a control flow statements as well as several style flags.
 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
-(Line.First->Next && Line.First->Next->is(tok::kw_else)))
+(Line.First->Next && Line.First->Next->is(tok::kw_else)) ||
+(I != AnnotatedLines.begin() && I[-1]->Last->is(tok::kw_else)))
   return 0;
 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
 tok::kw___try, tok::kw_catch, tok::kw___finally,
 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
   if (!Style.AllowShortBlocksOnASingleLine)
 return 0;
+  // Don't merge when we can't except the case when
+  // the control statement block is empty
+  if (!Style.AllowShortIfStatementsOnASingleLine &&
+  Line.startsWith(tok::kw_if) &&
+  !Style.BraceWrapping.AfterControlStatement &&
+  !I[1]->First->is(tok::r_brace))
+return 0;
   if (!Style.AllowShortIfStatementsOnASingleLine &&
-  Line.startsWith(tok::kw_if))
+  Line.startsWith(tok::kw_if) &&
+  Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
+  !I[2]->First->is(tok::r_brace))
 return 0;
   if (!Style.AllowShortLoopsOnASingleLine &&
-  Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
+  Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
+  !Style.BraceWrapping.AfterControlStatement &&
+  !I[1]->First->is(tok::r_brace))
+return 0;
+  if (!Style.AllowShortLoopsOnASingleLine &&
+  Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
+  Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
+  !I[2]->First->is(tok::r_brace))
 return 0;
   // FIXME: Consider an option to allow short exception handling clauses on
   // a single line.
@@ -460,52 +505,73 @@
 return 0;
 }
 
-FormatToken *Tok = I[1]->First;
-if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
-(Tok->getNextNonComment() == nullptr ||
- Tok->getNextNonComment()->is(tok::semi))) {
-  // We merge empty blocks even if the line exceeds the column

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

2017-09-11 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.

Thanks, 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] D37642: [pp-trace] Update skipped source ranges in tests

2017-09-11 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.

LG


https://reviews.llvm.org/D37642



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


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

2017-09-11 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee added a comment.

ping


https://reviews.llvm.org/D37260



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


[PATCH] D36150: [clangd] LSP extension to switch between source/header file

2017-09-11 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov requested changes to this revision.
ilya-biryukov added a comment.
This revision now requires changes to proceed.

Overall the code looks good, thanks for the clean-ups.

Only a few minor style comments and a major one about returning value when no 
file is matching.
Please add tests for the new feature.




Comment at: clangd/ClangdLSPServer.cpp:227
+TextDocumentIdentifier Params, StringRef ID, JSONOutput &Out) {
+
+  llvm::Optional Result =

Maybe remove this empty line?



Comment at: clangd/ClangdLSPServer.cpp:231
+  URI ResultUri;
+  if (Result != llvm::None)
+ResultUri = URI::fromFile(*Result);

Replace with more concise form: `if (Result)`



Comment at: clangd/ClangdLSPServer.cpp:234
+  else
+ResultUri = URI::fromFile("");
+

Running `unparse` on an instance created via `URI::fromFile("")`  will result 
in `"file:///"`. 

Have you considered returning a list of paths as a result from 
`switchHeaderSource`?
That way you could capture the "no file matched" case with an empty list.
Later when an implementation will look into index, that would allow to return 
multiple source files for a header file, which also  happens in some C++ 
projects.

Returning an empty string is also an option we could start with.



Comment at: clangd/ClangdServer.cpp:22
 
+using namespace llvm;
 using namespace clang;

Do we really need this `using namespace` or it can be deleted?



Comment at: clangd/ClangdServer.cpp:345
+if (FS->exists(NewPath)) {
+  return NewPath.str().str();
+}

Code style: we don't use braces around small single-statement control structures




Comment at: clangd/ClangdServer.h:185
 
+  /// Helper function that returns a path to the corresponding source file 
when given a header file and vice versa.
+  llvm::Optional switchSourceHeader(PathRef Path);

Could you please `clang-format` this file too?
Comment line length is clearly over the limit.


https://reviews.llvm.org/D36150



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


Re: r312633 - [AST] Traverse CXXOperatorCallExpr in LexicallyOrderedRecursiveASTVisitor

2017-09-11 Thread Alex L via cfe-commits
It's a good idea to merge the two. I'll work on moving the ObjC traversal
change when I get the time.

Thanks for the quick patches Johannes!

On 9 September 2017 at 12:03, Johannes Altmanninger 
wrote:

> Richard Smith  writes:
>
> > I am extremely uncomfortable about the direction this patch series is
> going.
> >
> > We have had two different RecursiveASTVisitors before
> (RecursiveASTVisitor
> > and DataRecursiveASTVisitor), and it was a maintenance nightmare:
> > frequently changes would be made to one of them and missed in the other
> > one, resulting in hard to track down bugs, as well as redundant
> development
> > effort making changes to both.
> >
> > Back when this was simply deriving from RecursiveASTVisitor and not
> > changing much, LexicallyOrderedRecursiveASTVisitor seemed like it
> wouldn't
> > suffer from the same problem, but it's becoming increasingly clear that
> > that simply isn't going to be the case long-term. And worse, there seems
> to
> > be absolutely no purpose in having two different visitors here -- the
> > existing users of RecursiveASTVisitor generally don't care about
> visitation
> > order.
> >
> > Also, we can play the "what if two people did this" game -- adding RAV
> > functionality in derived classes doesn't compose well. (If post-order
> > traversal were a derived class, you couldn't request a lexically-ordered
> > post-order traversal, and so on.)
> >
> > Therefore, I'd like to suggest that you stop making changes to
> > LexicallyOrderedRecursiveASTVisitor and instead start to fold its
> > functionality back into RecursiveASTVisitor, as follows:
> >
> >  * in cases where there is no reason for RAV to visit in non-lexical
> order,
> > change it to visit in lexical order
> >  * if there are any cases where there *is* a reason for non-lexical
> > visitation, add a bool function to it so the derived class can request
> > lexical / non-lexical order (like the existing shouldTraversePostOrder /
> > shouldVisitImplicitCode / ... functions).
>
> Ok, makes sense.
>
> +Alex so you are aware.
>
> I have created two revisions to move my changes to RecursiveASTVisitor,
> this should not break anything. I left the tests in
> LexicallyOrderedRecursiveASTVisitorTest for now because it saves some
> code duplication, but let's see, if we merge all the changes into
> RecursiveASTVisitor, then the tests will naturally follow.
>
> https://reviews.llvm.org/D37662
> https://reviews.llvm.org/D37663
>
> >
> > On 6 September 2017 at 06:12, Johannes Altmanninger via cfe-commits <
> > cfe-commits@lists.llvm.org> wrote:
> >
> >> Author: krobelus
> >> Date: Wed Sep  6 06:12:11 2017
> >> New Revision: 312633
> >>
> >> URL: http://llvm.org/viewvc/llvm-project?rev=312633&view=rev
> >> Log:
> >> [AST] Traverse CXXOperatorCallExpr in LexicallyOrderedRecursiveASTVi
> sitor
> >>
> >> Summary:
> >> This affects overloaded operators, which are represented by a
> >> CXXOperatorCallExpr whose first child is always a DeclRefExpr referring
> to
> >> the
> >> operator. For infix, postfix and call operators we want the first
> argument
> >> to be traversed before the operator.
> >>
> >> Reviewers: arphaman
> >>
> >> Subscribers: klimek, cfe-commits
> >>
> >> Differential Revision: https://reviews.llvm.org/D37200
> >>
> >> Modified:
> >> cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
> >> cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
> >> cfe/trunk/unittests/Tooling/LexicallyOrderedRecursiveASTVi
> >> sitorTest.cpp
> >>
> >> Modified: cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVi
> >> sitor.h
> >> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/
> >> LexicallyOrderedRecursiveASTVisitor.h?rev=312633&r1=312632&
> >> r2=312633&view=diff
> >> 
> >> ==
> >> --- cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
> >> (original)
> >> +++ cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
> Wed
> >> Sep  6 06:12:11 2017
> >> @@ -113,6 +113,33 @@ public:
> >>
> >>bool shouldTraverseTemplateArgumentsBeforeDecl() const { return
> true; }
> >>
> >> +  Stmt::child_range getStmtChildren(Stmt *S) { return S->children(); }
> >> +
> >> +  SmallVector getStmtChildren(CXXOperatorCallExpr *CE) {
> >> +SmallVector Children(CE->children());
> >> +bool Swap;
> >> +// Switch the operator and the first operand for all infix and
> postfix
> >> +// operations.
> >> +switch (CE->getOperator()) {
> >> +case OO_Arrow:
> >> +case OO_Call:
> >> +case OO_Subscript:
> >> +  Swap = true;
> >> +  break;
> >> +case OO_PlusPlus:
> >> +case OO_MinusMinus:
> >> +  // These are postfix unless there is exactly one argument.
> >> +  Swap = Children.size() != 2;
> >> +  break;
> >> +default:
> >> +  Swap = CE->isInfixBinaryOp();
> >> +  break;
> >> +}
> >> +if (Swap && Children.size() > 1)
> >> +   

[PATCH] D37572: [clang-tidy] SuspiciousEnumUsageCheck bugfix

2017-09-11 Thread Peter Szecsi via Phabricator via cfe-commits
szepet updated this revision to Diff 114567.
szepet marked 3 inline comments as done.
szepet added a comment.

Updates based on the comments. Thanks for the reduced test case and the fast 
review!

Not sure if in these cases am I allowed to commit (since it was accepted) or 
since it was accepted a lot of comments ago I should wait for another response?


https://reviews.llvm.org/D37572

Files:
  clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
  test/clang-tidy/misc-suspicious-enum-usage.cpp


Index: test/clang-tidy/misc-suspicious-enum-usage.cpp
===
--- test/clang-tidy/misc-suspicious-enum-usage.cpp
+++ test/clang-tidy/misc-suspicious-enum-usage.cpp
@@ -54,7 +54,7 @@
   int emptytest = EmptyVal | B;
   if (bestDay() | A)
 return 1;
-  // CHECK-MESSAGES: :[[@LINE-2]]:17: warning: enum values are from different 
enum types 
+  // CHECK-MESSAGES: :[[@LINE-2]]:17: warning: enum values are from different 
enum types
   if (I | Y)
 return 1;
   // CHECK-MESSAGES: :[[@LINE-2]]:9: warning: enum values are from different 
enum types
@@ -88,3 +88,9 @@
 return 1;
   return 42;
 }
+
+namespace PR34400 {
+enum { E1 = 0 };
+enum { E2 = -1 };
+enum { l = E1 | E2 };
+}
Index: clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
===
--- clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
+++ clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
@@ -42,7 +42,8 @@
 const auto MinMaxVal = std::minmax_element(
 EnumDec->enumerator_begin(), EnumDec->enumerator_end(),
 [](const EnumConstantDecl *E1, const EnumConstantDecl *E2) {
-  return E1->getInitVal() < E2->getInitVal();
+  return llvm::APSInt::compareValues(E1->getInitVal(),
+ E2->getInitVal()) < 0;
 });
 MinVal = MinMaxVal.first->getInitVal();
 MaxVal = MinMaxVal.second->getInitVal();
@@ -57,7 +58,8 @@
 static bool hasDisjointValueRange(const EnumDecl *Enum1,
   const EnumDecl *Enum2) {
   ValueRange Range1(Enum1), Range2(Enum2);
-  return (Range1.MaxVal < Range2.MinVal) || (Range2.MaxVal < Range1.MinVal);
+  return llvm::APSInt::compareValues(Range1.MaxVal, Range2.MinVal) < 0 ||
+ llvm::APSInt::compareValues(Range2.MaxVal, Range1.MinVal) < 0;
 }
 
 static bool isNonPowerOf2NorNullLiteral(const EnumConstantDecl *EnumConst) {


Index: test/clang-tidy/misc-suspicious-enum-usage.cpp
===
--- test/clang-tidy/misc-suspicious-enum-usage.cpp
+++ test/clang-tidy/misc-suspicious-enum-usage.cpp
@@ -54,7 +54,7 @@
   int emptytest = EmptyVal | B;
   if (bestDay() | A)
 return 1;
-  // CHECK-MESSAGES: :[[@LINE-2]]:17: warning: enum values are from different enum types 
+  // CHECK-MESSAGES: :[[@LINE-2]]:17: warning: enum values are from different enum types
   if (I | Y)
 return 1;
   // CHECK-MESSAGES: :[[@LINE-2]]:9: warning: enum values are from different enum types
@@ -88,3 +88,9 @@
 return 1;
   return 42;
 }
+
+namespace PR34400 {
+enum { E1 = 0 };
+enum { E2 = -1 };
+enum { l = E1 | E2 };
+}
Index: clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
===
--- clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
+++ clang-tidy/misc/SuspiciousEnumUsageCheck.cpp
@@ -42,7 +42,8 @@
 const auto MinMaxVal = std::minmax_element(
 EnumDec->enumerator_begin(), EnumDec->enumerator_end(),
 [](const EnumConstantDecl *E1, const EnumConstantDecl *E2) {
-  return E1->getInitVal() < E2->getInitVal();
+  return llvm::APSInt::compareValues(E1->getInitVal(),
+ E2->getInitVal()) < 0;
 });
 MinVal = MinMaxVal.first->getInitVal();
 MaxVal = MinMaxVal.second->getInitVal();
@@ -57,7 +58,8 @@
 static bool hasDisjointValueRange(const EnumDecl *Enum1,
   const EnumDecl *Enum2) {
   ValueRange Range1(Enum1), Range2(Enum2);
-  return (Range1.MaxVal < Range2.MinVal) || (Range2.MaxVal < Range1.MinVal);
+  return llvm::APSInt::compareValues(Range1.MaxVal, Range2.MinVal) < 0 ||
+ llvm::APSInt::compareValues(Range2.MaxVal, Range1.MinVal) < 0;
 }
 
 static bool isNonPowerOf2NorNullLiteral(const EnumConstantDecl *EnumConst) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37448: Fix cast assertion on MS inline assembly with vector spills (PR34021)

2017-09-11 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon updated this revision to Diff 114569.
RKSimon added a comment.

Added checks to test case


Repository:
  rL LLVM

https://reviews.llvm.org/D37448

Files:
  lib/CodeGen/CGStmt.cpp
  test/CodeGen/pr34021.c


Index: test/CodeGen/pr34021.c
===
--- test/CodeGen/pr34021.c
+++ test/CodeGen/pr34021.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fms-extensions %s -triple=i686-unknown-unknown -emit-llvm 
-o - | FileCheck %s --check-prefix=X86
+// RUN: %clang_cc1 -fms-extensions %s -triple=x86_64-unknown-unknown 
-emit-llvm -o - | FileCheck %s --check-prefix=X64
+// REQUIRES: asserts
+
+typedef int v4si __attribute__ ((vector_size (16)));
+v4si rep() {
+// X86-LABEL: define <4 x i32> @rep
+// X86:  %retval = alloca <4 x i32>, align 16
+// X86-NEXT: %res = alloca <4 x i32>, align 16
+// X86-NEXT: %0 = bitcast <4 x i32>* %retval to i128*
+// X86-NEXT: %1 = call i64 asm sideeffect inteldialect "", 
"=A,~{dirflag},~{fpsr},~{flags}"()
+// X86-NEXT: %2 = zext i64 %1 to i128
+// X86-NEXT: store i128 %2, i128* %0, align 16
+// X86-NEXT: %3 = load <4 x i32>, <4 x i32>* %res, align 16
+// X86-NEXT: ret <4 x i32> %3
+//
+// X64-LABEL: define <4 x i32> @rep
+// X64:  %res = alloca <4 x i32>, align 16
+// X64-NEXT: call void asm sideeffect inteldialect "", 
"~{dirflag},~{fpsr},~{flags}"()
+// X64-NEXT: %0 = load <4 x i32>, <4 x i32>* %res, align 16
+// X64-NEXT: ret <4 x i32> %0
+  v4si res;
+  __asm {}
+  return res;
+}
Index: lib/CodeGen/CGStmt.cpp
===
--- lib/CodeGen/CGStmt.cpp
+++ lib/CodeGen/CGStmt.cpp
@@ -2194,7 +2194,7 @@
llvm::IntegerType::get(getLLVMContext(), 
(unsigned)TmpSize));
 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
   } else if (TruncTy->isIntegerTy()) {
-Tmp = Builder.CreateTrunc(Tmp, TruncTy);
+Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
   } else if (TruncTy->isVectorTy()) {
 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
   }


Index: test/CodeGen/pr34021.c
===
--- test/CodeGen/pr34021.c
+++ test/CodeGen/pr34021.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fms-extensions %s -triple=i686-unknown-unknown -emit-llvm -o - | FileCheck %s --check-prefix=X86
+// RUN: %clang_cc1 -fms-extensions %s -triple=x86_64-unknown-unknown -emit-llvm -o - | FileCheck %s --check-prefix=X64
+// REQUIRES: asserts
+
+typedef int v4si __attribute__ ((vector_size (16)));
+v4si rep() {
+// X86-LABEL: define <4 x i32> @rep
+// X86:  %retval = alloca <4 x i32>, align 16
+// X86-NEXT: %res = alloca <4 x i32>, align 16
+// X86-NEXT: %0 = bitcast <4 x i32>* %retval to i128*
+// X86-NEXT: %1 = call i64 asm sideeffect inteldialect "", "=A,~{dirflag},~{fpsr},~{flags}"()
+// X86-NEXT: %2 = zext i64 %1 to i128
+// X86-NEXT: store i128 %2, i128* %0, align 16
+// X86-NEXT: %3 = load <4 x i32>, <4 x i32>* %res, align 16
+// X86-NEXT: ret <4 x i32> %3
+//
+// X64-LABEL: define <4 x i32> @rep
+// X64:  %res = alloca <4 x i32>, align 16
+// X64-NEXT: call void asm sideeffect inteldialect "", "~{dirflag},~{fpsr},~{flags}"()
+// X64-NEXT: %0 = load <4 x i32>, <4 x i32>* %res, align 16
+// X64-NEXT: ret <4 x i32> %0
+  v4si res;
+  __asm {}
+  return res;
+}
Index: lib/CodeGen/CGStmt.cpp
===
--- lib/CodeGen/CGStmt.cpp
+++ lib/CodeGen/CGStmt.cpp
@@ -2194,7 +2194,7 @@
llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
   } else if (TruncTy->isIntegerTy()) {
-Tmp = Builder.CreateTrunc(Tmp, TruncTy);
+Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
   } else if (TruncTy->isVectorTy()) {
 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic updated this revision to Diff 114573.

https://reviews.llvm.org/D34878

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Driver/CC1Options.td
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Arch/ARM.cpp
  lib/Driver/ToolChains/Arch/ARM.h
  test/Driver/clang-translation.c

Index: test/Driver/clang-translation.c
===
--- test/Driver/clang-translation.c
+++ test/Driver/clang-translation.c
@@ -87,6 +87,18 @@
 // ARMV5E: "-cc1"
 // ARMV5E: "-target-cpu" "arm1022e"
 
+// RUN: %clang -target arm-linux -mtp=cp15 -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER-HARD %s
+// ARMv7_THREAD_POINTER-HARD: "-target-feature" "+read-tp-hard"
+
+// RUN: %clang -target arm-linux -mtp=soft -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_SOFT %s
+// ARMv7_THREAD_POINTER_SOFT-NOT: "-target-feature" "+read-tp-hard"
+
+// RUN: %clang -target arm-linux -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_NON %s
+// ARMv7_THREAD_POINTER_NON-NOT: "-target-feature" "+read-tp-hard"
+
 // RUN: %clang -target powerpc64-unknown-linux-gnu \
 // RUN: -### -S %s -mcpu=G5 2>&1 | FileCheck -check-prefix=PPCG5 %s
 // PPCG5: clang
Index: lib/Driver/ToolChains/Arch/ARM.h
===
--- lib/Driver/ToolChains/Arch/ARM.h
+++ lib/Driver/ToolChains/Arch/ARM.h
@@ -32,14 +32,21 @@
 void appendEBLinkFlags(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs,
const llvm::Triple &Triple);
+enum class ReadTPMode {
+  Invalid,
+  Soft,
+  Cp15,
+};
+
 enum class FloatABI {
   Invalid,
   Soft,
   SoftFP,
   Hard,
 };
 
 FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args);
+ReadTPMode getReadTPMode(const ToolChain &TC, const llvm::opt::ArgList &Args);
 
 bool useAAPCSForMachO(const llvm::Triple &T);
 void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args,
Index: lib/Driver/ToolChains/Arch/ARM.cpp
===
--- lib/Driver/ToolChains/Arch/ARM.cpp
+++ lib/Driver/ToolChains/Arch/ARM.cpp
@@ -131,6 +131,26 @@
  T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
 }
 
+// Select mode for reading thread pointer (-mtp=soft/cp15).
+arm::ReadTPMode arm::getReadTPMode(const ToolChain &TC, const ArgList &Args) {
+  const Driver &D = TC.getDriver();
+  arm::ReadTPMode ThreadPointer = ReadTPMode::Invalid;
+  if (Arg *A =
+  Args.getLastArg(options::OPT_mtp_mode_EQ)) {
+ThreadPointer = llvm::StringSwitch(A->getValue())
+.Case("cp15", ReadTPMode::Cp15)
+.Case("soft", ReadTPMode::Soft)
+.Default(ReadTPMode::Invalid);
+if (ThreadPointer != ReadTPMode::Invalid)
+  return ThreadPointer;
+if (StringRef(A->getValue()).empty())
+  D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
+else
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+  }
+  return ReadTPMode::Soft;
+}
+
 // Select the float ABI as determined by -msoft-float, -mhard-float, and
 // -mfloat-abi=.
 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
@@ -262,6 +282,7 @@
   bool KernelOrKext =
   Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
+  arm::ReadTPMode ThreadPointer = arm::getReadTPMode(TC, Args);
   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
 
@@ -303,6 +324,10 @@
 }
   }
 
+
+  if (ThreadPointer == arm::ReadTPMode::Cp15)
+Features.push_back("+read-tp-hard");
+
   // Check -march. ClangAs gives preference to -Wa,-march=.
   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
   StringRef ArchName;
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1689,6 +1689,8 @@
   HelpText<"Disallow generation of data access to code sections (ARM only)">;
 def mno_execute_only : Flag<["-"], "mno-execute-only">, Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
+def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, Values<"soft, cp15">,
+  HelpText<"Read thread pointer from coprocessor register (ARM only)">;
 def mpure_code : Flag<["-"], "mpure-code">, Alias; // Alias for GCC compatibility
 def mno_pure_code : Flag<["-"], "mno-pure-code">, Alias;
 def mtvos_version_min_EQ : Joined<["-"], "mtvos-version-min=">, Group;
Index: include/clang/Driver/CC1Options.td
===
--- include/clang/Driver/CC1Options.td
+++ include/clang/Driver/CC1Options.td
@@ -257,6 +257,8 @@
"precision">;
 de

[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic added a comment.

Comments addressed.


https://reviews.llvm.org/D34878



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


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls added inline comments.



Comment at: lib/Driver/ToolChains/Arch/ARM.cpp:137
+  const Driver &D = TC.getDriver();
+  arm::ReadTPMode ThreadPointer = ReadTPMode::Invalid;
+  if (Arg *A =

With the new version of the code, there's no need to have a ThreadPointer 
variable declared here; it can be declared inside the if statement below 
instead.



Comment at: lib/Driver/ToolChains/Arch/ARM.cpp:149-150
+else
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+  }
+  return ReadTPMode::Soft;

a return ReadTPMode::Invalid is missing here.


https://reviews.llvm.org/D34878



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


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic added inline comments.



Comment at: lib/Driver/ToolChains/Arch/ARM.cpp:149-150
+else
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+  }
+  return ReadTPMode::Soft;

kristof.beyls wrote:
> a return ReadTPMode::Invalid is missing here.
Yes, my mistake, I will fix that.


https://reviews.llvm.org/D34878



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


[PATCH] D37681: [refactor] Simplify the interface and remove some template magic

2017-09-11 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
Herald added a subscriber: mgorny.

This patch tries to simplify the interface for the refactoring action rules and 
refactoring requirements. It merges the selection constraints and selection 
requirements into one class. The refactoring actions rules must now be 
implemented using subclassing instead of raw function / lambda pointers. This 
allowed me to get rid of a bunch of traits templates and other template checks.


Repository:
  rL LLVM

https://reviews.llvm.org/D37681

Files:
  include/clang/Tooling/Refactoring/RefactoringActionRule.h
  include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h
  include/clang/Tooling/Refactoring/RefactoringActionRuleRequirementsInternal.h
  include/clang/Tooling/Refactoring/RefactoringActionRules.h
  include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h
  include/clang/Tooling/Refactoring/RefactoringResultConsumer.h
  include/clang/Tooling/Refactoring/SourceSelectionConstraints.h
  lib/Tooling/Refactoring/CMakeLists.txt
  lib/Tooling/Refactoring/Rename/RenamingAction.cpp
  lib/Tooling/Refactoring/SourceSelectionConstraints.cpp
  unittests/Tooling/RefactoringActionRulesTest.cpp

Index: unittests/Tooling/RefactoringActionRulesTest.cpp
===
--- unittests/Tooling/RefactoringActionRulesTest.cpp
+++ unittests/Tooling/RefactoringActionRulesTest.cpp
@@ -18,7 +18,6 @@
 
 using namespace clang;
 using namespace tooling;
-using namespace refactoring_action_rules;
 
 namespace {
 
@@ -53,29 +52,39 @@
 }
 
 TEST_F(RefactoringActionRulesTest, MyFirstRefactoringRule) {
-  auto ReplaceAWithB =
-  [](const RefactoringRuleContext &,
- std::pair Selection)
-  -> Expected {
-const SourceManager &SM = Selection.first.getSources();
-SourceLocation Loc = Selection.first.getRange().getBegin().getLocWithOffset(
-Selection.second);
-AtomicChange Change(SM, Loc);
-llvm::Error E = Change.replace(SM, Loc, 1, "b");
-if (E)
-  return std::move(E);
-return AtomicChanges{Change};
+  class ReplaceAWithB : public SourceChangeRefactoringRule {
+std::pair Selection;
+
+  public:
+ReplaceAWithB(std::pair Selection)
+: Selection(Selection) {}
+
+Expected
+createSourceReplacements(RefactoringRuleContext &Context) {
+  const SourceManager &SM = Context.getSources();
+  SourceLocation Loc =
+  Selection.first.getBegin().getLocWithOffset(Selection.second);
+  AtomicChange Change(SM, Loc);
+  llvm::Error E = Change.replace(SM, Loc, 1, "b");
+  if (E)
+return std::move(E);
+  return AtomicChanges{Change};
+}
   };
-  class SelectionRequirement : public selection::Requirement {
+
+  class SelectionRequirement : public SourceRangeSelectionRequirement {
   public:
-std::pair
-evaluateSelection(const RefactoringRuleContext &,
-  selection::SourceSelectionRange Selection) const {
-  return std::make_pair(Selection, 20);
+Expected>
+evaluate(RefactoringRuleContext &Context) const {
+  Expected R =
+  SourceRangeSelectionRequirement::evaluate(Context);
+  if (!R)
+return R.takeError();
+  return std::make_pair(*R, 20);
 }
   };
-  auto Rule = createRefactoringRule(ReplaceAWithB,
-requiredSelection(SelectionRequirement()));
+  auto Rule =
+  createRefactoringActionRule(SelectionRequirement());
 
   // When the requirements are satisifed, the rule's function must be invoked.
   {
@@ -120,54 +129,24 @@
 llvm::handleAllErrors(
 ErrorOrResult.takeError(),
 [&](llvm::StringError &Error) { Message = Error.getMessage(); });
-EXPECT_EQ(Message, "refactoring action can't be initiated with the "
-   "specified selection range");
+EXPECT_EQ(Message,
+  "refactoring action can't be initiated without a selection");
   }
 }
 
 TEST_F(RefactoringActionRulesTest, ReturnError) {
-  Expected (*Func)(const RefactoringRuleContext &,
-  selection::SourceSelectionRange) =
-  [](const RefactoringRuleContext &,
- selection::SourceSelectionRange) -> Expected {
-return llvm::make_error(
-"Error", llvm::make_error_code(llvm::errc::invalid_argument));
-  };
-  auto Rule = createRefactoringRule(
-  Func, requiredSelection(
-selection::identity()));
-
-  RefactoringRuleContext RefContext(Context.Sources);
-  SourceLocation Cursor =
-  Context.Sources.getLocForStartOfFile(Context.Sources.getMainFileID());
-  RefContext.setSelectionRange({Cursor, Cursor});
-  Expected Result = createReplacements(Rule, RefContext);
-
-  ASSERT_TRUE(!Result);
-  std::string Message;
-  llvm::handleAllErrors(Result.takeError(), [&](llvm::StringError &Error) {
-Message = Error.getMessage();
-  });
-  EXPECT_EQ(Message, "Error");
-}
-
-TEST_F(RefactoringActionRulesTest, ReturnInitia

[PATCH] D36574: [refactor] add clang-refactor tool with initial testing support and local-rename action

2017-09-11 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

@klimek I've added a patch that simplifies the interface and the template code 
- https://reviews.llvm.org/D37681. Hopefully you'll find that the code there is 
cleaner.


Repository:
  rL LLVM

https://reviews.llvm.org/D36574



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


[PATCH] D36574: [refactor] add clang-refactor tool with initial testing support and local-rename action

2017-09-11 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

Feel free to land the patch now if comments are addressed.


Repository:
  rL LLVM

https://reviews.llvm.org/D36574



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


[clang-tools-extra] r312912 - [clang-tidy] FunctionSizeCheck: wrap FunctionASTVisitor into anon namespace, NFC

2017-09-11 Thread Roman Lebedev via cfe-commits
Author: lebedevri
Date: Mon Sep 11 06:12:31 2017
New Revision: 312912

URL: http://llvm.org/viewvc/llvm-project?rev=312912&view=rev
Log:
[clang-tidy] FunctionSizeCheck: wrap FunctionASTVisitor into anon namespace, NFC

This check is relatively simple, and is often being used
as an example. I'm aware of at least two cases, when
simply copying the FunctionASTVisitor class to a new
check resulted in a rather unobvious segfault. Having it
in anonymous namespace prevents such a problem.

No functionality change, so i opted to avoid phabricator,
especially since clang-tidy reviews are seriously jammed.

Modified:
clang-tools-extra/trunk/clang-tidy/readability/FunctionSizeCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/readability/FunctionSizeCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/FunctionSizeCheck.cpp?rev=312912&r1=312911&r2=312912&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/readability/FunctionSizeCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/readability/FunctionSizeCheck.cpp Mon 
Sep 11 06:12:31 2017
@@ -16,6 +16,7 @@ using namespace clang::ast_matchers;
 namespace clang {
 namespace tidy {
 namespace readability {
+namespace {
 
 class FunctionASTVisitor : public RecursiveASTVisitor {
   using Base = RecursiveASTVisitor;
@@ -85,6 +86,8 @@ public:
   unsigned CurrentNestingLevel = 0;
 };
 
+} // namespace
+
 FunctionSizeCheck::FunctionSizeCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   LineThreshold(Options.get("LineThreshold", -1U)),


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


r312911 - [AST] Make RecursiveASTVisitor visit TemplateDecls in source order

2017-09-11 Thread Johannes Altmanninger via cfe-commits
Author: krobelus
Date: Mon Sep 11 06:12:30 2017
New Revision: 312911

URL: http://llvm.org/viewvc/llvm-project?rev=312911&view=rev
Log:
[AST] Make RecursiveASTVisitor visit TemplateDecls in source order

Summary:
This causes template arguments to be traversed before the templated
declaration, which is useful for clients that expect the nodes in
the same order as they are in the source code. Additionally, there
seems to be no good reason not to do so.

This was moved here from LexicallyOrderedRecursiveASTVisitor. The tests
still reside in LexicallyOrderedRecursiveASTVisitorTest.cpp under
VisitTemplateDecls.

Reviewers: arphaman, rsmith, klimek

Subscribers: cfe-commits, klimek

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

Modified:
cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
cfe/trunk/include/clang/AST/RecursiveASTVisitor.h

Modified: cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h?rev=312911&r1=312910&r2=312911&view=diff
==
--- cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h (original)
+++ cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h Mon Sep 
11 06:12:30 2017
@@ -111,8 +111,6 @@ public:
 return true;
   }
 
-  bool shouldTraverseTemplateArgumentsBeforeDecl() const { return true; }
-
   Stmt::child_range getStmtChildren(Stmt *S) { return S->children(); }
 
   SmallVector getStmtChildren(CXXOperatorCallExpr *CE) {

Modified: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/RecursiveASTVisitor.h?rev=312911&r1=312910&r2=312911&view=diff
==
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h (original)
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h Mon Sep 11 06:12:30 2017
@@ -537,7 +537,6 @@ private:
 
   bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
   bool PostVisitStmt(Stmt *S);
-  bool shouldTraverseTemplateArgumentsBeforeDecl() const { return false; }
 };
 
 template 
@@ -1691,13 +1690,8 @@ bool RecursiveASTVisitor::Trave
 // template declarations.
 #define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND)   
\
   DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, {  
\
-if (getDerived().shouldTraverseTemplateArgumentsBeforeDecl()) {
\
-  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); 
\
-  TRY_TO(TraverseDecl(D->getTemplatedDecl())); 
\
-} else {   
\
-  TRY_TO(TraverseDecl(D->getTemplatedDecl())); 
\
-  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); 
\
-}  
\
+TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));   
\
+TRY_TO(TraverseDecl(D->getTemplatedDecl()));   
\

\
 /* By default, we do not traverse the instantiations of
\
class templates since they do not appear in the user code. The  
\


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


[PATCH] D37662: [AST] Make RecursiveASTVisitor visit TemplateDecls in source order

2017-09-11 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312911: [AST] Make RecursiveASTVisitor visit TemplateDecls 
in source order (authored by krobelus).

Repository:
  rL LLVM

https://reviews.llvm.org/D37662

Files:
  cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
  cfe/trunk/include/clang/AST/RecursiveASTVisitor.h


Index: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
===
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
@@ -537,7 +537,6 @@
 
   bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
   bool PostVisitStmt(Stmt *S);
-  bool shouldTraverseTemplateArgumentsBeforeDecl() const { return false; }
 };
 
 template 
@@ -1691,13 +1690,8 @@
 // template declarations.
 #define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND)   
\
   DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, {  
\
-if (getDerived().shouldTraverseTemplateArgumentsBeforeDecl()) {
\
-  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); 
\
-  TRY_TO(TraverseDecl(D->getTemplatedDecl())); 
\
-} else {   
\
-  TRY_TO(TraverseDecl(D->getTemplatedDecl())); 
\
-  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); 
\
-}  
\
+TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));   
\
+TRY_TO(TraverseDecl(D->getTemplatedDecl()));   
\

\
 /* By default, we do not traverse the instantiations of
\
class templates since they do not appear in the user code. The  
\
Index: cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
===
--- cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
+++ cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
@@ -111,8 +111,6 @@
 return true;
   }
 
-  bool shouldTraverseTemplateArgumentsBeforeDecl() const { return true; }
-
   Stmt::child_range getStmtChildren(Stmt *S) { return S->children(); }
 
   SmallVector getStmtChildren(CXXOperatorCallExpr *CE) {


Index: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
===
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
@@ -537,7 +537,6 @@
 
   bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
   bool PostVisitStmt(Stmt *S);
-  bool shouldTraverseTemplateArgumentsBeforeDecl() const { return false; }
 };
 
 template 
@@ -1691,13 +1690,8 @@
 // template declarations.
 #define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND)   \
   DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, {  \
-if (getDerived().shouldTraverseTemplateArgumentsBeforeDecl()) {\
-  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \
-  TRY_TO(TraverseDecl(D->getTemplatedDecl())); \
-} else {   \
-  TRY_TO(TraverseDecl(D->getTemplatedDecl())); \
-  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \
-}  \
+TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));   \
+TRY_TO(TraverseDecl(D->getTemplatedDecl()));   \
\
 /* By default, we do not traverse the instantiations of\
class templates since they do not appear in the user code. The  \
Index: cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
===
--- cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
+++ cfe/trunk/include/clang/AST/LexicallyOrderedRecursiveASTVisitor.h
@@ -111,8 +111,6 @@
 return true;
   }
 
-  bool shouldTraverseTemplateArgumentsBeforeDecl() const { return true; }
-
   Stmt::child_range getStmtChildren(Stmt *S) { return S->children(); }
 
   SmallVector getStmtChildren(CXXOperatorCallExpr *CE) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic updated this revision to Diff 114582.

https://reviews.llvm.org/D34878

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Driver/CC1Options.td
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Arch/ARM.cpp
  lib/Driver/ToolChains/Arch/ARM.h
  test/Driver/clang-translation.c

Index: test/Driver/clang-translation.c
===
--- test/Driver/clang-translation.c
+++ test/Driver/clang-translation.c
@@ -87,6 +87,18 @@
 // ARMV5E: "-cc1"
 // ARMV5E: "-target-cpu" "arm1022e"
 
+// RUN: %clang -target arm-linux -mtp=cp15 -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER-HARD %s
+// ARMv7_THREAD_POINTER-HARD: "-target-feature" "+read-tp-hard"
+
+// RUN: %clang -target arm-linux -mtp=soft -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_SOFT %s
+// ARMv7_THREAD_POINTER_SOFT-NOT: "-target-feature" "+read-tp-hard"
+
+// RUN: %clang -target arm-linux -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_NON %s
+// ARMv7_THREAD_POINTER_NON-NOT: "-target-feature" "+read-tp-hard"
+
 // RUN: %clang -target powerpc64-unknown-linux-gnu \
 // RUN: -### -S %s -mcpu=G5 2>&1 | FileCheck -check-prefix=PPCG5 %s
 // PPCG5: clang
Index: lib/Driver/ToolChains/Arch/ARM.h
===
--- lib/Driver/ToolChains/Arch/ARM.h
+++ lib/Driver/ToolChains/Arch/ARM.h
@@ -32,14 +32,21 @@
 void appendEBLinkFlags(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs,
const llvm::Triple &Triple);
+enum class ReadTPMode {
+  Invalid,
+  Soft,
+  Cp15,
+};
+
 enum class FloatABI {
   Invalid,
   Soft,
   SoftFP,
   Hard,
 };
 
 FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args);
+ReadTPMode getReadTPMode(const ToolChain &TC, const llvm::opt::ArgList &Args);
 
 bool useAAPCSForMachO(const llvm::Triple &T);
 void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args,
Index: lib/Driver/ToolChains/Arch/ARM.cpp
===
--- lib/Driver/ToolChains/Arch/ARM.cpp
+++ lib/Driver/ToolChains/Arch/ARM.cpp
@@ -131,6 +131,27 @@
  T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
 }
 
+// Select mode for reading thread pointer (-mtp=soft/cp15).
+arm::ReadTPMode arm::getReadTPMode(const ToolChain &TC, const ArgList &Args) {
+  if (Arg *A =
+  Args.getLastArg(options::OPT_mtp_mode_EQ)) {
+const Driver &D = TC.getDriver();
+arm::ReadTPMode ThreadPointer =
+   llvm::StringSwitch(A->getValue())
+   .Case("cp15", ReadTPMode::Cp15)
+   .Case("soft", ReadTPMode::Soft)
+   .Default(ReadTPMode::Invalid);
+if (ThreadPointer != ReadTPMode::Invalid)
+  return ThreadPointer;
+if (StringRef(A->getValue()).empty())
+  D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
+else
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+return ReadTPMode::Invalid;
+  }
+  return ReadTPMode::Soft;
+}
+
 // Select the float ABI as determined by -msoft-float, -mhard-float, and
 // -mfloat-abi=.
 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
@@ -262,6 +283,7 @@
   bool KernelOrKext =
   Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
+  arm::ReadTPMode ThreadPointer = arm::getReadTPMode(TC, Args);
   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
 
@@ -303,6 +325,10 @@
 }
   }
 
+
+  if (ThreadPointer == arm::ReadTPMode::Cp15)
+Features.push_back("+read-tp-hard");
+
   // Check -march. ClangAs gives preference to -Wa,-march=.
   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
   StringRef ArchName;
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1689,6 +1689,8 @@
   HelpText<"Disallow generation of data access to code sections (ARM only)">;
 def mno_execute_only : Flag<["-"], "mno-execute-only">, Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
+def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, Values<"soft, cp15">,
+  HelpText<"Read thread pointer from coprocessor register (ARM only)">;
 def mpure_code : Flag<["-"], "mpure-code">, Alias; // Alias for GCC compatibility
 def mno_pure_code : Flag<["-"], "mno-pure-code">, Alias;
 def mtvos_version_min_EQ : Joined<["-"], "mtvos-version-min=">, Group;
Index: include/clang/Driver/CC1Options.td
===
--- include/clang/Driver/CC1Options.td
+++ include/clang/Driver/CC1Options.td
@@ -257,6 +257,8 @@
"prec

[PATCH] D37677: [libc++] implement future synchronization using atomic_flag

2017-09-11 Thread Ben Craig via Phabricator via cfe-commits
bcraig added a comment.

Is there a benchmark where this demonstrates some performance improvement?  I 
fear that the switch to condition_variable_any will swamp any performance gains 
from the switch to a spin lock.

Also, the spin lock is being held during allocating operations (the exception 
throws and at_thread_exit code).  That's a little long to be holding a spin 
lock.


https://reviews.llvm.org/D37677



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


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls accepted this revision.
kristof.beyls added a comment.
This revision is now accepted and ready to land.

Thanks Strahinja!
I thought that some indentations looked a bit strange, so I'd just still check 
that clang-format formats your changes the same way.
Otherwise LGTM!


https://reviews.llvm.org/D34878



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


Re: [PATCH] D37629: [Sema] Move some stuff into -Wtautological-unsigned-enum-zero-compare

2017-09-11 Thread Roman Lebedev via cfe-commits
On Fri, Sep 8, 2017 at 9:33 PM, Roman Lebedev via Phabricator via
cfe-commits  wrote:
> lebedev.ri added a comment.
>
> In https://reviews.llvm.org/D37629#865068, @lebedev.ri wrote:
>
>> And finish reducing the code by for-range-loop`ing over array + use 
>> `std::array`.
>
>
> I will need to fix handling of the second edge-case (comparison with max 
> unsigned value or with min/max for signed values), so having the code this 
> way *might* help..
Allright, now that weekend has passed, does anyone has any concerns
with this, or can this be committed?
To reiterate, there are two things in here:
1. adding a new more fine-grained
-Wtautological-unsigned-enum-zero-compare, and using it instead of
-Wtautological-unsigned-zero-compare for enums
2. small code refactoring to minimize the code duplication that is
created by the first step.

> Repository:
>   rL LLVM
>
> https://reviews.llvm.org/D37629
Roman.

> ___
> 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] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic added a comment.

Thanks for the review!  I will check indentations with clang format.


https://reviews.llvm.org/D34878



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


[PATCH] D37572: [clang-tidy] SuspiciousEnumUsageCheck bugfix

2017-09-11 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.

Still LG. Fine to commit.

Thanks for the fix!

If you find time to construct the test case that triggers both affected code 
paths (my test seems to only inspect one of them, IIUC), it would be nice to do 
as a follow up.


https://reviews.llvm.org/D37572



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


[PATCH] D37663: [AST] Make RecursiveASTVisitor visit CXXOperatorCallExpr in source order

2017-09-11 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes added inline comments.



Comment at: include/clang/AST/RecursiveASTVisitor.h:334
+case OO_Arrow:
+case OO_Call:
+case OO_Subscript:

klimek wrote:
> Why do we need to swap for calls?
The idea is that the opening parenthesis/bracket  comes after the caller, for 
example in this call with two arguments.

```
`-CXXOperatorCallExpr
  |-ImplicitCastExpr
  | `-DeclRefExpr operator()
  |-DeclRefExpr caller
  |-IntegerLiteral
  `-IntegerLiteral
```

 Of course we fail to capture the fact that there is also a closing parenthesis 
or bracket. So this is no perfect solution.


https://reviews.llvm.org/D37663



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


[PATCH] D37668: [X86][intrinsics] lower _mm[256|512]_mask[z]_set1_epi[8|16|32|64] intrinsic to IR

2017-09-11 Thread jina via Phabricator via cfe-commits
jina.nahias updated this revision to Diff 114594.
jina.nahias added a comment.

delete from include/clang/Basic/BuiltinsX86.def and 
include/clang/Basic/BuiltinsX86_64.def


https://reviews.llvm.org/D37668

Files:
  include/clang/Basic/BuiltinsX86.def
  include/clang/Basic/BuiltinsX86_64.def


Index: include/clang/Basic/BuiltinsX86_64.def
===
--- include/clang/Basic/BuiltinsX86_64.def
+++ include/clang/Basic/BuiltinsX86_64.def
@@ -71,9 +71,6 @@
 TARGET_BUILTIN(__builtin_ia32_bextri_u64, "ULLiULLiIULLi", "", "tbm")
 TARGET_BUILTIN(__builtin_ia32_lwpins64, "UcULLiUiUi", "", "lwp")
 TARGET_BUILTIN(__builtin_ia32_lwpval64, "vULLiUiUi", "", "lwp")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastq512_gpr_mask, "V8LLiLLiV8LLiUc", "", 
"avx512f")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastq128_gpr_mask, 
"V2LLiULLiV2LLiUc","","avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastq256_gpr_mask, 
"V4LLiULLiV4LLiUc","","avx512vl")
 TARGET_BUILTIN(__builtin_ia32_vcvtsd2si64, "LLiV2dIi","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_vcvtsd2usi64, "ULLiV2dIi","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_vcvtss2si64, "LLiV4fIi","","avx512f")
Index: include/clang/Basic/BuiltinsX86.def
===
--- include/clang/Basic/BuiltinsX86.def
+++ include/clang/Basic/BuiltinsX86.def
@@ -977,7 +977,6 @@
 TARGET_BUILTIN(__builtin_ia32_pmuludq512, "V8LLiV16iV16i", "", "avx512f")
 TARGET_BUILTIN(__builtin_ia32_ptestmd512, "UsV16iV16iUs", "", "avx512f")
 TARGET_BUILTIN(__builtin_ia32_ptestmq512, "UcV8LLiV8LLiUc", "", "avx512f")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastd512_gpr_mask, "V16iiV16iUs", "", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_pbroadcastq512_mem_mask, "V8LLiLLiV8LLiUc", "", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_loaddqusi512_mask, "V16iiC*V16iUs", "", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_loaddqudi512_mask, "V8LLiLLiC*V8LLiUc", "", 
"avx512f")
@@ -1381,11 +1380,6 @@
 TARGET_BUILTIN(__builtin_ia32_movdqa64load256_mask, 
"V4LLiV4LLiC*V4LLiUc","","avx512vl")
 TARGET_BUILTIN(__builtin_ia32_movdqa64store128_mask, 
"vV2LLi*V2LLiUc","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_movdqa64store256_mask, 
"vV4LLi*V4LLiUc","","avx512f")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastb512_gpr_mask, 
"V64ccV64cULLi","","avx512bw")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastb128_gpr_mask, 
"V16ccV16cUs","","avx512bw,avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastb256_gpr_mask, 
"V32ccV32cUi","","avx512bw,avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastd128_gpr_mask, 
"V4iiV4iUc","","avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastd256_gpr_mask, 
"V8iiV8iUc","","avx512vl")
 TARGET_BUILTIN(__builtin_ia32_vpmadd52huq512_mask, 
"V8LLiV8LLiV8LLiV8LLiUc","","avx512ifma")
 TARGET_BUILTIN(__builtin_ia32_vpmadd52huq512_maskz, 
"V8LLiV8LLiV8LLiV8LLiUc","","avx512ifma")
 TARGET_BUILTIN(__builtin_ia32_vpmadd52luq512_mask, 
"V8LLiV8LLiV8LLiV8LLiUc","","avx512ifma")
@@ -1596,9 +1590,6 @@
 TARGET_BUILTIN(__builtin_ia32_broadcastmb256, "V4LLiUc","","avx512cd,avx512vl")
 TARGET_BUILTIN(__builtin_ia32_broadcastmw128, "V4iUs","","avx512cd,avx512vl")
 TARGET_BUILTIN(__builtin_ia32_broadcastmw256, "V8iUs","","avx512cd,avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastw512_gpr_mask, 
"V32shV32sUi","","avx512bw")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastw256_gpr_mask, 
"V16shV16sUs","","avx512bw,avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastw128_gpr_mask, 
"V8ssV8sUc","","avx512bw,avx512vl")
 TARGET_BUILTIN(__builtin_ia32_pmovsdb512_mask, "V16cV16iV16cUs","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_pmovsdb512mem_mask, "vV16c*V16iUs","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_pmovswb512mem_mask, "vV32c*V32sUi","","avx512bw")


Index: include/clang/Basic/BuiltinsX86_64.def
===
--- include/clang/Basic/BuiltinsX86_64.def
+++ include/clang/Basic/BuiltinsX86_64.def
@@ -71,9 +71,6 @@
 TARGET_BUILTIN(__builtin_ia32_bextri_u64, "ULLiULLiIULLi", "", "tbm")
 TARGET_BUILTIN(__builtin_ia32_lwpins64, "UcULLiUiUi", "", "lwp")
 TARGET_BUILTIN(__builtin_ia32_lwpval64, "vULLiUiUi", "", "lwp")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastq512_gpr_mask, "V8LLiLLiV8LLiUc", "", "avx512f")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastq128_gpr_mask, "V2LLiULLiV2LLiUc","","avx512vl")
-TARGET_BUILTIN(__builtin_ia32_pbroadcastq256_gpr_mask, "V4LLiULLiV4LLiUc","","avx512vl")
 TARGET_BUILTIN(__builtin_ia32_vcvtsd2si64, "LLiV2dIi","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_vcvtsd2usi64, "ULLiV2dIi","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_vcvtss2si64, "LLiV4fIi","","avx512f")
Index: include/clang/Basic/BuiltinsX86.def
===
--- include/clang/Basic/BuiltinsX86.def
+++ include/clang/Basic/BuiltinsX86.def
@@ -977,7 +977,6 @@
 TARGET_BUILTIN(__builtin_ia32_pmuludq512, "V8LLiV16iV16i", "", "avx512f")
 TARGET_BUILTIN(__builtin_ia32_ptestmd

[PATCH] D31140: [LLVMbugs] [Bug 18710] Only generate .ARM.exidx and .ARM.extab when needed in EHABI

2017-09-11 Thread Christian Bruel via Phabricator via cfe-commits
chrib updated this revision to Diff 114589.
chrib added a comment.

Hello Eli,

You were right, using IsUnwindTablesDefault is the correct way to abstract the 
need for UnwindTables. I missed the relationship between the driver 
munwind-table and GodeGenOpts.UnwindTables use in Codegen.

Here is a new patch just setting IsUnwindTablesDefault for EHABI. No Changes in 
the testsuite results with https://reviews.llvm.org/D31139


https://reviews.llvm.org/D31140

Files:
  lib/Driver/ToolChains/BareMetal.cpp
  lib/Driver/ToolChains/BareMetal.h


Index: lib/Driver/ToolChains/BareMetal.h
===
--- lib/Driver/ToolChains/BareMetal.h
+++ lib/Driver/ToolChains/BareMetal.h
@@ -32,6 +32,7 @@
 
 public:
   bool useIntegratedAs() const override { return true; }
+  bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const override;
   bool isCrossCompiling() const override { return true; }
   bool isPICDefault() const override { return false; }
   bool isPIEDefault() const override { return false; }
Index: lib/Driver/ToolChains/BareMetal.cpp
===
--- lib/Driver/ToolChains/BareMetal.cpp
+++ lib/Driver/ToolChains/BareMetal.cpp
@@ -57,6 +57,10 @@
   return true;
 }
 
+bool BareMetal::IsUnwindTablesDefault(const ArgList &Args) const {
+  return getDriver().CCCIsCXX();
+}
+
 bool BareMetal::handlesTarget(const llvm::Triple &Triple) {
   return isARMBareMetal(Triple);
 }


Index: lib/Driver/ToolChains/BareMetal.h
===
--- lib/Driver/ToolChains/BareMetal.h
+++ lib/Driver/ToolChains/BareMetal.h
@@ -32,6 +32,7 @@
 
 public:
   bool useIntegratedAs() const override { return true; }
+  bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const override;
   bool isCrossCompiling() const override { return true; }
   bool isPICDefault() const override { return false; }
   bool isPIEDefault() const override { return false; }
Index: lib/Driver/ToolChains/BareMetal.cpp
===
--- lib/Driver/ToolChains/BareMetal.cpp
+++ lib/Driver/ToolChains/BareMetal.cpp
@@ -57,6 +57,10 @@
   return true;
 }
 
+bool BareMetal::IsUnwindTablesDefault(const ArgList &Args) const {
+  return getDriver().CCCIsCXX();
+}
+
 bool BareMetal::handlesTarget(const llvm::Triple &Triple) {
   return isARMBareMetal(Triple);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37474: [PCH] Allow VFS to be used for tests that generate PCH files

2017-09-11 Thread Cameron via Phabricator via cfe-commits
cameron314 updated this revision to Diff 114604.
cameron314 added a comment.

Final diff, will commit soon. Thanks!


https://reviews.llvm.org/D37474

Files:
  include/clang/Frontend/PrecompiledPreamble.h
  lib/Frontend/ASTUnit.cpp
  unittests/Frontend/CMakeLists.txt
  unittests/Frontend/PCHPreambleTest.cpp

Index: unittests/Frontend/PCHPreambleTest.cpp
===
--- /dev/null
+++ unittests/Frontend/PCHPreambleTest.cpp
@@ -0,0 +1,156 @@
+//-- unittests/Frontend/PCHPreambleTest.cpp - FrontendAction tests ---//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Frontend/FrontendOptions.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/FileManager.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+class ReadCountingInMemoryFileSystem : public vfs::InMemoryFileSystem
+{
+  std::map ReadCounts;
+
+public:
+  ErrorOr> openFileForRead(const Twine &Path) override
+  {
+SmallVector PathVec;
+Path.toVector(PathVec);
+llvm::sys::path::remove_dots(PathVec, true);
+++ReadCounts[std::string(PathVec.begin(), PathVec.end())];
+return InMemoryFileSystem::openFileForRead(Path);
+  }
+
+  unsigned GetReadCount(const Twine &Path) const
+  {
+auto it = ReadCounts.find(Path.str());
+return it == ReadCounts.end() ? 0 : it->second;
+  }
+};
+
+class PCHPreambleTest : public ::testing::Test {
+  IntrusiveRefCntPtr VFS;
+  StringMap RemappedFiles;
+  std::shared_ptr PCHContainerOpts;
+  FileSystemOptions FSOpts;
+
+public:
+  void SetUp() override {
+VFS = new ReadCountingInMemoryFileSystem();
+// We need the working directory to be set to something absolute,
+// otherwise it ends up being inadvertently set to the current
+// working directory in the real file system due to a series of
+// unfortunate conditions interacting badly.
+// What's more, this path *must* be absolute on all (real)
+// filesystems, so just '/' won't work (e.g. on Win32).
+VFS->setCurrentWorkingDirectory("//./");
+  }
+
+  void TearDown() override {
+  }
+
+  void AddFile(const std::string &Filename, const std::string &Contents) {
+::time_t now;
+::time(&now);
+VFS->addFile(Filename, now, MemoryBuffer::getMemBufferCopy(Contents, Filename));
+  }
+
+  void RemapFile(const std::string &Filename, const std::string &Contents) {
+RemappedFiles[Filename] = Contents;
+  }
+
+  std::unique_ptr ParseAST(const std::string &EntryFile) {
+PCHContainerOpts = std::make_shared();
+std::shared_ptr CI(new CompilerInvocation);
+CI->getFrontendOpts().Inputs.push_back(
+  FrontendInputFile(EntryFile, FrontendOptions::getInputKindForExtension(
+llvm::sys::path::extension(EntryFile).substr(1;
+
+CI->getTargetOpts().Triple = "i386-unknown-linux-gnu";
+
+CI->getPreprocessorOpts().RemappedFileBuffers = GetRemappedFiles();
+
+PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
+PPOpts.RemappedFilesKeepOriginalName = true;
+
+IntrusiveRefCntPtr
+  Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions, new DiagnosticConsumer));
+
+FileManager *FileMgr = new FileManager(FSOpts, VFS);
+
+std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(
+  CI, PCHContainerOpts, Diags, FileMgr, false, false,
+  /*PrecompilePreambleAfterNParses=*/1);
+return AST;
+  }
+
+  bool ReparseAST(const std::unique_ptr &AST) {
+bool reparseFailed = AST->Reparse(PCHContainerOpts, GetRemappedFiles(), VFS);
+return !reparseFailed;
+  }
+
+  unsigned GetFileReadCount(const std::string &Filename) const {
+return VFS->GetReadCount(Filename);
+  }
+
+private:
+  std::vector>
+  GetRemappedFiles() const {
+std::vector> Remapped;
+for (const auto &RemappedFile : RemappedFiles) {
+  std::unique_ptr buf = MemoryBuffer::getMemBufferCopy(
+RemappedFile.second, RemappedFile.first());
+  Remapped.emplace_back(RemappedFile.first(), buf.release());
+}
+return Remapped;
+  }
+};
+
+TEST_F(PCHPreambleTest, ReparseWithOverriddenFileDoesNotInvalidatePreamble) {
+  std::string Header1 = "//./header1.h";
+  std::string Header2 = "//./header2.h";
+  std::string MainName = "//./main.cpp";
+  AddFile(Header1, "");
+  AddFile(Header2, "#pragma once");
+  AddFile(MainName,
+"#include \"//./foo/../header1.h\"\n"
+"#include \"//./foo/../header2.h\"\

[PATCH] D37474: [PCH] Allow VFS to be used for tests that generate PCH files

2017-09-11 Thread Cameron via Phabricator via cfe-commits
cameron314 added inline comments.



Comment at: include/clang/Frontend/PrecompiledPreamble.h:100
 
   /// PreambleBounds used to build the preamble
   PreambleBounds getBounds() const;

ilya-biryukov wrote:
> Not introduced by this change, but could you also add a full stop here for 
> constistency?
Sure.



Comment at: include/clang/Frontend/PrecompiledPreamble.h:103
 
+  /// The temporary file path at which the preamble PCH was placed
+  StringRef GetPCHPath() const { return PCHFile.getFilePath(); }

ilya-biryukov wrote:
> NIT: comment should end with a full stop.
OK!



Comment at: lib/Frontend/ASTUnit.cpp:1021
+  if (Buf)
+PCHFS->addFile(PCHFilename, 0, std::move(*Buf));
+  IntrusiveRefCntPtr

ilya-biryukov wrote:
> Maybe return original `VFS` if `PCHFilename` could not be read and not create 
> any empty overlays?
Makes sense, will do.



Comment at: lib/Frontend/ASTUnit.cpp:1053
+  IntrusiveRefCntPtr RealFS = vfs::getRealFileSystem();
+  if (OverrideMainBuffer && VFS && RealFS && VFS != RealFS &&
+  !VFS->exists(Preamble->GetPCHPath())) {

ilya-biryukov wrote:
> The check `&& RealFS` is redundant and can be removed.
It's not redundant, but looking at the implementation of 
`vfs::getRealFileSystem` it will always return a non-null pointer.


https://reviews.llvm.org/D37474



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


r312917 - [PCH] Allow VFS to be used for tests that generate PCH files

2017-09-11 Thread Cameron Desrochers via cfe-commits
Author: cameron314
Date: Mon Sep 11 08:03:23 2017
New Revision: 312917

URL: http://llvm.org/viewvc/llvm-project?rev=312917&view=rev
Log:
[PCH] Allow VFS to be used for tests that generate PCH files

When using a virtual file-system (VFS) and a preamble file (PCH) is generated,
it is generated on-disk in the real file-system instead of in the VFS (which
makes sense, since the VFS is read-only). However, when subsequently reading
the generated PCH, the frontend passes through the VFS it has been given --
resulting in an error and a failed parse (since the VFS doesn't contain the
PCH; the real filesystem does).

This patch fixes that by detecting when a VFS is being used for a parse that
needs to work with a PCH file, and creating an overlay VFS that includes the
PCH file from the real file-system.

This allows tests to be written which make use of both PCH files and a VFS.

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

Added:
cfe/trunk/unittests/Frontend/PCHPreambleTest.cpp   (with props)
Modified:
cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h
cfe/trunk/lib/Frontend/ASTUnit.cpp
cfe/trunk/unittests/Frontend/CMakeLists.txt

Modified: cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h?rev=312917&r1=312916&r2=312917&view=diff
==
--- cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h (original)
+++ cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h Mon Sep 11 08:03:23 
2017
@@ -97,9 +97,12 @@ public:
   PrecompiledPreamble(PrecompiledPreamble &&) = default;
   PrecompiledPreamble &operator=(PrecompiledPreamble &&) = default;
 
-  /// PreambleBounds used to build the preamble
+  /// PreambleBounds used to build the preamble.
   PreambleBounds getBounds() const;
 
+  /// The temporary file path at which the preamble PCH was placed.
+  StringRef GetPCHPath() const { return PCHFile.getFilePath(); }
+
   /// Check whether PrecompiledPreamble can be reused for the new contents(\p
   /// MainFileBuffer) of the main file.
   bool CanReuse(const CompilerInvocation &Invocation,

Modified: cfe/trunk/lib/Frontend/ASTUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/ASTUnit.cpp?rev=312917&r1=312916&r2=312917&view=diff
==
--- cfe/trunk/lib/Frontend/ASTUnit.cpp (original)
+++ cfe/trunk/lib/Frontend/ASTUnit.cpp Mon Sep 11 08:03:23 2017
@@ -1009,6 +1009,24 @@ static void checkAndSanitizeDiags(SmallV
   }
 }
 
+static IntrusiveRefCntPtr createVFSOverlayForPreamblePCH(
+StringRef PCHFilename,
+IntrusiveRefCntPtr RealFS,
+IntrusiveRefCntPtr VFS) {
+  // We want only the PCH file from the real filesystem to be available,
+  // so we create an in-memory VFS with just that and overlay it on top.
+  auto Buf = RealFS->getBufferForFile(PCHFilename);
+  if (!Buf)
+return VFS;
+  IntrusiveRefCntPtr
+  PCHFS(new vfs::InMemoryFileSystem());
+  PCHFS->addFile(PCHFilename, 0, std::move(*Buf));
+  IntrusiveRefCntPtr
+  Overlay(new vfs::OverlayFileSystem(VFS));
+  Overlay->pushOverlay(PCHFS);
+  return Overlay;
+}
+
 /// Parse the source file into a translation unit using the given compiler
 /// invocation, replacing the current translation unit.
 ///
@@ -1030,6 +1048,24 @@ bool ASTUnit::Parse(std::shared_ptrsetVirtualFileSystem(VFS);
   }
 
+  // Make sure we can access the PCH file even if we're using a VFS
+  if (!VFS && FileMgr)
+VFS = FileMgr->getVirtualFileSystem();
+  IntrusiveRefCntPtr RealFS = vfs::getRealFileSystem();
+  if (OverrideMainBuffer && VFS && RealFS && VFS != RealFS &&
+  !VFS->exists(Preamble->GetPCHPath())) {
+// We have a slight inconsistency here -- we're using the VFS to
+// read files, but the PCH was generated in the real file system.
+VFS = createVFSOverlayForPreamblePCH(Preamble->GetPCHPath(), RealFS, VFS);
+if (FileMgr) {
+  FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
+  Clang->setFileManager(FileMgr.get());
+}
+else {
+  Clang->setVirtualFileSystem(VFS);
+}
+  }
+
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar
 CICleanup(Clang.get());

Modified: cfe/trunk/unittests/Frontend/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Frontend/CMakeLists.txt?rev=312917&r1=312916&r2=312917&view=diff
==
--- cfe/trunk/unittests/Frontend/CMakeLists.txt (original)
+++ cfe/trunk/unittests/Frontend/CMakeLists.txt Mon Sep 11 08:03:23 2017
@@ -6,6 +6,7 @@ add_clang_unittest(FrontendTests
   ASTUnitTest.cpp
   FrontendActionTest.cpp
   CodeGenActionTest.cpp
+  PCHPreambleTest.cpp
   )
 target_link_libraries(FrontendTests
   clangAST

Added: cfe/trunk/unittests/Front

[PATCH] D37474: [PCH] Allow VFS to be used for tests that generate PCH files

2017-09-11 Thread Cameron via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312917: [PCH] Allow VFS to be used for tests that generate 
PCH files (authored by cameron314).

Changed prior to commit:
  https://reviews.llvm.org/D37474?vs=114604&id=114612#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37474

Files:
  cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h
  cfe/trunk/lib/Frontend/ASTUnit.cpp
  cfe/trunk/unittests/Frontend/CMakeLists.txt
  cfe/trunk/unittests/Frontend/PCHPreambleTest.cpp

Index: cfe/trunk/lib/Frontend/ASTUnit.cpp
===
--- cfe/trunk/lib/Frontend/ASTUnit.cpp
+++ cfe/trunk/lib/Frontend/ASTUnit.cpp
@@ -1009,6 +1009,24 @@
   }
 }
 
+static IntrusiveRefCntPtr createVFSOverlayForPreamblePCH(
+StringRef PCHFilename,
+IntrusiveRefCntPtr RealFS,
+IntrusiveRefCntPtr VFS) {
+  // We want only the PCH file from the real filesystem to be available,
+  // so we create an in-memory VFS with just that and overlay it on top.
+  auto Buf = RealFS->getBufferForFile(PCHFilename);
+  if (!Buf)
+return VFS;
+  IntrusiveRefCntPtr
+  PCHFS(new vfs::InMemoryFileSystem());
+  PCHFS->addFile(PCHFilename, 0, std::move(*Buf));
+  IntrusiveRefCntPtr
+  Overlay(new vfs::OverlayFileSystem(VFS));
+  Overlay->pushOverlay(PCHFS);
+  return Overlay;
+}
+
 /// Parse the source file into a translation unit using the given compiler
 /// invocation, replacing the current translation unit.
 ///
@@ -1030,6 +1048,24 @@
 Clang->setVirtualFileSystem(VFS);
   }
 
+  // Make sure we can access the PCH file even if we're using a VFS
+  if (!VFS && FileMgr)
+VFS = FileMgr->getVirtualFileSystem();
+  IntrusiveRefCntPtr RealFS = vfs::getRealFileSystem();
+  if (OverrideMainBuffer && VFS && RealFS && VFS != RealFS &&
+  !VFS->exists(Preamble->GetPCHPath())) {
+// We have a slight inconsistency here -- we're using the VFS to
+// read files, but the PCH was generated in the real file system.
+VFS = createVFSOverlayForPreamblePCH(Preamble->GetPCHPath(), RealFS, VFS);
+if (FileMgr) {
+  FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
+  Clang->setFileManager(FileMgr.get());
+}
+else {
+  Clang->setVirtualFileSystem(VFS);
+}
+  }
+
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar
 CICleanup(Clang.get());
Index: cfe/trunk/unittests/Frontend/CMakeLists.txt
===
--- cfe/trunk/unittests/Frontend/CMakeLists.txt
+++ cfe/trunk/unittests/Frontend/CMakeLists.txt
@@ -6,6 +6,7 @@
   ASTUnitTest.cpp
   FrontendActionTest.cpp
   CodeGenActionTest.cpp
+  PCHPreambleTest.cpp
   )
 target_link_libraries(FrontendTests
   clangAST
Index: cfe/trunk/unittests/Frontend/PCHPreambleTest.cpp
===
--- cfe/trunk/unittests/Frontend/PCHPreambleTest.cpp
+++ cfe/trunk/unittests/Frontend/PCHPreambleTest.cpp
@@ -0,0 +1,156 @@
+//-- unittests/Frontend/PCHPreambleTest.cpp - FrontendAction tests ---//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Frontend/FrontendOptions.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/FileManager.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+class ReadCountingInMemoryFileSystem : public vfs::InMemoryFileSystem
+{
+  std::map ReadCounts;
+
+public:
+  ErrorOr> openFileForRead(const Twine &Path) override
+  {
+SmallVector PathVec;
+Path.toVector(PathVec);
+llvm::sys::path::remove_dots(PathVec, true);
+++ReadCounts[std::string(PathVec.begin(), PathVec.end())];
+return InMemoryFileSystem::openFileForRead(Path);
+  }
+
+  unsigned GetReadCount(const Twine &Path) const
+  {
+auto it = ReadCounts.find(Path.str());
+return it == ReadCounts.end() ? 0 : it->second;
+  }
+};
+
+class PCHPreambleTest : public ::testing::Test {
+  IntrusiveRefCntPtr VFS;
+  StringMap RemappedFiles;
+  std::shared_ptr PCHContainerOpts;
+  FileSystemOptions FSOpts;
+
+public:
+  void SetUp() override {
+VFS = new ReadCountingInMemoryFileSystem();
+// We need the working directory to be set to something absolute,
+// otherwise it ends up being inadvertently set to the current
+// working directory in the real file system due to a seri

[PATCH] D37308: Interface class with uuid base record

2017-09-11 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

By my reading of the code, you still haven't fixed this example:

  struct __declspec(uuid("---C000-0046")) IUnknown {};
  struct IPropertyPageBase : public IUnknown {};
  struct IPropertyPage : public IPropertyPageBase {};
  
  __interface foo {};
  __interface bar {};
  __interface Prop2 : foo, bar, IUnknown{};
  
  __interface Prop3 : foo, Prop2{};

According to godbolt, all compile w/o error.




Comment at: lib/Sema/SemaDeclCXX.cpp:2394
+/// \brief Test if RD or its inhetited bases is an IUnknow type.
+static bool IsOrInheritsFromIUnknown(const CXXRecordDecl *RD) {
+  const CXXRecordDecl *Base =

See my example below, you still need to fix this.


https://reviews.llvm.org/D37308



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


[PATCH] D37694: [X86] [PATCH] [intrinsics] Lowering X86 ABS intrinsics to IR. (clang)

2017-09-11 Thread Uriel Korach via Phabricator via cfe-commits
uriel.k created this revision.

This patch, together with a matching llvm patch 
(https://reviews.llvm.org/D37693), implements the lowering of X86 ABS 
intrinsics to IR.


https://reviews.llvm.org/D37694

Files:
  lib/CodeGen/CGBuiltin.cpp
  test/CodeGen/avx2-builtins.c
  test/CodeGen/avx512bw-builtins.c
  test/CodeGen/avx512f-builtins.c
  test/CodeGen/avx512vl-builtins.c
  test/CodeGen/avx512vlbw-builtins.c
  test/CodeGen/ssse3-builtins.c

Index: test/CodeGen/ssse3-builtins.c
===
--- test/CodeGen/ssse3-builtins.c
+++ test/CodeGen/ssse3-builtins.c
@@ -7,19 +7,25 @@
 
 __m128i test_mm_abs_epi8(__m128i a) {
   // CHECK-LABEL: test_mm_abs_epi8
-  // CHECK: call <16 x i8> @llvm.x86.ssse3.pabs.b.128(<16 x i8> %{{.*}})
+  // CHECK: [[SUB:%.+]] = sub <16 x i8> zeroinitializer, [[A:%.+]]
+  // CHECK: [[CMP:%.+]] = icmp sgt <16 x i8> [[A]], zeroinitializer
+  // CHECK: %{{.*}} = select <16 x i1> [[CMP]], <16 x i8> [[A]], <16 x i8> [[SUB]]
   return _mm_abs_epi8(a);
 }
 
 __m128i test_mm_abs_epi16(__m128i a) {
   // CHECK-LABEL: test_mm_abs_epi16
-  // CHECK: call <8 x i16> @llvm.x86.ssse3.pabs.w.128(<8 x i16> %{{.*}})
+  // CHECK: [[SUB:%.+]] = sub <8 x i16> zeroinitializer, [[A:%.+]]
+  // CHECK: [[CMP:%.+]] = icmp sgt <8 x i16> [[A]], zeroinitializer
+  // CHECK: %{{.*}} = select <8 x i1> [[CMP]], <8 x i16> [[A]], <8 x i16> [[SUB]]
   return _mm_abs_epi16(a);
 }
 
 __m128i test_mm_abs_epi32(__m128i a) {
   // CHECK-LABEL: test_mm_abs_epi32
-  // CHECK: call <4 x i32> @llvm.x86.ssse3.pabs.d.128(<4 x i32> %{{.*}})
+  // CHECK: [[SUB:%.+]] = sub <4 x i32> zeroinitializer, [[A:%.+]]
+  // CHECK: [[CMP:%.+]] = icmp sgt <4 x i32> [[A]], zeroinitializer
+  // CHECK: %{{.*}} = select <4 x i1> [[CMP]], <4 x i32> [[A]], <4 x i32> [[SUB]]
   return _mm_abs_epi32(a);
 }
 
Index: test/CodeGen/avx512vlbw-builtins.c
===
--- test/CodeGen/avx512vlbw-builtins.c
+++ test/CodeGen/avx512vlbw-builtins.c
@@ -898,57 +898,73 @@
 
 __m128i test_mm_mask_abs_epi8(__m128i __W, __mmask16 __U, __m128i __A) {
   // CHECK-LABEL: @test_mm_mask_abs_epi8
-  // CHECK: @llvm.x86.ssse3.pabs.b
-  // CHECK: select <16 x i1> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}
+  // CHECK: [[SUB:%.*]] = sub <16 x i8> zeroinitializer, [[A:%.*]]
+  // CHECK: [[CMP:%.*]] = icmp sgt <16 x i8> [[A]], zeroinitializer
+  // CHECK: [[SEL:%.*]] = select <16 x i1> [[CMP]], <16 x i8> [[A]], <16 x i8> [[SUB]]
+  // CHECK: select <16 x i1> %{{.*}}, <16 x i8> [[SEL]], <16 x i8> %{{.*}}
   return _mm_mask_abs_epi8(__W,__U,__A); 
 }
 
 __m128i test_mm_maskz_abs_epi8(__mmask16 __U, __m128i __A) {
   // CHECK-LABEL: @test_mm_maskz_abs_epi8
-  // CHECK: @llvm.x86.ssse3.pabs.b
-  // CHECK: select <16 x i1> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}
+  // CHECK: [[SUB:%.*]] = sub <16 x i8> zeroinitializer, [[A:%.*]]
+  // CHECK: [[CMP:%.*]] = icmp sgt <16 x i8> [[A]], zeroinitializer
+  // CHECK: [[SEL:%.*]] = select <16 x i1> [[CMP]], <16 x i8> [[A]], <16 x i8> [[SUB]]
+  // CHECK: select <16 x i1> %{{.*}}, <16 x i8> [[SEL]], <16 x i8> %{{.*}}
   return _mm_maskz_abs_epi8(__U,__A); 
 }
 
 __m256i test_mm256_mask_abs_epi8(__m256i __W, __mmask32 __U, __m256i __A) {
   // CHECK-LABEL: @test_mm256_mask_abs_epi8
-  // CHECK: @llvm.x86.avx2.pabs.b
-  // CHECK: select <32 x i1> %{{.*}}, <32 x i8> %{{.*}}, <32 x i8> %{{.*}}
+  // CHECK: [[SUB:%.*]] = sub <32 x i8> zeroinitializer, [[A:%.*]]
+  // CHECK: [[CMP:%.*]] = icmp sgt <32 x i8> [[A]], zeroinitializer
+  // CHECK: [[SEL:%.*]] = select <32 x i1> [[CMP]], <32 x i8> [[A]], <32 x i8> [[SUB]]
+  // CHECK: select <32 x i1> %{{.*}}, <32 x i8> [[SEL]], <32 x i8> %{{.*}}
   return _mm256_mask_abs_epi8(__W,__U,__A); 
 }
 
 __m256i test_mm256_maskz_abs_epi8(__mmask32 __U, __m256i __A) {
   // CHECK-LABEL: @test_mm256_maskz_abs_epi8
-  // CHECK: @llvm.x86.avx2.pabs.b
-  // CHECK: select <32 x i1> %{{.*}}, <32 x i8> %{{.*}}, <32 x i8> %{{.*}}
+  // CHECK: [[SUB:%.*]] = sub <32 x i8> zeroinitializer, [[A:%.*]]
+  // CHECK: [[CMP:%.*]] = icmp sgt <32 x i8> [[A]], zeroinitializer
+  // CHECK: [[SEL:%.*]] = select <32 x i1> [[CMP]], <32 x i8> [[A]], <32 x i8> [[SUB]]
+  // CHECK: select <32 x i1> %{{.*}}, <32 x i8> [[SEL]], <32 x i8> %{{.*}}
   return _mm256_maskz_abs_epi8(__U,__A); 
 }
 
 __m128i test_mm_mask_abs_epi16(__m128i __W, __mmask8 __U, __m128i __A) {
   // CHECK-LABEL: @test_mm_mask_abs_epi16
-  // CHECK: @llvm.x86.ssse3.pabs.w
-  // CHECK: select <8 x i1> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}
+  // CHECK: [[SUB:%.*]] = sub <8 x i16> zeroinitializer, [[A:%.*]]
+  // CHECK: [[CMP:%.*]] = icmp sgt <8 x i16> [[A]], zeroinitializer
+  // CHECK: [[SEL:%.*]] = select <8 x i1> [[CMP]], <8 x i16> [[A]], <8 x i16> [[SUB]]
+  // CHECK: select <8 x i1> %{{.*}}, <8 x i16> [[SEL]], <8 x i16> %{{.*}}
   return _mm_mask_abs_epi16(__W,__U,__A); 
 }
 
 __m128i test_mm_maskz_abs_epi16(__mmask8 __U, __m128i __A) {
   //

[PATCH] D37695: [clang-format] Break non-trailing comments, try 2

2017-09-11 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
Herald added a subscriber: klimek.

This patch enables `BreakableToken` to manage the formatting of non-trailing
block comments. It is a refinement of https://reviews.llvm.org/D37007.
We discovered that the optimizer outsmarts us on cases where breaking the 
comment
costs considerably less than breaking after the comment. This patch addresses
this by ensuring that a newline is inserted between a block comment and the next
token.


https://reviews.llvm.org/D37695

Files:
  lib/Format/BreakableToken.cpp
  lib/Format/BreakableToken.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/ContinuationIndenter.h
  unittests/Format/FormatTestComments.cpp
  unittests/Format/FormatTestJS.cpp

Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -65,6 +65,27 @@
 TEST_F(FormatTestJS, BlockComments) {
   verifyFormat("/* a */ aaa(\n"
"aaa);");
+  // Breaks after a single line block comment.
+  EXPECT_EQ("a = .ccc(\n"
+"/** @type_{!.rrr..LLL.lala} */\n"
+"mediaMessage);",
+format("a = .ccc(\n"
+   "/** "
+   "@type_{!.rrr..LLL.lala} */ "
+   "mediaMessage);",
+   getGoogleJSStyleWithColumns(70)));
+  // Breaks after a multiline block comment.
+  EXPECT_EQ(
+  "a = .ccc(\n"
+  "/**\n"
+  " * @type_{!.rrr..LLL.lala}\n"
+  " */\n"
+  "mediaMessage);",
+  format("a = .ccc(\n"
+ "/**\n"
+ " * @type_{!.rrr..LLL.lala}\n"
+ " */ mediaMessage);",
+ getGoogleJSStyleWithColumns(70)));
 }
 
 TEST_F(FormatTestJS, JSDocComments) {
Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -2407,6 +2407,57 @@
getLLVMStyleWithColumns(15)));
 }
 
+TEST_F(FormatTestComments, BreaksAfterMultilineBlockCommentsInParamLists) {
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  a);",
+format("a = f(/* long long */ a);", getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  a);",
+format("a = f(/* long\n"
+   " long\n"
+   "   */a);",
+   getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  a);",
+format("a = f(/* long\n"
+   " long\n"
+   "   */ a);",
+   getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  (1 + 1));",
+format("a = f(/* long\n"
+   " long\n"
+   "   */ (1 + 1));",
+   getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ(
+  "a = f(a,\n"
+  "  /* long\n"
+  " long\n"
+  "   */\n"
+  "  b);",
+  format("a = f(a, /* long long */ b);", getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ(
+  "a = f(a,\n"
+  "  /* long\n"
+  " long\n"
+  "   */\n"
+  "  (1 + 1));",
+  format("a = f(a, /* long long */ (1 + 1));", getLLVMStyleWithColumns(15)));
+}
+
 TEST_F(FormatTestComments, IndentLineCommentsInStartOfBlockAtEndOfFile) {
   verifyFormat("{\n"
"  // a\n"
Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -154,7 +154,8 @@
 NoLineBreakInOperand(false), LastOperatorWrapped(true),
 ContainsLineBreak(false), ContainsUnwrappedBuilder(false),
 AlignColons(true), ObjCSelectorNameFound(false),
-HasMultipleNestedBlocks(false), NestedBlockInlined(false) {}
+HasMultipleNestedBlocks(false), NestedBlockInlined(false),
+LastBlockCommentWasBroken(false) {}
 
   /// \brief The position to which a specific parenthesis level needs to be
   /// indented.
@@ -264,6 +265,10 @@
   // "function" in JavaScript) is not wrapped to a new line.
   bool NestedBlockInlined : 1;
 
+  // \brief \c true if the last block comment on this level was broken by
+  // \c breakProtrudingToken.
+  bool LastBlockCommentWasBroken : 1;
+
   bool operator<(const

r312918 - clang-format: [JS] wrap and indent `goog.setTestOnly` calls.

2017-09-11 Thread Martin Probst via cfe-commits
Author: mprobst
Date: Mon Sep 11 08:22:52 2017
New Revision: 312918

URL: http://llvm.org/viewvc/llvm-project?rev=312918&view=rev
Log:
clang-format: [JS] wrap and indent `goog.setTestOnly` calls.

Summary:
While `goog.setTestOnly` usually appears in the imports section of a file, it is
not actually an import, and also usually doesn't take long parameters (nor
namespaces as a parameter, it's a description/message that should be wrapped).

This fixes a regression where a `goog.setTestOnly` call nested in a function was
not wrapped.

Reviewers: djasper

Subscribers: klimek

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

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

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=312918&r1=312917&r2=312918&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Sep 11 08:22:52 2017
@@ -960,7 +960,6 @@ private:
Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
   Tok.Next->Next->TokenText == "provide" ||
   Tok.Next->Next->TokenText == "require" ||
-  Tok.Next->Next->TokenText == "setTestOnly" ||
   Tok.Next->Next->TokenText == "forwardDeclare") &&
Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
   }

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=312918&r1=312917&r2=312918&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Mon Sep 11 08:22:52 2017
@@ -558,8 +558,6 @@ TEST_F(FormatTestJS, GoogModules) {
getGoogleJSStyleWithColumns(40));
   verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
getGoogleJSStyleWithColumns(40));
-  verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');",
-   getGoogleJSStyleWithColumns(40));
   verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');",
getGoogleJSStyleWithColumns(40));
 
@@ -567,6 +565,12 @@ TEST_F(FormatTestJS, GoogModules) {
   verifyFormat(
   "var MyLongClassName =\n"
   "
goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
+  verifyFormat("function a() {\n"
+   "  goog.setTestOnly();\n"
+   "}\n",
+   "function a() {\n"
+   "goog.setTestOnly();\n"
+   "}\n");
 }
 
 TEST_F(FormatTestJS, FormatsNamespaces) {


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


[PATCH] D37695: [clang-format] Break non-trailing comments, try 2

2017-09-11 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 114617.
krasimir added a comment.

- Add the original test cases


https://reviews.llvm.org/D37695

Files:
  lib/Format/BreakableToken.cpp
  lib/Format/BreakableToken.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/ContinuationIndenter.h
  unittests/Format/FormatTestComments.cpp
  unittests/Format/FormatTestJS.cpp

Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -65,6 +65,27 @@
 TEST_F(FormatTestJS, BlockComments) {
   verifyFormat("/* a */ aaa(\n"
"aaa);");
+  // Breaks after a single line block comment.
+  EXPECT_EQ("a = .ccc(\n"
+"/** @type_{!.rrr..LLL.lala} */\n"
+"mediaMessage);",
+format("a = .ccc(\n"
+   "/** "
+   "@type_{!.rrr..LLL.lala} */ "
+   "mediaMessage);",
+   getGoogleJSStyleWithColumns(70)));
+  // Breaks after a multiline block comment.
+  EXPECT_EQ(
+  "a = .ccc(\n"
+  "/**\n"
+  " * @type_{!.rrr..LLL.lala}\n"
+  " */\n"
+  "mediaMessage);",
+  format("a = .ccc(\n"
+ "/**\n"
+ " * @type_{!.rrr..LLL.lala}\n"
+ " */ mediaMessage);",
+ getGoogleJSStyleWithColumns(70)));
 }
 
 TEST_F(FormatTestJS, JSDocComments) {
Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -2407,6 +2407,57 @@
getLLVMStyleWithColumns(15)));
 }
 
+TEST_F(FormatTestComments, BreaksAfterMultilineBlockCommentsInParamLists) {
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  a);",
+format("a = f(/* long long */ a);", getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  a);",
+format("a = f(/* long\n"
+   " long\n"
+   "   */a);",
+   getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  a);",
+format("a = f(/* long\n"
+   " long\n"
+   "   */ a);",
+   getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ("a = f(/* long\n"
+" long\n"
+"   */\n"
+"  (1 + 1));",
+format("a = f(/* long\n"
+   " long\n"
+   "   */ (1 + 1));",
+   getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ(
+  "a = f(a,\n"
+  "  /* long\n"
+  " long\n"
+  "   */\n"
+  "  b);",
+  format("a = f(a, /* long long */ b);", getLLVMStyleWithColumns(15)));
+
+  EXPECT_EQ(
+  "a = f(a,\n"
+  "  /* long\n"
+  " long\n"
+  "   */\n"
+  "  (1 + 1));",
+  format("a = f(a, /* long long */ (1 + 1));", getLLVMStyleWithColumns(15)));
+}
+
 TEST_F(FormatTestComments, IndentLineCommentsInStartOfBlockAtEndOfFile) {
   verifyFormat("{\n"
"  // a\n"
@@ -2805,6 +2856,22 @@
   getLLVMStyleWithColumns(80)));
   // clang-format on
 }
+
+TEST_F(FormatTestComments, NonTrailingBlockComments) {
+  verifyFormat("const /** comment comment */ A = B;",
+   getLLVMStyleWithColumns(40));
+
+  verifyFormat("const /** comment comment comment */ A =\n"
+   "B;",
+   getLLVMStyleWithColumns(40));
+
+  EXPECT_EQ("const /** comment comment comment\n"
+" comment */\n"
+"A = B;",
+format("const /** comment comment comment comment */\n"
+   "A = B;",
+   getLLVMStyleWithColumns(40)));
+}
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -154,7 +154,8 @@
 NoLineBreakInOperand(false), LastOperatorWrapped(true),
 ContainsLineBreak(false), ContainsUnwrappedBuilder(false),
 AlignColons(true), ObjCSelectorNameFound(false),
-HasMultipleNestedBlocks(false), NestedBlockInlined(false) {}
+HasMultipleNestedBlocks(false), NestedBlockInlined(false),
+LastBlockCommentWasBroken(false) {}
 
   /// \bri

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

2017-09-11 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

Yes, I meant that it should at least be controlled by a flag. However, adding 
flags to clang-format requires careful consideration, we usually would accept 
options that are necessary for commonly used styles with style guides and with 
a community willing to support these options.

So, I'd like to get the feedback from @djasper about it.


https://reviews.llvm.org/D37260



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


[PATCH] D33589: clang-format: consider not splitting tokens in optimization

2017-09-11 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

ping?


https://reviews.llvm.org/D33589



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


[PATCH] D33440: clang-format: better handle statement and namespace macros

2017-09-11 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

ping?


https://reviews.llvm.org/D33440



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


[PATCH] D32478: [clang-format] Fix AlignOperands when BreakBeforeBinaryOperators is set

2017-09-11 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

ping?


https://reviews.llvm.org/D32478



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


[PATCH] D34878: [ARM] Option for reading thread pointer from coprocessor register

2017-09-11 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic updated this revision to Diff 114618.
spetrovic added a comment.

Indentations fixed.


https://reviews.llvm.org/D34878

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Driver/CC1Options.td
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Arch/ARM.cpp
  lib/Driver/ToolChains/Arch/ARM.h
  test/Driver/clang-translation.c

Index: test/Driver/clang-translation.c
===
--- test/Driver/clang-translation.c
+++ test/Driver/clang-translation.c
@@ -87,6 +87,18 @@
 // ARMV5E: "-cc1"
 // ARMV5E: "-target-cpu" "arm1022e"
 
+// RUN: %clang -target arm-linux -mtp=cp15 -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER-HARD %s
+// ARMv7_THREAD_POINTER-HARD: "-target-feature" "+read-tp-hard"
+
+// RUN: %clang -target arm-linux -mtp=soft -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_SOFT %s
+// ARMv7_THREAD_POINTER_SOFT-NOT: "-target-feature" "+read-tp-hard"
+
+// RUN: %clang -target arm-linux -### -S %s -arch armv7 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_NON %s
+// ARMv7_THREAD_POINTER_NON-NOT: "-target-feature" "+read-tp-hard"
+
 // RUN: %clang -target powerpc64-unknown-linux-gnu \
 // RUN: -### -S %s -mcpu=G5 2>&1 | FileCheck -check-prefix=PPCG5 %s
 // PPCG5: clang
Index: lib/Driver/ToolChains/Arch/ARM.h
===
--- lib/Driver/ToolChains/Arch/ARM.h
+++ lib/Driver/ToolChains/Arch/ARM.h
@@ -32,14 +32,21 @@
 void appendEBLinkFlags(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs,
const llvm::Triple &Triple);
+enum class ReadTPMode {
+  Invalid,
+  Soft,
+  Cp15,
+};
+
 enum class FloatABI {
   Invalid,
   Soft,
   SoftFP,
   Hard,
 };
 
 FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args);
+ReadTPMode getReadTPMode(const ToolChain &TC, const llvm::opt::ArgList &Args);
 
 bool useAAPCSForMachO(const llvm::Triple &T);
 void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args,
Index: lib/Driver/ToolChains/Arch/ARM.cpp
===
--- lib/Driver/ToolChains/Arch/ARM.cpp
+++ lib/Driver/ToolChains/Arch/ARM.cpp
@@ -131,6 +131,26 @@
  T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
 }
 
+// Select mode for reading thread pointer (-mtp=soft/cp15).
+arm::ReadTPMode arm::getReadTPMode(const ToolChain &TC, const ArgList &Args) {
+  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
+const Driver &D = TC.getDriver();
+arm::ReadTPMode ThreadPointer =
+llvm::StringSwitch(A->getValue())
+.Case("cp15", ReadTPMode::Cp15)
+.Case("soft", ReadTPMode::Soft)
+.Default(ReadTPMode::Invalid);
+if (ThreadPointer != ReadTPMode::Invalid)
+  return ThreadPointer;
+if (StringRef(A->getValue()).empty())
+  D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
+else
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+return ReadTPMode::Invalid;
+  }
+  return ReadTPMode::Soft;
+}
+
 // Select the float ABI as determined by -msoft-float, -mhard-float, and
 // -mfloat-abi=.
 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
@@ -262,6 +282,7 @@
   bool KernelOrKext =
   Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
+  arm::ReadTPMode ThreadPointer = arm::getReadTPMode(TC, Args);
   const Arg *WaCPU = nullptr, *WaFPU = nullptr;
   const Arg *WaHDiv = nullptr, *WaArch = nullptr;
 
@@ -303,6 +324,9 @@
 }
   }
 
+  if (ThreadPointer == arm::ReadTPMode::Cp15)
+Features.push_back("+read-tp-hard");
+
   // Check -march. ClangAs gives preference to -Wa,-march=.
   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
   StringRef ArchName;
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1689,6 +1689,8 @@
   HelpText<"Disallow generation of data access to code sections (ARM only)">;
 def mno_execute_only : Flag<["-"], "mno-execute-only">, Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
+def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, Values<"soft, cp15">,
+  HelpText<"Read thread pointer from coprocessor register (ARM only)">;
 def mpure_code : Flag<["-"], "mpure-code">, Alias; // Alias for GCC compatibility
 def mno_pure_code : Flag<["-"], "mno-pure-code">, Alias;
 def mtvos_version_min_EQ : Joined<["-"], "mtvos-version-min=">, Group;
Index: include/clang/Driver/CC1Options.td
===
--- include/clang/Driver/CC1Options.td
+++ include/clang/Driver/CC1Options.td
@@ -257,6 +257,8 @@
"precision">;

[PATCH] D37577: [libclang] add 'clang_getCursorTLSKind'

2017-09-11 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd added inline comments.



Comment at: bindings/python/tests/cindex/test_tls_kind.py:14
+int tls_none;
+thread_local tls_dynamic;
+""", lang = 'cpp')

Can we add a test case for static TLS as well please?  Also, I think that we 
should add a test case for `__declspec(thread)`.



Comment at: tools/libclang/CIndex.cpp:7426
+}
+  }
+

This block is not properly formatted.  Please clang-format your code.


https://reviews.llvm.org/D37577



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


[libcxx] r312923 - Add include of to , since things in there return strings. Fixes PR#34529.

2017-09-11 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Sep 11 09:05:42 2017
New Revision: 312923

URL: http://llvm.org/viewvc/llvm-project?rev=312923&view=rev
Log:
Add include of  to , since things in there return 
strings. Fixes PR#34529.

Added:

libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/types.pass.cpp
  - copied, changed from r312922, 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp

libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/types.pass.cpp
  - copied, changed from r312922, 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/nothing_to_do.pass.cpp
Removed:

libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp

libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/nothing_to_do.pass.cpp
Modified:
libcxx/trunk/include/system_error

Modified: libcxx/trunk/include/system_error
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/system_error?rev=312923&r1=312922&r2=312923&view=diff
==
--- libcxx/trunk/include/system_error (original)
+++ libcxx/trunk/include/system_error Mon Sep 11 09:05:42 2017
@@ -230,6 +230,7 @@ template <> struct hash
 #include 
 #include <__functional_base>
+#include 
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header

Removed: 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp?rev=312922&view=auto
==
--- 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp
 (removed)
@@ -1,12 +0,0 @@
-//===--===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is dual licensed under the MIT and the University of Illinois Open
-// Source Licenses. See LICENSE.TXT for details.
-//
-//===--===//
-
-int main()
-{
-}

Copied: 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/types.pass.cpp
 (from r312922, 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/types.pass.cpp?p2=libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/types.pass.cpp&p1=libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp&r1=312922&r2=312923&rev=312923&view=diff
==
--- 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/nothing_to_do.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcode/syserr.errcode.overview/types.pass.cpp
 Mon Sep 11 09:05:42 2017
@@ -7,6 +7,17 @@
 //
 
//===--===//
 
+// 
+// class error_code
+
+// Make sure that the error_code bits of  are self-contained.
+
+#include 
+
 int main()
 {
+std::error_code x;
+(void) x.category();   // returns a std::error_category &
+(void) x.default_error_condition(); // std::error_condition
+(void) x.message();// returns a std::string
 }

Removed: 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/nothing_to_do.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/nothing_to_do.pass.cpp?rev=312922&view=auto
==
--- 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/nothing_to_do.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/diagnostics/syserr/syserr.errcondition/syserr.errcondition.overview/nothing_to_do.pass.cpp
 (removed)
@@ -1,12 +0,0 @@
-//===--===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is dual licensed under the MIT and the University of Illinois Open
-// Source Licenses. See LICENSE.TXT for details.
-//
-//===--===//
-
-int main()
-{
-}

Copied: 
libcxx/trunk/test/std/diagnostics/syserr/syserr

[PATCH] D37376: [libcxx] Fix libc++experimental build on Windows

2017-09-11 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd requested changes to this revision.
compnerd added inline comments.
This revision now requires changes to proceed.



Comment at: lib/CMakeLists.txt:189
 
+macro(add_msvcrt_defs_if_needed target)
+  if(WIN32 AND NOT MINGW)

Please use `function` rather than `macro`.  There is no need to pollute the 
namespace here.


https://reviews.llvm.org/D37376



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


[PATCH] D37668: [X86][intrinsics] lower _mm[256|512]_mask[z]_set1_epi[8|16|32|64] intrinsic to IR

2017-09-11 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

I think when you uploaded the changes to remove it from BuiltinsX86.def you 
lost your earlier changes to the header files


https://reviews.llvm.org/D37668



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


[PATCH] D37562: [X86] Lower _mm[256|512]_[mask[z]]_avg_epu[8|16] intrinsics to native llvm IR

2017-09-11 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM


https://reviews.llvm.org/D37562



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


[PATCH] D37667: [C++14][Sema] Disallow decltype(auto) deduction for lambdas

2017-09-11 Thread Blitz Rakete via Phabricator via cfe-commits
Rakete abandoned this revision.
Rakete added a comment.

Agreed. Closing this.


https://reviews.llvm.org/D37667



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


[PATCH] D37694: [X86] [PATCH] [intrinsics] Lowering X86 ABS intrinsics to IR. (clang)

2017-09-11 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

Remove the builtins from BuiltinsX86.def


https://reviews.llvm.org/D37694



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


[PATCH] D37677: [libc++] implement future synchronization using atomic_flag

2017-09-11 Thread Dennis Luxen via Phabricator via cfe-commits
dennis.luxen added a comment.

In https://reviews.llvm.org/D37677#866362, @bcraig wrote:

> Is there a benchmark where this demonstrates some performance improvement?  I 
> fear that the switch to condition_variable_any will swamp any performance 
> gains from the switch to a spin lock.
>
> Also, the spin lock is being held during allocating operations (the exception 
> throws and at_thread_exit code).  That's a little long to be holding a spin 
> lock.


Thanks @bcraig, I will devise a benchmark and report back with its numbers for 
X86_64.


https://reviews.llvm.org/D37677



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


[PATCH] D37577: [libclang] add 'clang_getCursorTLSKind'

2017-09-11 Thread Masud Rahman via Phabricator via cfe-commits
frutiger added inline comments.



Comment at: bindings/python/tests/cindex/test_tls_kind.py:14
+int tls_none;
+thread_local tls_dynamic;
+""", lang = 'cpp')

compnerd wrote:
> Can we add a test case for static TLS as well please?  Also, I think that we 
> should add a test case for `__declspec(thread)`.
I will add a test case for static TLS.

`__declspec(thread)` is not implemented as a TLS kind on a cursor; instead it 
is implemented as a child attribute of the cursor.  Would you like me to add a 
test case for that here?



Comment at: tools/libclang/CIndex.cpp:7426
+}
+  }
+

compnerd wrote:
> This block is not properly formatted.  Please clang-format your code.
I will fix this, thank you for the feedback.


https://reviews.llvm.org/D37577



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


[PATCH] D37448: Fix cast assertion on MS inline assembly with vector spills (PR34021)

2017-09-11 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

I was hoping for a test case that didn't require assertions, but this is enough 
to land the fix.


Repository:
  rL LLVM

https://reviews.llvm.org/D37448



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


[PATCH] D37577: [libclang] add 'clang_getCursorTLSKind'

2017-09-11 Thread Masud Rahman via Phabricator via cfe-commits
frutiger added inline comments.



Comment at: bindings/python/tests/cindex/test_tls_kind.py:14
+int tls_none;
+thread_local tls_dynamic;
+""", lang = 'cpp')

frutiger wrote:
> compnerd wrote:
> > Can we add a test case for static TLS as well please?  Also, I think that 
> > we should add a test case for `__declspec(thread)`.
> I will add a test case for static TLS.
> 
> `__declspec(thread)` is not implemented as a TLS kind on a cursor; instead it 
> is implemented as a child attribute of the cursor.  Would you like me to add 
> a test case for that here?
Please ignore the above comment regarding `__declspec(thread)`, it does indeed 
add a static TLS kind to the cursor.


https://reviews.llvm.org/D37577



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


[PATCH] D37700: Fix recording preamble's conditional stack in skipped PP branches.

2017-09-11 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.

This fixes PR34547.
`Lexer::LexEndOfFile` handles recording of ConditionalStack for
preamble and reporting errors about unmatched conditionalal PP
directives.
However, SkipExcludedConditionalBlock contianed duplicated logic for
reporting errors and clearing ConditionalStack, but not for preamble
recording.

This fix removes error reporting logic from
`SkipExcludedConditionalBlock`, unmatched PP conditionals are now
reported inside `Lexer::LexEndOfFile`.


https://reviews.llvm.org/D37700

Files:
  lib/Lex/PPDirectives.cpp
  test/Index/preamble-conditionals-inverted-with-error.cpp
  test/Index/preamble-conditionals-inverted.cpp


Index: test/Index/preamble-conditionals-inverted.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s --implicit-check-not "error:"
+#ifdef FOO_H
+
+void foo();
+
+#endif
Index: test/Index/preamble-conditionals-inverted-with-error.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted-with-error.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s
+#ifdef FOO_H
+
+void foo();
+
+// CHECK: preamble-conditionals-inverted-with-error.cpp:4:2: error: 
unterminated conditional directive
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -381,15 +381,8 @@
 
 // If this is the end of the buffer, we have an error.
 if (Tok.is(tok::eof)) {
-  // Emit errors for each unterminated conditional on the stack, including
-  // the current one.
-  while (!CurPPLexer->ConditionalStack.empty()) {
-if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
-  Diag(CurPPLexer->ConditionalStack.back().IfLoc,
-   diag::err_pp_unterminated_conditional);
-CurPPLexer->ConditionalStack.pop_back();
-  }
-
+  // We don't emit errors for unterminated conditionals here,
+  // Lexer::LexEndOfFile can do that propertly.
   // Just return and let the caller lex after this #include.
   break;
 }


Index: test/Index/preamble-conditionals-inverted.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s --implicit-check-not "error:"
+#ifdef FOO_H
+
+void foo();
+
+#endif
Index: test/Index/preamble-conditionals-inverted-with-error.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted-with-error.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s
+#ifdef FOO_H
+
+void foo();
+
+// CHECK: preamble-conditionals-inverted-with-error.cpp:4:2: error: unterminated conditional directive
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -381,15 +381,8 @@
 
 // If this is the end of the buffer, we have an error.
 if (Tok.is(tok::eof)) {
-  // Emit errors for each unterminated conditional on the stack, including
-  // the current one.
-  while (!CurPPLexer->ConditionalStack.empty()) {
-if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
-  Diag(CurPPLexer->ConditionalStack.back().IfLoc,
-   diag::err_pp_unterminated_conditional);
-CurPPLexer->ConditionalStack.pop_back();
-  }
-
+  // We don't emit errors for unterminated conditionals here,
+  // Lexer::LexEndOfFile can do that propertly.
   // Just return and let the caller lex after this #include.
   break;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37700: Fix recording preamble's conditional stack in skipped PP branches.

2017-09-11 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 114634.
ilya-biryukov added a comment.

Fixed description of the change.


https://reviews.llvm.org/D37700

Files:
  lib/Lex/PPDirectives.cpp
  test/Index/preamble-conditionals-inverted-with-error.cpp
  test/Index/preamble-conditionals-inverted.cpp


Index: test/Index/preamble-conditionals-inverted.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s --implicit-check-not "error:"
+#ifdef FOO_H
+
+void foo();
+
+#endif
Index: test/Index/preamble-conditionals-inverted-with-error.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted-with-error.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s
+#ifdef FOO_H
+
+void foo();
+
+// CHECK: preamble-conditionals-inverted-with-error.cpp:4:2: error: 
unterminated conditional directive
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -381,15 +381,8 @@
 
 // If this is the end of the buffer, we have an error.
 if (Tok.is(tok::eof)) {
-  // Emit errors for each unterminated conditional on the stack, including
-  // the current one.
-  while (!CurPPLexer->ConditionalStack.empty()) {
-if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
-  Diag(CurPPLexer->ConditionalStack.back().IfLoc,
-   diag::err_pp_unterminated_conditional);
-CurPPLexer->ConditionalStack.pop_back();
-  }
-
+  // We don't emit errors for unterminated conditionals here,
+  // Lexer::LexEndOfFile can do that propertly.
   // Just return and let the caller lex after this #include.
   break;
 }


Index: test/Index/preamble-conditionals-inverted.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s --implicit-check-not "error:"
+#ifdef FOO_H
+
+void foo();
+
+#endif
Index: test/Index/preamble-conditionals-inverted-with-error.cpp
===
--- /dev/null
+++ test/Index/preamble-conditionals-inverted-with-error.cpp
@@ -0,0 +1,8 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source-reparse 5 \
+// RUN:   local -std=c++14 %s 2>&1 \
+// RUN: | FileCheck %s
+#ifdef FOO_H
+
+void foo();
+
+// CHECK: preamble-conditionals-inverted-with-error.cpp:4:2: error: unterminated conditional directive
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -381,15 +381,8 @@
 
 // If this is the end of the buffer, we have an error.
 if (Tok.is(tok::eof)) {
-  // Emit errors for each unterminated conditional on the stack, including
-  // the current one.
-  while (!CurPPLexer->ConditionalStack.empty()) {
-if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
-  Diag(CurPPLexer->ConditionalStack.back().IfLoc,
-   diag::err_pp_unterminated_conditional);
-CurPPLexer->ConditionalStack.pop_back();
-  }
-
+  // We don't emit errors for unterminated conditionals here,
+  // Lexer::LexEndOfFile can do that propertly.
   // Just return and let the caller lex after this #include.
   break;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37677: [libc++] implement future synchronization using atomic_flag

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

TODO.txt says "future should use  for synchronization." I would have 
interpreted this as meaning that the line

  unsigned __state_;

should become

  std::atomic __state_;

and appropriate loads and stores used so that `__is_ready()` can be checked 
without having to take the mutex first. OTOH, I don't actually see how that 
would help: if it's not ready, you probably want to take a unique_lock so you 
can wait, and if it *is* ready, you probably want to take a lock so that you 
can get the value out.
Atomics might allow functions like `__set_future_attached()` to stop taking the 
lock as well. But again I'm not sure what the benefit would be; the cost is 
obviously "risk of subtle bugs and maintenance nightmare."

This current patch just swaps out std::mutex for a std::mutex-alike class that 
claims to be faster for uncontested accesses. Definitely safer than my 
interpretation. :) If this patch actually helps, then I would offer that the 
class could be provided as a reusable class `std::__spin_lock` in the  
header instead of being hidden inside `__assoc_shared_state`.


https://reviews.llvm.org/D37677



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


Re: r312580 - Fix memory leak after r312467. The ModuleMap is the owner of the global module object until it's reparented under a real module.

2017-09-11 Thread David Blaikie via cfe-commits
On Tue, Sep 5, 2017 at 2:47 PM Richard Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: rsmith
> Date: Tue Sep  5 14:46:22 2017
> New Revision: 312580
>
> URL: http://llvm.org/viewvc/llvm-project?rev=312580&view=rev
> Log:
> Fix memory leak after r312467. The ModuleMap is the owner of the global
> module object until it's reparented under a real module.
>
> Modified:
> cfe/trunk/include/clang/Lex/ModuleMap.h
> cfe/trunk/lib/Lex/ModuleMap.cpp
>
> Modified: cfe/trunk/include/clang/Lex/ModuleMap.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/ModuleMap.h?rev=312580&r1=312579&r2=312580&view=diff
>
> ==
> --- cfe/trunk/include/clang/Lex/ModuleMap.h (original)
> +++ cfe/trunk/include/clang/Lex/ModuleMap.h Tue Sep  5 14:46:22 2017
> @@ -82,22 +82,26 @@ class ModuleMap {
>
>/// \brief The directory used for Clang-supplied, builtin include
> headers,
>/// such as "stdint.h".
> -  const DirectoryEntry *BuiltinIncludeDir;
> +  const DirectoryEntry *BuiltinIncludeDir = nullptr;
>
>/// \brief Language options used to parse the module map itself.
>///
>/// These are always simple C language options.
>LangOptions MMapLangOpts;
>
> -  // The module that the main source file is associated with (the module
> -  // named LangOpts::CurrentModule, if we've loaded it).
> -  Module *SourceModule;
> +  /// The module that the main source file is associated with (the module
> +  /// named LangOpts::CurrentModule, if we've loaded it).
> +  Module *SourceModule = nullptr;
> +
> +  /// The global module for the current TU, if we still own it.
> (Ownership is
> +  /// transferred if/when we create an enclosing module.
> +  std::unique_ptr PendingGlobalModule;
>
>/// \brief The top-level modules that are known.
>llvm::StringMap Modules;
>
>/// \brief The number of modules we have created in total.
> -  unsigned NumCreatedModules;
> +  unsigned NumCreatedModules = 0;
>
>  public:
>/// \brief Flags describing the role of a module header.
>
> Modified: cfe/trunk/lib/Lex/ModuleMap.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/ModuleMap.cpp?rev=312580&r1=312579&r2=312580&view=diff
>
> ==
> --- cfe/trunk/lib/Lex/ModuleMap.cpp (original)
> +++ cfe/trunk/lib/Lex/ModuleMap.cpp Tue Sep  5 14:46:22 2017
> @@ -256,8 +256,7 @@ ModuleMap::ModuleMap(SourceManager &Sour
>   const LangOptions &LangOpts, const TargetInfo
> *Target,
>   HeaderSearch &HeaderInfo)
>  : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts),
> Target(Target),
> -  HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
> -  SourceModule(nullptr), NumCreatedModules(0) {
> +  HeaderInfo(HeaderInfo) {
>MMapLangOpts.LineComment = true;
>  }
>
> @@ -747,10 +746,12 @@ std::pair ModuleMap::fin
>  }
>
>  Module *ModuleMap::createGlobalModuleForInterfaceUnit(SourceLocation Loc)
> {
> -  auto *Result = new Module("", Loc, nullptr, /*IsFramework*/
> false,
> -/*IsExplicit*/ true, NumCreatedModules++);
> -  Result->Kind = Module::GlobalModuleFragment;
> -  return Result;
> +  assert(!PendingGlobalModule && "created multiple global modules");
> +  PendingGlobalModule.reset(
> +  new Module("", Loc, nullptr, /*IsFramework*/ false,
> + /*IsExplicit*/ true, NumCreatedModules++));
> +  PendingGlobalModule->Kind = Module::GlobalModuleFragment;
> +  return PendingGlobalModule.get();
>  }
>
>  Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
> @@ -766,7 +767,10 @@ Module *ModuleMap::createModuleForInterf
>Modules[Name] = SourceModule = Result;
>
>// Reparent the current global module fragment as a submodule of this
> module.
> +  assert(GlobalModule == PendingGlobalModule.get() &&
> + "unexpected global module");
>GlobalModule->setParent(Result);
> +  PendingGlobalModule.release(); // now owned by parent
>

Would it be reasonable to reverse the 'setParent' API (into an addSubmodule
call on the parent - that takes the child/submodule by std::unique_ptr
value) so the hand-off/ownership is more clear/less error prone?


>
>// Mark the main source file as being within the newly-created module
> so that
>// declarations and macros are properly visibility-restricted to it.
>
>
> ___
> 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] D37101: [clangd] Add support for snippet completions

2017-09-11 Thread Raoul Wols via Phabricator via cfe-commits
rwols added a comment.

No, I don't have access to the repo, sorry forgot to mention this.


https://reviews.llvm.org/D37101



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


[PATCH] D37677: [libc++] implement future synchronization using atomic_flag

2017-09-11 Thread Ben Craig via Phabricator via cfe-commits
bcraig added a comment.

In https://reviews.llvm.org/D37677#866743, @Quuxplusone wrote:

> This current patch just swaps out std::mutex for a std::mutex-alike class 
> that claims to be faster for uncontested accesses. Definitely safer than my 
> interpretation. :) If this patch actually helps, then I would offer that the 
> class could be provided as a reusable class `std::__spin_lock` in the  
> header instead of being hidden inside `__assoc_shared_state`.


I think the bar for accepting this should be significantly faster, and not just 
a little faster.  Spinlocks don't behave as well as mutexes in abnormal 
conditions.  Spinlocks are more likely to cause priority inversion.  They are 
more likely to cause throughput issues when there is a lot of contention, as 
the spinlock'd thread will consume a full time slice before relinquishing a 
cpu.  On Windows, CRITICAL_SECTION and SRWLOCK become electrified 
 during 
process termination to avoid indefinite hangs.  We shouldn't give all of that 
up for a minor perf gain.  We might give it up for a large perf gain though.


https://reviews.llvm.org/D37677



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


[libcxx] r312932 - mark mersenne_twister_engine<>::seed(result_type __sd) with _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK to placate UBSAN. Fixes PR#34160

2017-09-11 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Sep 11 11:10:33 2017
New Revision: 312932

URL: http://llvm.org/viewvc/llvm-project?rev=312932&view=rev
Log:
mark mersenne_twister_engine<>::seed(result_type __sd) with 
_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK to placate UBSAN. Fixes PR#34160



Modified:
libcxx/trunk/include/random

Modified: libcxx/trunk/include/random
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/random?rev=312932&r1=312931&r2=312932&view=diff
==
--- libcxx/trunk/include/random (original)
+++ libcxx/trunk/include/random Mon Sep 11 11:10:33 2017
@@ -2308,6 +2308,7 @@ template ::seed(result_type __sd)
+_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
 {   // __w >= 2
 __x_[0] = __sd & _Max;
 for (size_t __i = 1; __i < __n; ++__i)


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


[PATCH] D37577: [libclang] add 'clang_getCursorTLSKind'

2017-09-11 Thread Masud Rahman via Phabricator via cfe-commits
frutiger updated this revision to Diff 114640.
frutiger added a comment.

Add test cases for `__declspec(thread)` and static TLS.  Clean up formatting to 
adhere to the project style.


https://reviews.llvm.org/D37577

Files:
  bindings/python/clang/cindex.py
  bindings/python/tests/cindex/test_tls_kind.py
  include/clang-c/Index.h
  tools/libclang/CIndex.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -189,6 +189,7 @@
 clang_getCursorResultType
 clang_getCursorSemanticParent
 clang_getCursorSpelling
+clang_getCursorTLSKind
 clang_getCursorType
 clang_getCursorUSR
 clang_getCursorVisibility
Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -7412,6 +7412,22 @@
   return CXLanguage_Invalid;
 }
 
+CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
+  const Decl *D = cxcursor::getCursorDecl(cursor);
+  if (const VarDecl *VD = dyn_cast(D)) {
+switch (VD->getTLSKind()) {
+case VarDecl::TLS_None:
+  return CXTLS_None;
+case VarDecl::TLS_Dynamic:
+  return CXTLS_Dynamic;
+case VarDecl::TLS_Static:
+  return CXTLS_Static;
+}
+  }
+
+  return CXTLS_None;
+}
+
  /// \brief If the given cursor is the "templated" declaration
  /// descibing a class or function template, return the class or
  /// function template.
Index: include/clang-c/Index.h
===
--- include/clang-c/Index.h
+++ include/clang-c/Index.h
@@ -2836,6 +2836,20 @@
  */
 CINDEX_LINKAGE enum CXLanguageKind clang_getCursorLanguage(CXCursor cursor);
 
+/**
+ * \brief Describe the "TLS kind" of the declaration referred to by a cursor.
+ */
+enum CXTLSKind {
+  CXTLS_None = 0,
+  CXTLS_Dynamic,
+  CXTLS_Static
+};
+
+/**
+ * \brief Determine the "TLS kind" of the declaration referred to by a cursor.
+ */
+CINDEX_LINKAGE enum CXTLSKind clang_getCursorTLSKind(CXCursor cursor);
+
 /**
  * \brief Returns the translation unit that a cursor originated from.
  */
Index: bindings/python/tests/cindex/test_tls_kind.py
===
--- /dev/null
+++ bindings/python/tests/cindex/test_tls_kind.py
@@ -0,0 +1,36 @@
+
+from clang.cindex import TLSKind
+from clang.cindex import Cursor
+from clang.cindex import TranslationUnit
+
+from .util import get_cursor
+from .util import get_tu
+
+def test_tls_kind():
+"""Ensure that linkage specifers are available on cursors"""
+
+tu = get_tu("""
+int tls_none;
+thread_local int tls_dynamic;
+_Thread_local int tls_static;
+""", lang = 'cpp')
+
+tls_none = get_cursor(tu.cursor, 'tls_none')
+assert tls_none.tls_kind == TLSKind.NONE;
+
+tls_dynamic = get_cursor(tu.cursor, 'tls_dynamic')
+assert tls_dynamic.tls_kind == TLSKind.DYNAMIC
+
+tls_static = get_cursor(tu.cursor, 'tls_static')
+assert tls_static.tls_kind == TLSKind.STATIC
+
+# The following case tests '__declspec(thread)'.  Since it is a Microsoft
+# specific extension, specific flags are required for the parser to pick
+# these up.
+tu = get_tu("""
+__declspec(thread) int tls_declspec;
+""", lang = 'cpp', flags=['-fms-extensions', '-target', 'amd64-win32'])
+
+tls_declspec = get_cursor(tu.cursor, 'tls_declspec')
+assert tls_declspec.tls_kind == TLSKind.STATIC
+
Index: bindings/python/clang/cindex.py
===
--- bindings/python/clang/cindex.py
+++ bindings/python/clang/cindex.py
@@ -1548,6 +1548,14 @@
 
 return self._loc
 
+@property
+def tls_kind(self):
+"""Return the TLS kind of this cursor."""
+if not hasattr(self, '_tls_kind'):
+self._tls_kind = conf.lib.clang_getCursorTLSKind(self)
+
+return TLSKind.from_id(self._tls_kind)
+
 @property
 def extent(self):
 """
@@ -2061,6 +2069,23 @@
 RefQualifierKind.LVALUE = RefQualifierKind(1)
 RefQualifierKind.RVALUE = RefQualifierKind(2)
 
+class TLSKind(BaseEnumeration):
+"""Describes the kind of thread local storage of a cursor."""
+
+# The unique kind objects, indexed by id.
+_kinds = []
+_name_map = None
+
+def from_param(self):
+return self.value
+
+def __repr__(self):
+return 'TLSKind.%s' % (self.name,)
+
+TLSKind.NONE = TLSKind(0)
+TLSKind.DYNAMIC = TLSKind(1)
+TLSKind.STATIC = TLSKind(2)
+
 class Type(Structure):
 """
 The type of an element in the abstract syntax tree.
@@ -4066,6 +4091,7 @@
 'Index',
 'SourceLocation',
 'SourceRange',
+'TLSKind',
 'TokenKind',
 'Token',
 'TranslationUnitLoadError',
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-com

[PATCH] D37703: [AMDGPU] Change addr space of clk_event_t, queue_t and reserve_id_t to global

2017-09-11 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
Herald added subscribers: t-tye, tpr, dstuttard, nhaehnle, wdng, kzhuravl.

https://reviews.llvm.org/D37703

Files:
  lib/Basic/Targets/AMDGPU.h
  test/CodeGenOpenCL/opencl_types.cl


Index: test/CodeGenOpenCL/opencl_types.cl
===
--- test/CodeGenOpenCL/opencl_types.cl
+++ test/CodeGenOpenCL/opencl_types.cl
@@ -1,13 +1,13 @@
-// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "spir-unknown-unknown" -emit-llvm 
-o - -O0 | FileCheck %s --check-prefix=CHECK-SPIR
-// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "amdgcn--amdhsa" -emit-llvm -o - 
-O0 | FileCheck %s --check-prefix=CHECK-AMDGCN
+// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "spir-unknown-unknown" -emit-llvm 
-o - -O0 | FileCheck %s --check-prefixes=CHECK-COM,CHECK-SPIR
+// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "amdgcn--amdhsa" -emit-llvm -o - 
-O0 | FileCheck %s --check-prefixes=CHECK-COM,CHECK-AMDGCN
 
 #define CLK_ADDRESS_CLAMP_TO_EDGE   2
 #define CLK_NORMALIZED_COORDS_TRUE  1
 #define CLK_FILTER_NEAREST  0x10
 #define CLK_FILTER_LINEAR   0x20
 
 constant sampler_t glb_smp = 
CLK_ADDRESS_CLAMP_TO_EDGE|CLK_NORMALIZED_COORDS_TRUE|CLK_FILTER_NEAREST;
-// CHECK-SPIR-NOT: constant i32
+// CHECK-COM-NOT: constant i32
 
 void fnc1(image1d_t img) {}
 // CHECK-SPIR: @fnc1(%opencl.image1d_ro_t addrspace(1)*
@@ -39,20 +39,23 @@
 
 kernel void foo(image1d_t img) {
   sampler_t smp = 
CLK_ADDRESS_CLAMP_TO_EDGE|CLK_NORMALIZED_COORDS_TRUE|CLK_FILTER_LINEAR;
-  // CHECK-SPIR: alloca %opencl.sampler_t addrspace(2)*
+  // CHECK-COM: alloca %opencl.sampler_t addrspace(2)*
   event_t evt;
-  // CHECK-SPIR: alloca %opencl.event_t*
+  // CHECK-COM: alloca %opencl.event_t*
   clk_event_t clk_evt;
   // CHECK-SPIR: alloca %opencl.clk_event_t*
+  // CHECK-AMDGCN: alloca %opencl.clk_event_t addrspace(1)*
   queue_t queue;
   // CHECK-SPIR: alloca %opencl.queue_t*
+  // CHECK-AMDGCN: alloca %opencl.queue_t addrspace(1)*
   reserve_id_t rid;
   // CHECK-SPIR: alloca %opencl.reserve_id_t*
-  // CHECK-SPIR: store %opencl.sampler_t addrspace(2)*
+  // CHECK-AMDGCN: alloca %opencl.reserve_id_t addrspace(1)*
+  // CHECK-COM: store %opencl.sampler_t addrspace(2)*
   fnc4smp(smp);
-  // CHECK-SPIR: call {{.*}}void @fnc4smp(%opencl.sampler_t addrspace(2)*
+  // CHECK-COM: call {{.*}}void @fnc4smp(%opencl.sampler_t addrspace(2)*
   fnc4smp(glb_smp);
-  // CHECK-SPIR: call {{.*}}void @fnc4smp(%opencl.sampler_t addrspace(2)*
+  // CHECK-COM: call {{.*}}void @fnc4smp(%opencl.sampler_t addrspace(2)*
 }
 
 kernel void foo_pipe(read_only pipe int p) {}
Index: lib/Basic/Targets/AMDGPU.h
===
--- lib/Basic/Targets/AMDGPU.h
+++ lib/Basic/Targets/AMDGPU.h
@@ -202,6 +202,10 @@
   case BuiltinType::Id:
\
 return LangAS::opencl_constant;
 #include "clang/Basic/OpenCLImageTypes.def"
+case BuiltinType::OCLClkEvent:
+case BuiltinType::OCLQueue:
+case BuiltinType::OCLReserveID:
+  return LangAS::opencl_global;
 
 default:
   return TargetInfo::getOpenCLTypeAddrSpace(T);


Index: test/CodeGenOpenCL/opencl_types.cl
===
--- test/CodeGenOpenCL/opencl_types.cl
+++ test/CodeGenOpenCL/opencl_types.cl
@@ -1,13 +1,13 @@
-// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "spir-unknown-unknown" -emit-llvm -o - -O0 | FileCheck %s --check-prefix=CHECK-SPIR
-// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "amdgcn--amdhsa" -emit-llvm -o - -O0 | FileCheck %s --check-prefix=CHECK-AMDGCN
+// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "spir-unknown-unknown" -emit-llvm -o - -O0 | FileCheck %s --check-prefixes=CHECK-COM,CHECK-SPIR
+// RUN: %clang_cc1 -cl-std=CL2.0 %s -triple "amdgcn--amdhsa" -emit-llvm -o - -O0 | FileCheck %s --check-prefixes=CHECK-COM,CHECK-AMDGCN
 
 #define CLK_ADDRESS_CLAMP_TO_EDGE   2
 #define CLK_NORMALIZED_COORDS_TRUE  1
 #define CLK_FILTER_NEAREST  0x10
 #define CLK_FILTER_LINEAR   0x20
 
 constant sampler_t glb_smp = CLK_ADDRESS_CLAMP_TO_EDGE|CLK_NORMALIZED_COORDS_TRUE|CLK_FILTER_NEAREST;
-// CHECK-SPIR-NOT: constant i32
+// CHECK-COM-NOT: constant i32
 
 void fnc1(image1d_t img) {}
 // CHECK-SPIR: @fnc1(%opencl.image1d_ro_t addrspace(1)*
@@ -39,20 +39,23 @@
 
 kernel void foo(image1d_t img) {
   sampler_t smp = CLK_ADDRESS_CLAMP_TO_EDGE|CLK_NORMALIZED_COORDS_TRUE|CLK_FILTER_LINEAR;
-  // CHECK-SPIR: alloca %opencl.sampler_t addrspace(2)*
+  // CHECK-COM: alloca %opencl.sampler_t addrspace(2)*
   event_t evt;
-  // CHECK-SPIR: alloca %opencl.event_t*
+  // CHECK-COM: alloca %opencl.event_t*
   clk_event_t clk_evt;
   // CHECK-SPIR: alloca %opencl.clk_event_t*
+  // CHECK-AMDGCN: alloca %opencl.clk_event_t addrspace(1)*
   queue_t queue;
   // CHECK-SPIR: alloca %opencl.queue_t*
+  // CHECK-AMDGCN: alloca %opencl.queue_t addrspace(1)*
   reserve_id_t rid;

[PATCH] D37196: [Clang] Bug 32352 - Provide a way for OptimizationRemarkEmitter::allowExtraAnalysis to check if (specific) remarks are enabled

2017-09-11 Thread Vivek Pandya via Phabricator via cfe-commits
vivekvpandya marked an inline comment as done.
vivekvpandya added inline comments.



Comment at: lib/CodeGen/CodeGenAction.cpp:882-883
   BEConsumer = Result.get();
-
+  VMContext->setDiagnosticHandler(llvm::make_unique(
+  CI.getCodeGenOpts(), Result.get()));
   // Enable generating macro debug info only when debug info is not disabled 
and

anemet wrote:
> Any reason you moved where we set this up?
 

  #  At older place I was not able to define ClangDiagnosticHandler class as it 
will require definition of BackendComsumer and vice versa.
  # and this seems to be appropriate place to create and tie DiagnosticHandler 
to LLVMContext

 
But I am not sure about why old diagnostic handler was tied back to  context 
that is why I wanted someone from clang to look at this.




https://reviews.llvm.org/D37196



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


[PATCH] D37196: [Clang] Bug 32352 - Provide a way for OptimizationRemarkEmitter::allowExtraAnalysis to check if (specific) remarks are enabled

2017-09-11 Thread Vivek Pandya via Phabricator via cfe-commits
vivekvpandya updated this revision to Diff 114645.
vivekvpandya added a comment.

Update


https://reviews.llvm.org/D37196

Files:
  lib/CodeGen/CodeGenAction.cpp


Index: lib/CodeGen/CodeGenAction.cpp
===
--- lib/CodeGen/CodeGenAction.cpp
+++ lib/CodeGen/CodeGenAction.cpp
@@ -224,10 +224,6 @@
   void *OldContext = Ctx.getInlineAsmDiagnosticContext();
   Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
 
-  LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
-  Ctx.getDiagnosticHandler();
-  void *OldDiagnosticContext = Ctx.getDiagnosticContext();
-  Ctx.setDiagnosticHandler(DiagnosticHandler, this);
   Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
   if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
 Ctx.setDiagnosticsHotnessThreshold(
@@ -264,8 +260,6 @@
 
   Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
 
-  Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
-
   if (OptRecordFile)
 OptRecordFile->keep();
 }
@@ -299,11 +293,6 @@
   ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
 }
 
-static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
-  void *Context) {
-  ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
-}
-
 /// Get the best possible source location to represent a diagnostic that
 /// may have associated debug info.
 const FullSourceLoc
@@ -756,6 +745,33 @@
 }
 #undef ComputeDiagID
 
+class ClangDiagnosticHandler final : public DiagnosticHandler {
+public:
+  ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
+  : CodeGenOpts(CGOpts), BackendCon(BCon) {}
+
+  bool handleDiagnostics(const DiagnosticInfo &DI) override {
+BackendCon->DiagnosticHandlerImpl(DI);
+return true;
+  }
+  bool isAnalysisRemarkEnable(const std::string &PassName) {
+return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
+CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
+  }
+  bool isMissedOptRemarkEnable(const std::string &PassName) {
+return (CodeGenOpts.OptimizationRemarkMissedPattern &&
+CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
+  }
+  bool isPassedOptRemarkEnable(const std::string &PassName) {
+return (CodeGenOpts.OptimizationRemarkPattern &&
+CodeGenOpts.OptimizationRemarkPattern->match(PassName));
+  }
+
+private:
+  const CodeGenOptions &CodeGenOpts;
+  BackendConsumer *BackendCon;
+};
+
 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
   OwnsVMContext(!_VMContext) {}
@@ -853,7 +869,8 @@
   CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
   std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
   BEConsumer = Result.get();
-
+  VMContext->setDiagnosticHandler(llvm::make_unique(
+  CI.getCodeGenOpts(), Result.get()));
   // Enable generating macro debug info only when debug info is not disabled 
and
   // also macro debug info is enabled.
   if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&


Index: lib/CodeGen/CodeGenAction.cpp
===
--- lib/CodeGen/CodeGenAction.cpp
+++ lib/CodeGen/CodeGenAction.cpp
@@ -224,10 +224,6 @@
   void *OldContext = Ctx.getInlineAsmDiagnosticContext();
   Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
 
-  LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
-  Ctx.getDiagnosticHandler();
-  void *OldDiagnosticContext = Ctx.getDiagnosticContext();
-  Ctx.setDiagnosticHandler(DiagnosticHandler, this);
   Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
   if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
 Ctx.setDiagnosticsHotnessThreshold(
@@ -264,8 +260,6 @@
 
   Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
 
-  Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
-
   if (OptRecordFile)
 OptRecordFile->keep();
 }
@@ -299,11 +293,6 @@
   ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
 }
 
-static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
-  void *Context) {
-  ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
-}
-
 /// Get the best possible source location to represent a diagnostic that
 /// may have associated debug info.
 const FullSourceLoc
@@ -756,6 +745,33 @@
 }
 #undef ComputeDiagID
 
+class ClangDiagnosticHandler final : public DiagnosticHandler {
+public:
+  ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
+  : CodeGenOpts(CGOpts), BackendCon(BCon) {}
+
+  bool handleDiagnostics(const D

[PATCH] D33514: [WIP] Bug 32352 - Provide a way for OptimizationRemarkEmitter::allowExtraAnalysis to check if (specific) remarks are enabled

2017-09-11 Thread Vivek Pandya via Phabricator via cfe-commits
vivekvpandya updated this revision to Diff 114647.
vivekvpandya marked 8 inline comments as done.

https://reviews.llvm.org/D33514

Files:
  include/llvm/Analysis/OptimizationDiagnosticInfo.h
  include/llvm/CodeGen/MachineOptimizationRemarkEmitter.h
  include/llvm/IR/DiagnosticHandler.h
  include/llvm/IR/DiagnosticInfo.h
  include/llvm/IR/LLVMContext.h
  include/llvm/LTO/Config.h
  include/llvm/LTO/legacy/LTOCodeGenerator.h
  lib/IR/CMakeLists.txt
  lib/IR/Core.cpp
  lib/IR/DiagnosticHandler.cpp
  lib/IR/DiagnosticInfo.cpp
  lib/IR/LLVMContext.cpp
  lib/IR/LLVMContextImpl.cpp
  lib/IR/LLVMContextImpl.h
  lib/LTO/LTOCodeGenerator.cpp
  lib/Transforms/Scalar/GVN.cpp
  lib/Transforms/Vectorize/LoopVectorize.cpp
  test/Transforms/GVN/opt-remarks.ll
  tools/llc/llc.cpp
  tools/llvm-dis/llvm-dis.cpp
  tools/llvm-link/llvm-link.cpp
  tools/llvm-lto/llvm-lto.cpp
  tools/lto/lto.cpp

Index: tools/lto/lto.cpp
===
--- tools/lto/lto.cpp
+++ tools/lto/lto.cpp
@@ -75,20 +75,23 @@
 
 static LLVMContext *LTOContext = nullptr;
 
-static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
-  if (DI.getSeverity() != DS_Error) {
-DiagnosticPrinterRawOStream DP(errs());
-DI.print(DP);
-errs() << '\n';
-return;
-  }
-  sLastErrorString = "";
-  {
-raw_string_ostream Stream(sLastErrorString);
-DiagnosticPrinterRawOStream DP(Stream);
-DI.print(DP);
+struct LTOToolDiagnosticHandler : public DiagnosticHandler {
+  bool handleDiagnostics(const DiagnosticInfo &DI) override {
+if (DI.getSeverity() != DS_Error) {
+  DiagnosticPrinterRawOStream DP(errs());
+  DI.print(DP);
+  errs() << '\n';
+  return true;
+}
+sLastErrorString = "";
+{
+  raw_string_ostream Stream(sLastErrorString);
+  DiagnosticPrinterRawOStream DP(Stream);
+  DI.print(DP);
+}
+return true;
   }
-}
+};
 
 // Initialize the configured targets if they have not been initialized.
 static void lto_initialize() {
@@ -108,7 +111,8 @@
 
 static LLVMContext Context;
 LTOContext = &Context;
-LTOContext->setDiagnosticHandler(diagnosticHandler, nullptr, true);
+LTOContext->setDiagnosticHandler(
+llvm::make_unique(), true);
 initialized = true;
   }
 }
@@ -274,7 +278,8 @@
 
   // Create a local context. Ownership will be transferred to LTOModule.
   std::unique_ptr Context = llvm::make_unique();
-  Context->setDiagnosticHandler(diagnosticHandler, nullptr, true);
+  Context->setDiagnosticHandler(llvm::make_unique(),
+true);
 
   ErrorOr> M = LTOModule::createInLocalContext(
   std::move(Context), mem, length, Options, StringRef(path));
Index: tools/llvm-lto/llvm-lto.cpp
===
--- tools/llvm-lto/llvm-lto.cpp
+++ tools/llvm-lto/llvm-lto.cpp
@@ -235,34 +235,40 @@
 }
 
 static std::string CurrentActivity;
-static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
-  raw_ostream &OS = errs();
-  OS << "llvm-lto: ";
-  switch (DI.getSeverity()) {
-  case DS_Error:
-OS << "error";
-break;
-  case DS_Warning:
-OS << "warning";
-break;
-  case DS_Remark:
-OS << "remark";
-break;
-  case DS_Note:
-OS << "note";
-break;
-  }
-  if (!CurrentActivity.empty())
-OS << ' ' << CurrentActivity;
-  OS << ": ";
-
-  DiagnosticPrinterRawOStream DP(OS);
-  DI.print(DP);
-  OS << '\n';
 
-  if (DI.getSeverity() == DS_Error)
-exit(1);
-}
+namespace {
+  struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
+bool handleDiagnostics(const DiagnosticInfo &DI) override {
+  raw_ostream &OS = errs();
+  OS << "llvm-lto: ";
+  switch (DI.getSeverity()) {
+  case DS_Error:
+OS << "error";
+break;
+  case DS_Warning:
+OS << "warning";
+break;
+  case DS_Remark:
+OS << "remark";
+break;
+  case DS_Note:
+OS << "note";
+break;
+  }
+  if (!CurrentActivity.empty())
+OS << ' ' << CurrentActivity;
+  OS << ": ";
+  
+  DiagnosticPrinterRawOStream DP(OS);
+  DI.print(DP);
+  OS << '\n';
+  
+  if (DI.getSeverity() == DS_Error)
+exit(1);
+  return true;
+}
+  };
+  }
 
 static void error(const Twine &Msg) {
   errs() << "llvm-lto: " << Msg << '\n';
@@ -293,7 +299,8 @@
   Buffer = std::move(BufferOrErr.get());
   CurrentActivity = ("loading file '" + Path + "'").str();
   std::unique_ptr Context = llvm::make_unique();
-  Context->setDiagnosticHandler(diagnosticHandler, nullptr, true);
+  Context->setDiagnosticHandler(llvm::make_unique(),
+true);
   ErrorOr> Ret = LTOModule::createInLocalContext(
   std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
   Options, Path);
@@ -837,7 +844,8 @@
   unsigned BaseArg = 0;
 
   LLVMContext Context;
-  Context.setDiagnosticHandler(diagnostic

[PATCH] D36150: [clangd] LSP extension to switch between source/header file

2017-09-11 Thread William Enright via Phabricator via cfe-commits
Nebiroth marked 5 inline comments as done.
Nebiroth added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:234
+  else
+ResultUri = URI::fromFile("");
+

ilya-biryukov wrote:
> Running `unparse` on an instance created via `URI::fromFile("")`  will result 
> in `"file:///"`. 
> 
> Have you considered returning a list of paths as a result from 
> `switchHeaderSource`?
> That way you could capture the "no file matched" case with an empty list.
> Later when an implementation will look into index, that would allow to return 
> multiple source files for a header file, which also  happens in some C++ 
> projects.
> 
> Returning an empty string is also an option we could start with.
I think I will start by returning an empty string for now. Returning a list of 
paths sounds like a good idea once an indexer is implemented, but that would 
require changing some parts of the code like find_if which returns only the 
first instance of a match.


https://reviews.llvm.org/D36150



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


[PATCH] D37529: [codeview] omit debug locations for nested exprs unless column info enabled

2017-09-11 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




Comment at: clang/lib/CodeGen/CodeGenModule.h:517
+  /// Return true if we should emit location information for nested 
expressions.
+  bool getNestedExpressionLocationsEnabled() const {
+return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;

I'd drop the "nested" part of this name. Statements are also nested, in a 
sense. A for loop is a statement, and it has child statements. This is really 
about expression locations vs. statement expressions.


https://reviews.llvm.org/D37529



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


[PATCH] D37530: [MinGW] Don't link -lmsvcrt if a different msvcrt version is to be linked

2017-09-11 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


https://reviews.llvm.org/D37530



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


[PATCH] D37530: [MinGW] Don't link -lmsvcrt if a different msvcrt version is to be linked

2017-09-11 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

In https://reviews.llvm.org/D37530#865333, @mstorsjo wrote:

> Attempted implementing Reid's suggestion.
>
> On the mingw-w64 mailing list 
> (https://sourceforge.net/p/mingw-w64/mailman/message/36030072/), there were 
> points made that it would be better with some mechanism that controls both 
> linking the right msvcrt version and setting `__MSVCRT_VERSION__` in sync.
>
> And someone pointed out some widely used (but not upstreamed) patches for GCC 
> that adds an option `-mcrtdll` which does pretty much exactly what my 
> `-mmsvcrt` option did in the previous iteration 
> (https://raw.githubusercontent.com/Alexpux/MINGW-packages/master/mingw-w64-gcc-git/0006-gcc-7-branch-Windows-New-feature-to-allow-overriding.patch),
>  which in another non-upstreamed patch also is used to set 
> `__MSVCRT_VERSION__` 
> (https://raw.githubusercontent.com/nak5124/build_env/master/gcc_build/patches/gcc/0020-MinGW-w64-Define-__MSVCRT_VERSION__.patch).


Hm, these are interesting. Getting a separate concept of CRT version would be 
nice. We've talked about getting something like that for glibc as well, since 
there were some new math builtins we'd like to use there.


https://reviews.llvm.org/D37530



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


[PATCH] D36150: [clangd] LSP extension to switch between source/header file

2017-09-11 Thread William Enright via Phabricator via cfe-commits
Nebiroth updated this revision to Diff 114652.
Nebiroth added a comment.

Return value when no file is found is now an empty string instead of file://
Minor code style changes and cleanup.
Ran clang-format on ClangdServer.h


https://reviews.llvm.org/D36150

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -12,7 +12,6 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Program.h"
-
 #include 
 #include 
 #include 
Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -47,7 +47,9 @@
   virtual void onCompletion(TextDocumentPositionParams Params, StringRef ID,
 JSONOutput &Out) = 0;
   virtual void onGoToDefinition(TextDocumentPositionParams Params, StringRef ID,
-JSONOutput &Out) = 0;
+JSONOutput &Out) = 0;
+  virtual void onSwitchSourceHeader(TextDocumentIdentifier Params, StringRef ID,
+JSONOutput &Out) = 0;
 };
 
 void regiterCallbackHandlers(JSONRPCDispatcher &Dispatcher, JSONOutput &Out,
Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -204,6 +204,22 @@
   ProtocolCallbacks &Callbacks;
 };
 
+struct SwitchSourceHeaderHandler : Handler {
+  SwitchSourceHeaderHandler(JSONOutput &Output, ProtocolCallbacks &Callbacks)
+  : Handler(Output), Callbacks(Callbacks) {}
+
+  void handleMethod(llvm::yaml::MappingNode *Params, StringRef ID) override {
+auto TDPP = TextDocumentIdentifier::parse(Params);
+if (!TDPP)
+  return;
+
+Callbacks.onSwitchSourceHeader(*TDPP, ID, Output);
+  }
+
+private:
+  ProtocolCallbacks &Callbacks;
+};
+
 } // namespace
 
 void clangd::regiterCallbackHandlers(JSONRPCDispatcher &Dispatcher,
@@ -237,6 +253,10 @@
   Dispatcher.registerHandler(
   "textDocument/completion",
   llvm::make_unique(Out, Callbacks));
-  Dispatcher.registerHandler("textDocument/definition",
+  Dispatcher.registerHandler(
+  "textDocument/definition",
   llvm::make_unique(Out, Callbacks));
+  Dispatcher.registerHandler(
+  "textDocument/switchSourceHeader",
+  llvm::make_unique(Out, Callbacks));
 }
Index: clangd/ClangdServer.h
===
--- clangd/ClangdServer.h
+++ clangd/ClangdServer.h
@@ -182,6 +182,10 @@
   /// Get definition of symbol at a specified \p Line and \p Column in \p File.
   Tagged> findDefinitions(PathRef File, Position Pos);
 
+  /// Helper function that returns a path to the corresponding source file when
+  /// given a header file and vice versa.
+  llvm::Optional switchSourceHeader(PathRef Path);
+
   /// Run formatting for \p Rng inside \p File.
   std::vector formatRange(PathRef File, Range Rng);
   /// Run formatting for the whole \p File.
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -15,6 +15,7 @@
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 
@@ -273,16 +274,76 @@
   return DumpFuture.get();
 }
 
-Tagged>
-ClangdServer::findDefinitions(PathRef File, Position Pos) {
+Tagged> ClangdServer::findDefinitions(PathRef File,
+Position Pos) {
   auto FileContents = DraftMgr.getDraft(File);
-  assert(FileContents.Draft && "findDefinitions is called for non-added document");
+  assert(FileContents.Draft &&
+ "findDefinitions is called for non-added document");
 
   std::vector Result;
   auto TaggedFS = FSProvider.getTaggedFileSystem(File);
-  Units.runOnUnit(File, *FileContents.Draft, ResourceDir, CDB, PCHs,
-  TaggedFS.Value, [&](ClangdUnit &Unit) {
-Result = Unit.findDefinitions(Pos);
-  });
+  Units.runOnUnit(
+  File, *FileContents.Draft, ResourceDir, CDB, PCHs, TaggedFS.Value,
+  [&](ClangdUnit &Unit) { Result = Unit.findDefinitions(Pos); });
   return make_tagged(std::move(Result), TaggedFS.Tag);
 }
+
+llvm::Optional ClangdServer::switchSourceHeader(PathRef Path) {
+
+  StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
+  ".c++", ".m", ".mm"};
+  StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
+
+  StringRef PathExt = llvm::sys::path::extension(Path);
+
+  // Lookup in a list of known exten

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

2017-09-11 Thread William Enright via Phabricator via cfe-commits
Nebiroth updated this revision to Diff 114654.
Nebiroth added a comment.

Simpilified a pointer return value.


https://reviews.llvm.org/D37150

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -11,8 +11,8 @@
 #include "JSONRPCDispatcher.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
-
 #include 
 #include 
 #include 
@@ -25,16 +25,43 @@
  llvm::cl::desc("parse on main thread"),
  llvm::cl::init(false), llvm::cl::Hidden);
 
+static llvm::cl::opt CompileCommandsDir(
+"compile-commands-dir",
+llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
+   "is invalid, clangd will look in the current directory and "
+   "parent paths of each source file."));
+
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
 
   llvm::raw_ostream &Outs = llvm::outs();
   llvm::raw_ostream &Logs = llvm::errs();
   JSONOutput Out(Outs, Logs);
 
+  // If --compile-commands-dir arg was invoked, check value and override default
+  // path.
+  namespace path = llvm::sys::path;
+
+  if (!llvm::sys::path::is_absolute(CompileCommandsDir)) {
+Out.log("Path specified by --compile-commands-dir must be an absolute "
+"path. The argument will be ignored.\n");
+CompileCommandsDir = "";
+  }
+
+  if (!llvm::sys::fs::exists(CompileCommandsDir)) {
+Out.log("Path specified by --compile-commands-dir. The argument will be "
+"ignored.\n");
+CompileCommandsDir = "";
+  }
+  llvm::Optional CompileCommandsDirPath;
+
   // Change stdin to binary to not lose \r\n on windows.
   llvm::sys::ChangeStdinToBinary();
+  if (CompileCommandsDir.empty())
+CompileCommandsDirPath = llvm::None;
+  else
+CompileCommandsDirPath = CompileCommandsDir;
 
-  ClangdLSPServer LSPServer(Out, RunSynchronously);
+  ClangdLSPServer LSPServer(Out, RunSynchronously, CompileCommandsDirPath);
   LSPServer.run(std::cin);
 }
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalCompilationDatabase.h
@@ -45,13 +45,18 @@
 class DirectoryBasedGlobalCompilationDatabase
 : public GlobalCompilationDatabase {
 public:
+  DirectoryBasedGlobalCompilationDatabase(
+  llvm::Optional NewCompileCommandsDir)
+  : CompileCommandsDir(NewCompileCommandsDir.getValue()) {}
   std::vector
   getCompileCommands(PathRef File) override;
 
   void setExtraFlagsForFile(PathRef File, std::vector ExtraFlags);
 
 private:
   tooling::CompilationDatabase *getCompilationDatabase(PathRef File);
+  Path CompileCommandsDir;
+  tooling::CompilationDatabase *tryLoadDatabaseFromPath(PathRef File);
 
   std::mutex Mutex;
   /// Caches compilation databases loaded from directories(keys are
Index: clangd/GlobalCompilationDatabase.cpp
===
--- clangd/GlobalCompilationDatabase.cpp
+++ clangd/GlobalCompilationDatabase.cpp
@@ -62,43 +62,52 @@
 }
 
 tooling::CompilationDatabase *
-DirectoryBasedGlobalCompilationDatabase::getCompilationDatabase(PathRef File) {
-  std::lock_guard Lock(Mutex);
-
+DirectoryBasedGlobalCompilationDatabase::tryLoadDatabaseFromPath(PathRef File) {
   namespace path = llvm::sys::path;
+  auto CachedIt = CompilationDatabases.find(File);
+  std::string Error = "";
 
   assert((path::is_absolute(File, path::Style::posix) ||
   path::is_absolute(File, path::Style::windows)) &&
  "path must be absolute");
 
-  for (auto Path = path::parent_path(File); !Path.empty();
-   Path = path::parent_path(Path)) {
-
-auto CachedIt = CompilationDatabases.find(Path);
-if (CachedIt != CompilationDatabases.end())
-  return CachedIt->second.get();
-std::string Error;
-auto CDB = tooling::CompilationDatabase::loadFromDirectory(Path, Error);
-if (!CDB) {
-  if (!Error.empty()) {
-// FIXME(ibiryukov): logging
-// Output.log("Error when trying to load compilation database from " +
-//Twine(Path) + ": " + Twine(Error) + "\n");
-  }
-  continue;
-}
+  if (CachedIt != CompilationDatabases.end())
+return (CachedIt->second.get());
+  auto CDB = tooling::CompilationDatabase::loadFromDirectory(File, Error);
+  if (CDB && Error.empty()) {
+auto result = CDB.get();
+CompilationDatabases.insert(std::make_pair(File, std::move(CDB)));
 
 // FIXME(ibiryukov): Invalidate cached compilation databases on changes
-auto result = CDB.get();
-Compil

r312942 - clang-rename: let -force handle multiple renames

2017-09-11 Thread Miklos Vajna via cfe-commits
Author: vmiklos
Date: Mon Sep 11 13:18:38 2017
New Revision: 312942

URL: http://llvm.org/viewvc/llvm-project?rev=312942&view=rev
Log:
clang-rename: let -force handle multiple renames

Summary:
The use case is that renaming multiple symbols in a large enough codebase is
much faster if all of these can be done with a single invocation, but
there will be multiple translation units where one or more symbols are
not found.

Old behavior was to exit with an error (default) or exit without
reporting an error (-force). New behavior is that -force results in a
best-effort rename: rename symbols which are found and just ignore the
rest.

The existing help for -force sort of already implies this behavior.

Reviewers: cfe-commits, klimek, arphaman

Reviewed By: klimek

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

Added:
cfe/trunk/test/clang-rename/ForceMulti.cpp
Modified:
cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
cfe/trunk/tools/clang-rename/ClangRename.cpp

Modified: cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp?rev=312942&r1=312941&r2=312942&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp Mon Sep 11 
13:18:38 2017
@@ -84,8 +84,13 @@ public:
 FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {}
 
   void HandleTranslationUnit(ASTContext &Context) override {
-for (unsigned I = 0; I < NewNames.size(); ++I)
+for (unsigned I = 0; I < NewNames.size(); ++I) {
+  // If the previous name was not found, ignore this rename request.
+  if (PrevNames[I].empty())
+continue;
+
   HandleOneRename(Context, NewNames[I], PrevNames[I], USRList[I]);
+}
   }
 
   void HandleOneRename(ASTContext &Context, const std::string &NewName,

Modified: cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp?rev=312942&r1=312941&r2=312942&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp Mon Sep 11 
13:18:38 2017
@@ -198,8 +198,11 @@ private:
 return false;
   }
 
-  if (Force)
+  if (Force) {
+SpellingNames.push_back(std::string());
+USRList.push_back(std::vector());
 return true;
+  }
 
   unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID(
   DiagnosticsEngine::Error, "clang-rename could not find symbol %0");

Added: cfe/trunk/test/clang-rename/ForceMulti.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/clang-rename/ForceMulti.cpp?rev=312942&view=auto
==
--- cfe/trunk/test/clang-rename/ForceMulti.cpp (added)
+++ cfe/trunk/test/clang-rename/ForceMulti.cpp Mon Sep 11 13:18:38 2017
@@ -0,0 +1,8 @@
+class B /* Test 1 */ { // CHECK: class B2 /* Test 1 */ {
+};
+
+class D : public B /* Test 1 */ { // CHECK: class D : public B2 /* Test 1 */ {
+};
+
+// Test 1.
+// RUN: clang-rename -force -qualified-name B -new-name B2 -qualified-name E 
-new-name E2 %s -- | sed 's,//.*,,' | FileCheck %s

Modified: cfe/trunk/tools/clang-rename/ClangRename.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-rename/ClangRename.cpp?rev=312942&r1=312941&r2=312942&view=diff
==
--- cfe/trunk/tools/clang-rename/ClangRename.cpp (original)
+++ cfe/trunk/tools/clang-rename/ClangRename.cpp Mon Sep 11 13:18:38 2017
@@ -175,12 +175,6 @@ int main(int argc, const char **argv) {
 return 1;
   }
 
-  if (Force && PrevNames.size() < NewNames.size()) {
-// No matching PrevName for all NewNames. Without Force this is an error
-// above already.
-return 0;
-  }
-
   // Perform the renaming.
   tooling::RenamingAction RenameAction(NewNames, PrevNames, USRList,
Tool.getReplacements(), PrintLocations);


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


r312941 - Driver: default to `-fno-use-cxatexit` on Windows

2017-09-11 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Mon Sep 11 13:18:09 2017
New Revision: 312941

URL: http://llvm.org/viewvc/llvm-project?rev=312941&view=rev
Log:
Driver: default to `-fno-use-cxatexit` on Windows

This primarily impacts the Windows MSVC and Windows itanium
environments.  Windows MSVC does not use `__cxa_atexit` and Itanium
follows suit.  Simplify the logic for the default value calculation and
blanket the Windows environments to default to off for use of
`__cxa_atexit`.

Added:
cfe/trunk/test/Driver/cxa-atexit.cpp
Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=312941&r1=312940&r2=312941&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Sep 11 13:18:09 2017
@@ -4022,7 +4022,7 @@ void Clang::ConstructJob(Compilation &C,
   // -fuse-cxa-atexit is default.
   if (!Args.hasFlag(
   options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
-  !IsWindowsCygnus && !IsWindowsGNU &&
+  !RawTriple.isOSWindows() &&
   RawTriple.getOS() != llvm::Triple::Solaris &&
   getToolChain().getArch() != llvm::Triple::hexagon &&
   getToolChain().getArch() != llvm::Triple::xcore &&

Added: cfe/trunk/test/Driver/cxa-atexit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cxa-atexit.cpp?rev=312941&view=auto
==
--- cfe/trunk/test/Driver/cxa-atexit.cpp (added)
+++ cfe/trunk/test/Driver/cxa-atexit.cpp Mon Sep 11 13:18:09 2017
@@ -0,0 +1,27 @@
+// RUN: %clang -### -target armv7-unknown-windows-msvc -c %s -o /dev/null 2>&1 
| FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target armv7-unknown-windows-itanium -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target armv7-unknown-windows-gnu -c %s -o /dev/null 2>&1 
| FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target armv7-unknown-windows-cygnus -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target i686-unknown-windows-msvc -c %s -o /dev/null 2>&1 
| FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target i686-unknown-windows-itanium -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target i686-unknown-windows-gnu -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target i686-unknown-windows-cygnus -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target x86_64-unknown-windows-msvc -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target x86_64-unknown-windows-itanium -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target x86_64-unknown-windows-gnu -c %s -o /dev/null 2>&1 
| FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target x86_64-unknown-windows-cygnus -c %s -o /dev/null 
2>&1 | FileCheck %s -check-prefix CHECK-WINDOWS
+// RUN: %clang -### -target hexagon-unknown-none -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-HEXAGON
+// RUN: %clang -### -target xcore-unknown-none -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-XCORE
+// RUN: %clang -### -target armv7-mti-none -c %s -o /dev/null 2>&1 | FileCheck 
%s -check-prefix CHECK-MTI
+// RUN: %clang -### -target mips-unknown-none -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-MIPS
+// RUN: %clang -### -target mips-unknown-none-gnu -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-MIPS
+// RUN: %clang -### -target mips-mti-none-gnu -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-MIPS
+// RUN: %clang -### -target sparc-sun-solaris -c %s -o /dev/null 2>&1 | 
FileCheck %s -check-prefix CHECK-SOLARIS
+
+// CHECK-WINDOWS: "-fno-use-cxa-atexit"
+// CHECK-SOLARIS: "-fno-use-cxa-atexit"
+// CHECK-HEXAGON: "-fno-use-cxa-atexit"
+// CHECK-XCORE: "-fno-use-cxa-atexit"
+// CHECK-MTI: "-fno-use-cxa-atexit"
+// CHECK-MIPS-NOT: "-fno-use-cxa-atexit"
+


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


[PATCH] D37634: clang-rename: let -force handle multiple renames

2017-09-11 Thread Miklos Vajna via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312942: clang-rename: let -force handle multiple renames 
(authored by vmiklos).

Changed prior to commit:
  https://reviews.llvm.org/D37634?vs=114402&id=114663#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37634

Files:
  cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
  cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
  cfe/trunk/test/clang-rename/ForceMulti.cpp
  cfe/trunk/tools/clang-rename/ClangRename.cpp


Index: cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -198,8 +198,11 @@
 return false;
   }
 
-  if (Force)
+  if (Force) {
+SpellingNames.push_back(std::string());
+USRList.push_back(std::vector());
 return true;
+  }
 
   unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID(
   DiagnosticsEngine::Error, "clang-rename could not find symbol %0");
Index: cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
@@ -84,8 +84,13 @@
 FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {}
 
   void HandleTranslationUnit(ASTContext &Context) override {
-for (unsigned I = 0; I < NewNames.size(); ++I)
+for (unsigned I = 0; I < NewNames.size(); ++I) {
+  // If the previous name was not found, ignore this rename request.
+  if (PrevNames[I].empty())
+continue;
+
   HandleOneRename(Context, NewNames[I], PrevNames[I], USRList[I]);
+}
   }
 
   void HandleOneRename(ASTContext &Context, const std::string &NewName,
Index: cfe/trunk/tools/clang-rename/ClangRename.cpp
===
--- cfe/trunk/tools/clang-rename/ClangRename.cpp
+++ cfe/trunk/tools/clang-rename/ClangRename.cpp
@@ -175,12 +175,6 @@
 return 1;
   }
 
-  if (Force && PrevNames.size() < NewNames.size()) {
-// No matching PrevName for all NewNames. Without Force this is an error
-// above already.
-return 0;
-  }
-
   // Perform the renaming.
   tooling::RenamingAction RenameAction(NewNames, PrevNames, USRList,
Tool.getReplacements(), PrintLocations);
Index: cfe/trunk/test/clang-rename/ForceMulti.cpp
===
--- cfe/trunk/test/clang-rename/ForceMulti.cpp
+++ cfe/trunk/test/clang-rename/ForceMulti.cpp
@@ -0,0 +1,8 @@
+class B /* Test 1 */ { // CHECK: class B2 /* Test 1 */ {
+};
+
+class D : public B /* Test 1 */ { // CHECK: class D : public B2 /* Test 1 */ {
+};
+
+// Test 1.
+// RUN: clang-rename -force -qualified-name B -new-name B2 -qualified-name E 
-new-name E2 %s -- | sed 's,//.*,,' | FileCheck %s


Index: cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -198,8 +198,11 @@
 return false;
   }
 
-  if (Force)
+  if (Force) {
+SpellingNames.push_back(std::string());
+USRList.push_back(std::vector());
 return true;
+  }
 
   unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID(
   DiagnosticsEngine::Error, "clang-rename could not find symbol %0");
Index: cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
@@ -84,8 +84,13 @@
 FileToReplaces(FileToReplaces), PrintLocations(PrintLocations) {}
 
   void HandleTranslationUnit(ASTContext &Context) override {
-for (unsigned I = 0; I < NewNames.size(); ++I)
+for (unsigned I = 0; I < NewNames.size(); ++I) {
+  // If the previous name was not found, ignore this rename request.
+  if (PrevNames[I].empty())
+continue;
+
   HandleOneRename(Context, NewNames[I], PrevNames[I], USRList[I]);
+}
   }
 
   void HandleOneRename(ASTContext &Context, const std::string &NewName,
Index: cfe/trunk/tools/clang-rename/ClangRename.cpp
===
--- cfe/trunk/tools/clang-rename/ClangRename.cpp
+++ cfe/trunk/tools/clang-rename/ClangRename.cpp
@@ -175,12 +175,6 @@
 return 1;
   }
 
-  if (Force && PrevNames.size() < NewNames.size()) {
-// No matching PrevName for all NewNames. Without Force this is an error
-// above already.
-retur

[PATCH] D37529: [codeview] omit debug locations for nested exprs unless column info enabled

2017-09-11 Thread David Majnemer via Phabricator via cfe-commits
majnemer added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.h:32
 #include "clang/Basic/XRayLists.h"
+#include "clang/Frontend/CodeGenOptions.h"
 #include "llvm/ADT/DenseMap.h"

Any reason to do this? I'd just keep getNestedExpressionLocationsEnabled in the 
.cpp file.


https://reviews.llvm.org/D37529



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


r312947 - [Lexer] Report more precise skipped regions (PR34166)

2017-09-11 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Sep 11 13:47:42 2017
New Revision: 312947

URL: http://llvm.org/viewvc/llvm-project?rev=312947&view=rev
Log:
[Lexer] Report more precise skipped regions (PR34166)

This patch teaches the preprocessor to report more precise source ranges for
code that is skipped due to conditional directives.

The new behavior includes the '#' from the opening directive and the full text
of the line containing the closing directive in the skipped area. This matches
up clang's behavior (we don't IRGen the code between the closing "endif" and
the end of a line).

This also affects the code coverage implementation. See llvm.org/PR34166 (this
also happens to be rdar://problem/23224058).

The old behavior (report the end of the skipped range as the end
location of the 'endif' token) is preserved for indexing clients.

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

Modified:
cfe/trunk/include/clang/Lex/PPCallbacks.h
cfe/trunk/include/clang/Lex/PreprocessingRecord.h
cfe/trunk/include/clang/Lex/Preprocessor.h
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/lib/CodeGen/CoverageMappingGen.h
cfe/trunk/lib/Lex/PPDirectives.cpp
cfe/trunk/lib/Lex/PreprocessingRecord.cpp
cfe/trunk/test/CoverageMapping/preprocessor.c
cfe/trunk/test/Index/skipped-ranges.c
cfe/trunk/tools/libclang/Indexing.cpp

Modified: cfe/trunk/include/clang/Lex/PPCallbacks.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/PPCallbacks.h?rev=312947&r1=312946&r2=312947&view=diff
==
--- cfe/trunk/include/clang/Lex/PPCallbacks.h (original)
+++ cfe/trunk/include/clang/Lex/PPCallbacks.h Mon Sep 11 13:47:42 2017
@@ -266,7 +266,10 @@ public:
   /// \brief Hook called when a source range is skipped.
   /// \param Range The SourceRange that was skipped. The range begins at the
   /// \#if/\#else directive and ends after the \#endif/\#else directive.
-  virtual void SourceRangeSkipped(SourceRange Range) {
+  /// \param EndifLoc The end location of the 'endif' token, which may precede
+  /// the range skipped by the directive (e.g excluding comments after an
+  /// 'endif').
+  virtual void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) {
   }
 
   enum ConditionValueKind {
@@ -468,9 +471,9 @@ public:
 Second->Defined(MacroNameTok, MD, Range);
   }
 
-  void SourceRangeSkipped(SourceRange Range) override {
-First->SourceRangeSkipped(Range);
-Second->SourceRangeSkipped(Range);
+  void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override 
{
+First->SourceRangeSkipped(Range, EndifLoc);
+Second->SourceRangeSkipped(Range, EndifLoc);
   }
 
   /// \brief Hook called whenever an \#if is seen.

Modified: cfe/trunk/include/clang/Lex/PreprocessingRecord.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/PreprocessingRecord.h?rev=312947&r1=312946&r2=312947&view=diff
==
--- cfe/trunk/include/clang/Lex/PreprocessingRecord.h (original)
+++ cfe/trunk/include/clang/Lex/PreprocessingRecord.h Mon Sep 11 13:47:42 2017
@@ -504,7 +504,8 @@ namespace clang {
 void Defined(const Token &MacroNameTok, const MacroDefinition &MD,
  SourceRange Range) override;
 
-void SourceRangeSkipped(SourceRange Range) override;
+void SourceRangeSkipped(SourceRange Range,
+SourceLocation EndifLoc) override;
 
 void addMacroExpansion(const Token &Id, const MacroInfo *MI,
SourceRange Range);

Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Preprocessor.h?rev=312947&r1=312946&r2=312947&view=diff
==
--- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
+++ cfe/trunk/include/clang/Lex/Preprocessor.h Mon Sep 11 13:47:42 2017
@@ -1837,7 +1837,8 @@ private:
   /// \p FoundElse is false, then \#else directives are ok, if not, then we 
have
   /// already seen one so a \#else directive is a duplicate.  When this 
returns,
   /// the caller can lex the first valid token.
-  void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
+  void SkipExcludedConditionalBlock(const Token &HashToken,
+SourceLocation IfTokenLoc,
 bool FoundNonSkipPortion, bool FoundElse,
 SourceLocation ElseLoc = SourceLocation());
 
@@ -2031,12 +2032,13 @@ private:
   void HandleUndefDirective();
 
   // Conditional Inclusion.
-  void HandleIfdefDirective(Token &Tok, bool isIfndef,
-bool ReadAnyTokensBeforeDirective);
-  void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective);
+  void HandleIfdefDirective(Token &Tok, const Token &HashToken,
+ 

[clang-tools-extra] r312948 - [pp-trace] Update skipped source ranges in tests

2017-09-11 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Sep 11 13:47:45 2017
New Revision: 312948

URL: http://llvm.org/viewvc/llvm-project?rev=312948&view=rev
Log:
[pp-trace] Update skipped source ranges in tests

Depends on D36642

Modified:
clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp
clang-tools-extra/trunk/test/pp-trace/pp-trace-macro.cpp

Modified: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp?rev=312948&r1=312947&r2=312948&view=diff
==
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp (original)
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp Mon Sep 11 13:47:45 
2017
@@ -342,9 +342,10 @@ void PPCallbacksTracker::Defined(const c
 }
 
 // Hook called when a source range is skipped.
-void PPCallbacksTracker::SourceRangeSkipped(clang::SourceRange Range) {
+void PPCallbacksTracker::SourceRangeSkipped(clang::SourceRange Range,
+clang::SourceLocation EndifLoc) {
   beginCallback("SourceRangeSkipped");
-  appendArgument("Range", Range);
+  appendArgument("Range", clang::SourceRange(Range.getBegin(), EndifLoc));
 }
 
 // Hook called whenever an #if is seen.

Modified: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h?rev=312948&r1=312947&r2=312948&view=diff
==
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h (original)
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h Mon Sep 11 13:47:45 
2017
@@ -145,7 +145,8 @@ public:
   void Defined(const clang::Token &MacroNameTok,
const clang::MacroDefinition &MD,
clang::SourceRange Range) override;
-  void SourceRangeSkipped(clang::SourceRange Range) override;
+  void SourceRangeSkipped(clang::SourceRange Range,
+  clang::SourceLocation EndifLoc) override;
   void If(clang::SourceLocation Loc, clang::SourceRange ConditionRange,
   ConditionValueKind ConditionValue) override;
   void Elif(clang::SourceLocation Loc, clang::SourceRange ConditionRange,

Modified: clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp?rev=312948&r1=312947&r2=312948&view=diff
==
--- clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp (original)
+++ clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp Mon Sep 11 
13:47:45 2017
@@ -92,7 +92,7 @@
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:7:2"
 // CHECK-NEXT:   IfLoc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:2"
 // CHECK-NEXT: - Callback: SourceRangeSkipped
-// CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:2", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:7:2"]
+// CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:1", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:7:2"]
 // CHECK-NEXT: - Callback: If
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:2"
 // CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:4", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:10:1"]
@@ -104,7 +104,7 @@
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:11:2"
 // CHECK-NEXT:   IfLoc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:2"
 // CHECK-NEXT: - Callback: SourceRangeSkipped
-// CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:10:2", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:11:2"]
+// CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:10:1", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:11:2"]
 // CHECK-NEXT: - Callback: If
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:2"
 // CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:4", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:14:1"]
@@ -113,7 +113,7 @@
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:14:2"
 // CHECK-NEXT:   IfLoc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:2"
 // CHECK-NEXT: - Callback: SourceRangeSkipped
-// CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:2", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:14:2"]
+// CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:1", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:14:2"]
 // CHECK-NEXT: - Callback: Endif
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:15:2"
 // CHECK-NEXT:   IfLoc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:2"
@@ -130,7 +130,7 @@
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:19:2"
 

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

2017-09-11 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312947: [Lexer] Report more precise skipped regions 
(PR34166) (authored by vedantk).

Changed prior to commit:
  https://reviews.llvm.org/D36642?vs=114433&id=114676#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D36642

Files:
  cfe/trunk/include/clang/Lex/PPCallbacks.h
  cfe/trunk/include/clang/Lex/PreprocessingRecord.h
  cfe/trunk/include/clang/Lex/Preprocessor.h
  cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
  cfe/trunk/lib/CodeGen/CoverageMappingGen.h
  cfe/trunk/lib/Lex/PPDirectives.cpp
  cfe/trunk/lib/Lex/PreprocessingRecord.cpp
  cfe/trunk/test/CoverageMapping/preprocessor.c
  cfe/trunk/test/Index/skipped-ranges.c
  cfe/trunk/tools/libclang/Indexing.cpp

Index: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
===
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
@@ -29,7 +29,7 @@
 using namespace CodeGen;
 using namespace llvm::coverage;
 
-void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
+void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
   SkippedRanges.push_back(Range);
 }
 
Index: cfe/trunk/lib/CodeGen/CoverageMappingGen.h
===
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.h
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.h
@@ -39,7 +39,7 @@
 public:
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
-  void SourceRangeSkipped(SourceRange Range) override;
+  void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
 };
 
 namespace CodeGen {
Index: cfe/trunk/lib/Lex/PreprocessingRecord.cpp
===
--- cfe/trunk/lib/Lex/PreprocessingRecord.cpp
+++ cfe/trunk/lib/Lex/PreprocessingRecord.cpp
@@ -400,8 +400,9 @@
   MacroNameTok.getLocation());
 }
 
-void PreprocessingRecord::SourceRangeSkipped(SourceRange Range) {
-  SkippedRanges.push_back(Range);
+void PreprocessingRecord::SourceRangeSkipped(SourceRange Range,
+ SourceLocation EndifLoc) {
+  SkippedRanges.emplace_back(Range.getBegin(), EndifLoc);
 }
 
 void PreprocessingRecord::MacroExpands(const Token &Id,
Index: cfe/trunk/lib/Lex/PPDirectives.cpp
===
--- cfe/trunk/lib/Lex/PPDirectives.cpp
+++ cfe/trunk/lib/Lex/PPDirectives.cpp
@@ -79,7 +79,8 @@
 }
 
 /// \brief Read and discard all tokens remaining on the current line until
-/// the tok::eod token is found.
+/// the tok::eod token is found. If the discarded tokens are in a skipped range,
+/// complete the range and pass it to the \c SourceRangeSkipped callback.
 void Preprocessor::DiscardUntilEndOfDirective() {
   Token Tmp;
   do {
@@ -350,7 +351,8 @@
 /// If ElseOk is true, then \#else directives are ok, if not, then we have
 /// already seen one so a \#else directive is a duplicate.  When this returns,
 /// the caller can lex the first valid token.
-void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
+void Preprocessor::SkipExcludedConditionalBlock(const Token &HashToken,
+SourceLocation IfTokenLoc,
 bool FoundNonSkipPortion,
 bool FoundElse,
 SourceLocation ElseLoc) {
@@ -558,10 +560,10 @@
   // the #if block.
   CurPPLexer->LexingRawMode = false;
 
-  if (Callbacks) {
-SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
-Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
-  }
+  if (Callbacks)
+Callbacks->SourceRangeSkipped(
+SourceRange(HashToken.getLocation(), CurPPLexer->getSourceLocation()),
+Tok.getLocation());
 }
 
 void Preprocessor::PTHSkipExcludedConditionalBlock() {
@@ -949,15 +951,17 @@
 default: break;
 // C99 6.10.1 - Conditional Inclusion.
 case tok::pp_if:
-  return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
+  return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
 case tok::pp_ifdef:
-  return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
+  return HandleIfdefDirective(Result, SavedHash, false,
+  true /*not valid for miopt*/);
 case tok::pp_ifndef:
-  return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
+  return HandleIfdefDirective(Result, SavedHash, true,
+  ReadAnyTokensBeforeDirective);
 case tok::pp_elif:
-  return HandleElifDirective(Result);
+  return HandleElifDirective(Result, SavedHash);
 case tok::pp_else:
-  return HandleElseDirective(Result);
+  return Hand

[PATCH] D37577: [libclang] add 'clang_getCursorTLSKind'

2017-09-11 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd accepted this revision.
compnerd added inline comments.
This revision is now accepted and ready to land.



Comment at: bindings/python/tests/cindex/test_tls_kind.py:32
+__declspec(thread) int tls_declspec;
+""", lang = 'cpp', flags=['-fms-extensions', '-target', 'amd64-win32'])
+

Would be nicer to use `x86_64-unknown-windows-msvc` as the target.


https://reviews.llvm.org/D37577



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


[PATCH] D37529: [codeview] omit debug locations for nested exprs unless column info enabled

2017-09-11 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.h:32
 #include "clang/Basic/XRayLists.h"
+#include "clang/Frontend/CodeGenOptions.h"
 #include "llvm/ADT/DenseMap.h"

majnemer wrote:
> Any reason to do this? I'd just keep getNestedExpressionLocationsEnabled in 
> the .cpp file.
+1, I think we can continue to expect that ApplyDebugLocation will be used for 
expression emission and CodeGenFunction::EmitStopPoint (or whatever we rename 
it to) will be called for statements in CGStmt.


https://reviews.llvm.org/D37529



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


  1   2   >