[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-23 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

High level note: `clang::TypeAliasDecl` has the same issue as `CXXRecordDecl`, 
so templated versions should not be added to the DeclContext. Could you add 
that just for the sake of completeness?


Repository:
  rC Clang

https://reviews.llvm.org/D42301



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


[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-23 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I do not see a test for the following changes:

- ASTImporter: don't add templated declarations into DeclContext
- ASTImporter: proper set ParmVarDecls for imported FunctionProtoTypeLoc




Comment at: lib/AST/ASTImporter.cpp:2085
+  case FunctionDecl::TK_MemberSpecialization: {
+FunctionDecl *InstFD = cast_or_null(
+  Importer.Import(FromFD->getInstantiatedFromMemberFunction()));

Use `auto` to avoid repeating type.



Comment at: lib/AST/ASTImporter.cpp:2100
+auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
+FunctionTemplateDecl *Template = cast_or_null(
+Importer.Import(FTSInfo->getTemplate()));

Use `auto` to avoid repeating type.



Comment at: lib/AST/ASTImporter.cpp:2160
+
+  return false;
+}

Is the switch above meant to be exhaustive? If so, adding `LLVM_UNREACHABLE` 
here might be beneficial.



Comment at: lib/AST/ASTImporter.cpp:6138
+  CXXRecordDecl *FromClass = LE->getLambdaClass();
+  CXXRecordDecl *ToClass = dyn_cast_or_null(
+Importer.Import(FromClass));

Use `auto` to avoid repeting type.



Comment at: lib/AST/ASTStructuralEquivalence.cpp:1267
 
+static bool IsTemplateDeclStructurallyEquivalent(
+StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) {

The name if this function might be misleading. Only looking at the name I would 
assume that it is also checking for the templated decl itself not just the 
identifier and the template parameters. I think it would be nice to either 
change the functionality or the name.


Repository:
  rC Clang

https://reviews.llvm.org/D42301



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


[PATCH] D42373: [clang-format] Disable string literal breaking for text protos

2018-01-23 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added a comment.

I am not sure we should actually do this. I agree that badly reflowing 
multiline string literals is not ideal, but neither is violating the column 
limit. In any case, proper reflowing would probably the best solution. How hard 
would it be to implement that (for proto as well as C++)?


Repository:
  rC Clang

https://reviews.llvm.org/D42373



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


[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-23 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

> I do not see a test for the following changes:
> 
> - ASTImporter: don't add templated declarations into DeclContext

It's in ASTImporterTest. It checks that the templated decl cannot be found in 
the enclosing TU.

> - ASTImporter: proper set ParmVarDecls for imported FunctionProtoTypeLoc

test/ASTMerge/function-cpp. If you remove the change, Sema will segfault.


Repository:
  rC Clang

https://reviews.llvm.org/D42301



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


[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-23 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

In https://reviews.llvm.org/D42301#984713, @a.sidorin wrote:

> > I do not see a test for the following changes:
> > 
> > - ASTImporter: don't add templated declarations into DeclContext
>
> It's in ASTImporterTest. It checks that the templated decl cannot be found in 
> the enclosing TU.


Oh indeed, it looks likeI missed that, thanks :)

>> - ASTImporter: proper set ParmVarDecls for imported FunctionProtoTypeLoc
> 
> test/ASTMerge/function-cpp. If you remove the change, Sema will segfault.

Neat!


Repository:
  rC Clang

https://reviews.llvm.org/D42301



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


[PATCH] D42318: [ARM] Pass _Float16 as int or float

2018-01-23 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer updated this revision to Diff 131009.
SjoerdMeijer added a comment.

Moved the tests to the existing file (and fixed a few typos in the tests).


https://reviews.llvm.org/D42318

Files:
  include/clang/AST/Type.h
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/arm-fp16-arguments.c


Index: test/CodeGen/arm-fp16-arguments.c
===
--- test/CodeGen/arm-fp16-arguments.c
+++ test/CodeGen/arm-fp16-arguments.c
@@ -25,3 +25,27 @@
 // HARD: ret float [[BITCAST]]
 // NATIVE: [[LOAD:%.*]] = load half, half* @g
 // NATIVE: ret half [[LOAD]]
+
+_Float16 h;
+
+void t3(_Float16 a) { h = a; }
+// SOFT: define void @t3(i32 [[PARAM:%.*]])
+// SOFT: [[TRUNC:%.*]] = trunc i32 [[PARAM]] to i16
+// HARD: define arm_aapcs_vfpcc void @t3(float [[PARAM:%.*]])
+// HARD: [[BITCAST:%.*]] = bitcast float [[PARAM]] to i32
+// HARD: [[TRUNC:%.*]] = trunc i32 [[BITCAST]] to i16
+// CHECK: store i16 [[TRUNC]], i16* bitcast (half* @h to i16*)
+// NATIVE: define void @t3(half [[PARAM:%.*]])
+// NATIVE: store half [[PARAM]], half* @h
+
+_Float16 t4() { return h; }
+// SOFT: define i32 @t4()
+// HARD: define arm_aapcs_vfpcc float @t4()
+// NATIVE: define half @t4()
+// CHECK: [[LOAD:%.*]] = load i16, i16* bitcast (half* @h to i16*)
+// CHECK: [[ZEXT:%.*]] = zext i16 [[LOAD]] to i32
+// SOFT: ret i32 [[ZEXT]]
+// HARD: [[BITCAST:%.*]] = bitcast i32 [[ZEXT]] to float
+// HARD: ret float [[BITCAST]]
+// NATIVE: [[LOAD:%.*]] = load half, half* @h
+// NATIVE: ret half [[LOAD]]
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -5730,10 +5730,11 @@
 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
   }
 
-  // __fp16 gets passed as if it were an int or float, but with the top 16 bits
-  // unspecified. This is not done for OpenCL as it handles the half type
-  // natively, and does not need to interwork with AAPCS code.
-  if (Ty->isHalfType() && 
!getContext().getLangOpts().NativeHalfArgsAndReturns) {
+  // _Float16 and __fp16 get passed as if it were an int or float, but with
+  // the top 16 bits unspecified. This is not done for OpenCL as it handles the
+  // half type natively, and does not need to interwork with AAPCS code.
+  if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
+  !getContext().getLangOpts().NativeHalfArgsAndReturns) {
 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
   llvm::Type::getFloatTy(getVMContext()) :
   llvm::Type::getInt32Ty(getVMContext());
@@ -5928,10 +5929,11 @@
 return getNaturalAlignIndirect(RetTy);
   }
 
-  // __fp16 gets returned as if it were an int or float, but with the top 16
-  // bits unspecified. This is not done for OpenCL as it handles the half type
-  // natively, and does not need to interwork with AAPCS code.
-  if (RetTy->isHalfType() && 
!getContext().getLangOpts().NativeHalfArgsAndReturns) {
+  // _Float16 and __fp16 get returned as if it were an int or float, but with
+  // the top 16 bits unspecified. This is not done for OpenCL as it handles the
+  // half type natively, and does not need to interwork with AAPCS code.
+  if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
+  !getContext().getLangOpts().NativeHalfArgsAndReturns) {
 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
   llvm::Type::getFloatTy(getVMContext()) :
   llvm::Type::getInt32Ty(getVMContext());
Index: include/clang/AST/Type.h
===
--- include/clang/AST/Type.h
+++ include/clang/AST/Type.h
@@ -1730,6 +1730,7 @@
   bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
   bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
   bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
+  bool isFloat16Type() const;  // C11 extension ISO/IEC TS 18661
   bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
   bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
   bool isVoidType() const; // C99 6.2.5p19
@@ -6181,6 +6182,12 @@
   return false;
 }
 
+inline bool Type::isFloat16Type() const {
+  if (const BuiltinType *BT = dyn_cast(CanonicalType))
+return BT->getKind() == BuiltinType::Float16;
+  return false;
+}
+
 inline bool Type::isNullPtrType() const {
   if (const BuiltinType *BT = getAs())
 return BT->getKind() == BuiltinType::NullPtr;


Index: test/CodeGen/arm-fp16-arguments.c
===
--- test/CodeGen/arm-fp16-arguments.c
+++ test/CodeGen/arm-fp16-arguments.c
@@ -25,3 +25,27 @@
 // HARD: ret float [[BITCAST]]
 // NATIVE: [[LOAD:%.*]] = load half, half* @g
 // NATIVE: ret half [[LOAD]]
+
+_Float16 h;
+
+void t3(_Float16 a) { h = a; }
+// SOFT: define void @t3(i32 [[PARAM:%.*]])
+// SOFT: [[TRUNC:%.*]] = trunc i32 [[PARAM]] to i16
+// HARD: define arm_aapcs_vf

[PATCH] D42318: [ARM] Pass _Float16 as int or float

2018-01-23 Thread Sam Parker via Phabricator via cfe-commits
samparker accepted this revision.
samparker added a comment.
This revision is now accepted and ready to land.

Thanks for the explanation, LGTM, thanks!


https://reviews.llvm.org/D42318



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


[PATCH] D42363: [clang-tidy] Don't generate fixes for invalid new expr location in modernize-make-unique.

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

In https://reviews.llvm.org/D42363#983769, @hokein wrote:

> Yeah, we should fix the clang bug (root cause). But I think this patch still 
> makes sense -- as we usually ignore invalid cases in clang-tidy checks.


Sure, thanks for clarifying. LGTM.
It's a bit unfortunate that the test will break when we fix an actual bug in 
clang. But it's just something to watch out for, still nice to have a test 
after the bug is fixed.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42363



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


[PATCH] D35472: Implement P0463R1: "Endian just Endian"

2018-01-23 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: test/std/utilities/meta/meta.type.synop/endian.pass.cpp:10
+
+// UNSUPPORTED: c++98, c++03, c++11, c++14, c++1z
+

c++17, not c++1z
At least grep says there are no c++1z left in the libc++ tests.


https://reviews.llvm.org/D35472



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


r323185 - [ARM] Pass _Float16 as int or float

2018-01-23 Thread Sjoerd Meijer via cfe-commits
Author: sjoerdmeijer
Date: Tue Jan 23 02:13:49 2018
New Revision: 323185

URL: http://llvm.org/viewvc/llvm-project?rev=323185&view=rev
Log:
[ARM] Pass _Float16 as int or float

Pass and return _Float16 as if it were an int or float for ARM, but with the
top 16 bits unspecified, similarly like we already do for __fp16.

We will implement proper half-precision function argument lowering in the ARM
backend soon, but want to use this workaround in the mean time.

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

Modified:
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/lib/CodeGen/TargetInfo.cpp
cfe/trunk/test/CodeGen/arm-fp16-arguments.c

Modified: cfe/trunk/include/clang/AST/Type.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Type.h?rev=323185&r1=323184&r2=323185&view=diff
==
--- cfe/trunk/include/clang/AST/Type.h (original)
+++ cfe/trunk/include/clang/AST/Type.h Tue Jan 23 02:13:49 2018
@@ -1728,6 +1728,7 @@ public:
   bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
   bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
   bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
+  bool isFloat16Type() const;  // C11 extension ISO/IEC TS 18661
   bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
   bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
   bool isVoidType() const; // C99 6.2.5p19
@@ -6179,6 +6180,12 @@ inline bool Type::isHalfType() const {
   return false;
 }
 
+inline bool Type::isFloat16Type() const {
+  if (const BuiltinType *BT = dyn_cast(CanonicalType))
+return BT->getKind() == BuiltinType::Float16;
+  return false;
+}
+
 inline bool Type::isNullPtrType() const {
   if (const BuiltinType *BT = getAs())
 return BT->getKind() == BuiltinType::NullPtr;

Modified: cfe/trunk/lib/CodeGen/TargetInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/TargetInfo.cpp?rev=323185&r1=323184&r2=323185&view=diff
==
--- cfe/trunk/lib/CodeGen/TargetInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/TargetInfo.cpp Tue Jan 23 02:13:49 2018
@@ -5721,10 +5721,11 @@ ABIArgInfo ARMABIInfo::classifyArgumentT
 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
   }
 
-  // __fp16 gets passed as if it were an int or float, but with the top 16 bits
-  // unspecified. This is not done for OpenCL as it handles the half type
-  // natively, and does not need to interwork with AAPCS code.
-  if (Ty->isHalfType() && 
!getContext().getLangOpts().NativeHalfArgsAndReturns) {
+  // _Float16 and __fp16 get passed as if it were an int or float, but with
+  // the top 16 bits unspecified. This is not done for OpenCL as it handles the
+  // half type natively, and does not need to interwork with AAPCS code.
+  if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
+  !getContext().getLangOpts().NativeHalfArgsAndReturns) {
 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
   llvm::Type::getFloatTy(getVMContext()) :
   llvm::Type::getInt32Ty(getVMContext());
@@ -5919,10 +5920,11 @@ ABIArgInfo ARMABIInfo::classifyReturnTyp
 return getNaturalAlignIndirect(RetTy);
   }
 
-  // __fp16 gets returned as if it were an int or float, but with the top 16
-  // bits unspecified. This is not done for OpenCL as it handles the half type
-  // natively, and does not need to interwork with AAPCS code.
-  if (RetTy->isHalfType() && 
!getContext().getLangOpts().NativeHalfArgsAndReturns) {
+  // _Float16 and __fp16 get returned as if it were an int or float, but with
+  // the top 16 bits unspecified. This is not done for OpenCL as it handles the
+  // half type natively, and does not need to interwork with AAPCS code.
+  if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
+  !getContext().getLangOpts().NativeHalfArgsAndReturns) {
 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
   llvm::Type::getFloatTy(getVMContext()) :
   llvm::Type::getInt32Ty(getVMContext());

Modified: cfe/trunk/test/CodeGen/arm-fp16-arguments.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/arm-fp16-arguments.c?rev=323185&r1=323184&r2=323185&view=diff
==
--- cfe/trunk/test/CodeGen/arm-fp16-arguments.c (original)
+++ cfe/trunk/test/CodeGen/arm-fp16-arguments.c Tue Jan 23 02:13:49 2018
@@ -25,3 +25,27 @@ __fp16 t2() { return g; }
 // HARD: ret float [[BITCAST]]
 // NATIVE: [[LOAD:%.*]] = load half, half* @g
 // NATIVE: ret half [[LOAD]]
+
+_Float16 h;
+
+void t3(_Float16 a) { h = a; }
+// SOFT: define void @t3(i32 [[PARAM:%.*]])
+// SOFT: [[TRUNC:%.*]] = trunc i32 [[PARAM]] to i16
+// HARD: define arm_aapcs_vfpcc void @t3(float [[PARAM:%.*]])
+// HARD: [[BITCAST:%.*]] = bitcast float [[PARAM]] to i32
+// HARD: [[TRUNC:%

[PATCH] D42318: [ARM] Pass _Float16 as int or float

2018-01-23 Thread Sjoerd Meijer via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323185: [ARM] Pass _Float16 as int or float (authored by 
SjoerdMeijer, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42318?vs=131009&id=131011#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42318

Files:
  cfe/trunk/include/clang/AST/Type.h
  cfe/trunk/lib/CodeGen/TargetInfo.cpp
  cfe/trunk/test/CodeGen/arm-fp16-arguments.c


Index: cfe/trunk/include/clang/AST/Type.h
===
--- cfe/trunk/include/clang/AST/Type.h
+++ cfe/trunk/include/clang/AST/Type.h
@@ -1728,6 +1728,7 @@
   bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
   bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
   bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
+  bool isFloat16Type() const;  // C11 extension ISO/IEC TS 18661
   bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
   bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
   bool isVoidType() const; // C99 6.2.5p19
@@ -6179,6 +6180,12 @@
   return false;
 }
 
+inline bool Type::isFloat16Type() const {
+  if (const BuiltinType *BT = dyn_cast(CanonicalType))
+return BT->getKind() == BuiltinType::Float16;
+  return false;
+}
+
 inline bool Type::isNullPtrType() const {
   if (const BuiltinType *BT = getAs())
 return BT->getKind() == BuiltinType::NullPtr;
Index: cfe/trunk/test/CodeGen/arm-fp16-arguments.c
===
--- cfe/trunk/test/CodeGen/arm-fp16-arguments.c
+++ cfe/trunk/test/CodeGen/arm-fp16-arguments.c
@@ -25,3 +25,27 @@
 // HARD: ret float [[BITCAST]]
 // NATIVE: [[LOAD:%.*]] = load half, half* @g
 // NATIVE: ret half [[LOAD]]
+
+_Float16 h;
+
+void t3(_Float16 a) { h = a; }
+// SOFT: define void @t3(i32 [[PARAM:%.*]])
+// SOFT: [[TRUNC:%.*]] = trunc i32 [[PARAM]] to i16
+// HARD: define arm_aapcs_vfpcc void @t3(float [[PARAM:%.*]])
+// HARD: [[BITCAST:%.*]] = bitcast float [[PARAM]] to i32
+// HARD: [[TRUNC:%.*]] = trunc i32 [[BITCAST]] to i16
+// CHECK: store i16 [[TRUNC]], i16* bitcast (half* @h to i16*)
+// NATIVE: define void @t3(half [[PARAM:%.*]])
+// NATIVE: store half [[PARAM]], half* @h
+
+_Float16 t4() { return h; }
+// SOFT: define i32 @t4()
+// HARD: define arm_aapcs_vfpcc float @t4()
+// NATIVE: define half @t4()
+// CHECK: [[LOAD:%.*]] = load i16, i16* bitcast (half* @h to i16*)
+// CHECK: [[ZEXT:%.*]] = zext i16 [[LOAD]] to i32
+// SOFT: ret i32 [[ZEXT]]
+// HARD: [[BITCAST:%.*]] = bitcast i32 [[ZEXT]] to float
+// HARD: ret float [[BITCAST]]
+// NATIVE: [[LOAD:%.*]] = load half, half* @h
+// NATIVE: ret half [[LOAD]]
Index: cfe/trunk/lib/CodeGen/TargetInfo.cpp
===
--- cfe/trunk/lib/CodeGen/TargetInfo.cpp
+++ cfe/trunk/lib/CodeGen/TargetInfo.cpp
@@ -5721,10 +5721,11 @@
 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
   }
 
-  // __fp16 gets passed as if it were an int or float, but with the top 16 bits
-  // unspecified. This is not done for OpenCL as it handles the half type
-  // natively, and does not need to interwork with AAPCS code.
-  if (Ty->isHalfType() && 
!getContext().getLangOpts().NativeHalfArgsAndReturns) {
+  // _Float16 and __fp16 get passed as if it were an int or float, but with
+  // the top 16 bits unspecified. This is not done for OpenCL as it handles the
+  // half type natively, and does not need to interwork with AAPCS code.
+  if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
+  !getContext().getLangOpts().NativeHalfArgsAndReturns) {
 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
   llvm::Type::getFloatTy(getVMContext()) :
   llvm::Type::getInt32Ty(getVMContext());
@@ -5919,10 +5920,11 @@
 return getNaturalAlignIndirect(RetTy);
   }
 
-  // __fp16 gets returned as if it were an int or float, but with the top 16
-  // bits unspecified. This is not done for OpenCL as it handles the half type
-  // natively, and does not need to interwork with AAPCS code.
-  if (RetTy->isHalfType() && 
!getContext().getLangOpts().NativeHalfArgsAndReturns) {
+  // _Float16 and __fp16 get returned as if it were an int or float, but with
+  // the top 16 bits unspecified. This is not done for OpenCL as it handles the
+  // half type natively, and does not need to interwork with AAPCS code.
+  if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
+  !getContext().getLangOpts().NativeHalfArgsAndReturns) {
 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
   llvm::Type::getFloatTy(getVMContext()) :
   llvm::Type::getInt32Ty(getVMContext());


Index: cfe/trunk/include/clang/AST/Type.h
===
--- cfe/trunk/include/clang/AST/Type.h
+++ cfe/trunk/include/clang/AST/Type.h
@@ -1728,6

[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 131012.
krasimir added a comment.

- Address review comments


Repository:
  rC Clang

https://reviews.llvm.org/D42376

Files:
  lib/Format/BreakableToken.cpp
  lib/Format/BreakableToken.h
  lib/Format/ContinuationIndenter.cpp
  unittests/Format/FormatTestTextProto.cpp


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -290,5 +290,17 @@
"  product_data \n"
">");
 }
+
+TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
+  // The two closing braces count towards the string UnbreakableTailLength, but
+  // since we have broken after the corresponding opening braces, we don't
+  // consider that length for string breaking.
+  verifyFormat(
+  "foo: {\n"
+  "  bar: {\n"
+  "text: \"\"\n"
+  "  }\n"
+  "}");
+}
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1576,9 +1576,16 @@
   Text.startswith(Prefix = "u8\"") ||
   Text.startswith(Prefix = "L\""))) ||
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  // We need this to address the case where there is an unbreakable tail
+  // only if certain other formatting decisions have been taken. The
+  // UnbreakableTailLenght of Current is an overapproximation is that case
+  // and we need to be correct here.
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0
+   : Current.UnbreakableTailLength;
   return llvm::make_unique(
-  Current, StartColumn, Prefix, Postfix, State.Line->InPPDirective,
-  Encoding, Style);
+  Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
+  State.Line->InPPDirective, Encoding, Style);
 }
   } else if (Current.is(TT_BlockComment)) {
 if (!Style.ReflowComments ||
Index: lib/Format/BreakableToken.h
===
--- lib/Format/BreakableToken.h
+++ lib/Format/BreakableToken.h
@@ -238,8 +238,8 @@
   /// after formatting.
   BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn,
  StringRef Prefix, StringRef Postfix,
- bool InPPDirective, encoding::Encoding Encoding,
- const FormatStyle &Style);
+ unsigned UnbreakableTailLength, bool InPPDirective,
+ encoding::Encoding Encoding, const FormatStyle 
&Style);
 
   Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  unsigned ReflowColumn,
Index: lib/Format/BreakableToken.cpp
===
--- lib/Format/BreakableToken.cpp
+++ lib/Format/BreakableToken.cpp
@@ -214,11 +214,11 @@
 
 BreakableStringLiteral::BreakableStringLiteral(
 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
-StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
-const FormatStyle &Style)
+StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
+encoding::Encoding Encoding, const FormatStyle &Style)
 : BreakableToken(Tok, InPPDirective, Encoding, Style),
   StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
-  UnbreakableTailLength(Tok.UnbreakableTailLength) {
+  UnbreakableTailLength(UnbreakableTailLength) {
   assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
   Line = Tok.TokenText.substr(
   Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -290,5 +290,17 @@
"  product_data \n"
">");
 }
+
+TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
+  // The two closing braces count towards the string UnbreakableTailLength, but
+  // since we have broken after the corresponding opening braces, we don't
+  // consider that length for string breaking.
+  verifyFormat(
+  "foo: {\n"
+  "  bar: {\n"
+  "text: \"\"\n"
+  "  }\n"
+  "}");
+}
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/F

[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

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



Comment at: lib/Format/ContinuationIndenter.cpp:1579
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0

djasper wrote:
> I think a comment might help here. Specifically, it should mention that this 
> is required for the special case where there is an unbreakable tail only if 
> certain other formatting decisions have been taken. The UnbreakableTailLength 
> is an overapproximation in that case and we need to be correct here.
> 
> Thinking about this some more, there might actually be cases where this is 
> still not correct as the unbreakable tail is neither 0 nor the precomputed 
> value.
> 
> E.g. can we construct a case where there is a trailing comma in a braced 
> list? Maybe this:
> 
> vector x = {"aa",};
> 
> In this case, I think the comma will always be part of the string literal, 
> but the "};" only get part of the tail if we don't wrap after the "{".
In the `vector x = {"a",};` only the comma is part of the 
`UnbreakableTailLength` of the string:
```
M=1 C=1 T=Unknown S=0 B=0 BK=0 P=59 Name=string_literal L=100 PPK=2 
FakeLParens=1/ FakeRParens=0 Text='"a"'
M=0 C=0 T=Unknown S=0 B=0 BK=0 P=41 Name=comma L=101 PPK=2 FakeLParens= 
FakeRParens=1 Text=','
M=1 C=1 T=Unknown S=1 B=0 BK=0 P=41 Name=r_brace L=181 PPK=2 FakeLParens= 
FakeRParens=1 Text='}'
M=0 C=0 T=Unknown S=0 B=0 BK=0 P=23 Name=semi L=182 PPK=2 FakeLParens= 
FakeRParens=0 Text=';'

breakProtrudingToken: CanBreak=0, UnbreakableTailLength=1
```



Repository:
  rC Clang

https://reviews.llvm.org/D42376



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


[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 131013.
hokein marked 5 inline comments as done.
hokein added a comment.

Address remaining comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -58,6 +58,7 @@
 using ::testing::ElementsAre;
 using ::testing::Not;
 using ::testing::UnorderedElementsAre;
+using ::testing::Field;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
   void
@@ -676,6 +677,109 @@
   EXPECT_EQ(1, Results.activeParameter);
 }
 
+class IndexRequestCollector : public SymbolIndex {
+public:
+  bool
+  fuzzyFind(const Context &Ctx, const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+Requests.push_back(Req);
+return false;
+  }
+
+  const std::vector allRequests() const { return Requests; }
+
+private:
+  mutable std::vector Requests;
+};
+
+std::vector captureIndexRequests(llvm::StringRef Code) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+  auto Results = completions(Code, {}, Opts);
+
+  return Requests.allRequests();
+}
+
+TEST(CompletionTest, UnqualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+ namespace std {}
+ using namespace std;
+ namespace ns {
+ void f() {
+   vec^
+ }
+ }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns::", "std::";
+}
+
+TEST(CompletionTest, ResolvedQualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+ namespace ns1 {}
+ namespace ns2 {} // ignore
+ namespace ns3 { namespace nns3 {} }
+ namespace foo {
+ using namespace ns1;
+ using namespace ns3::nns3;
+ }
+ namespace ns {
+ void f() {
+   foo::^
+ }
+ }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(
+  &FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::";
+}
+
+TEST(CompletionTest, UnresolvedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("bar::";
+}
+
+TEST(CompletionTest, EmptyQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("", "ns::";
+}
+
+TEST(CompletionTest, GlobalQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -309,23 +309,100 @@
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
+// Scopes of the paritial identifier we're trying to complete.
+// It is used when we query the index for more completion results.
 struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", the
-  /// written scope specifier is "ns::".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Resolved;
-
-  llvm::StringRef forIndex() {
-return Resolved.empty() ? StringRef(Written).ltrim("::")
-: StringRef(Resolved);
+  // The scopes we should look in, determined by Sema.
+  //
+  // If the qualifier was fully resolved, we look for completions in these
+  // scopes; if there is an unresolved part of the qualifier, it should be
+  // resolved within these scopes.
+  //
+  // Examples of qualified completion:
+  //
+  //   "::vec"  => {""}
+  //   "using namespace std; ::vec^"=> {"", "std::"}
+  //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
+  //   "std::vec^"  => {""}  // "std" unresolved
+  //
+  // Examples of unqualif

[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/CodeComplete.cpp:653
+// Get all scopes that will be queried in indexes.
+std::vector getQueryScopes(Sema &S,
+CodeCompletionContext &CCContext) {

sammccall wrote:
> as Ilya pointed out to me, passing Sema around is a big scary thing that we 
> should try to avoid. Here it's only used to get the text if the CXXScopeSpec 
> is invalid. Can we pass just the SourceManager, or better yet, the text as a 
> StringPiece?
SG, we don't need the Sema to compute the `DeclContext` from scope specifier. 
SourceManager is the only thing we need from `Sema` now. 



Comment at: clangd/CodeComplete.cpp:695
+  Info.UnresolvedQualifier =
+  Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
+   S.getSourceManager(), clang::LangOptions());

sammccall wrote:
> do you need to remove any leading :: here?
Not needed, as Sema exclues the trailing "::". Added a comment.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073



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


[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 131014.
hokein added a comment.

Cleanup tests.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -58,6 +58,7 @@
 using ::testing::ElementsAre;
 using ::testing::Not;
 using ::testing::UnorderedElementsAre;
+using ::testing::Field;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
   void
@@ -676,6 +677,107 @@
   EXPECT_EQ(1, Results.activeParameter);
 }
 
+class IndexRequestCollector : public SymbolIndex {
+public:
+  bool
+  fuzzyFind(const Context &Ctx, const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+Requests.push_back(Req);
+return false;
+  }
+
+  const std::vector allRequests() const { return Requests; }
+
+private:
+  mutable std::vector Requests;
+};
+
+std::vector captureIndexRequests(llvm::StringRef Code) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+  return completions(Code, {}, Opts).allRequests();
+}
+
+TEST(CompletionTest, UnqualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+ namespace std {}
+ using namespace std;
+ namespace ns {
+ void f() {
+   vec^
+ }
+ }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns::", "std::";
+}
+
+TEST(CompletionTest, ResolvedQualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+ namespace ns1 {}
+ namespace ns2 {} // ignore
+ namespace ns3 { namespace nns3 {} }
+ namespace foo {
+ using namespace ns1;
+ using namespace ns3::nns3;
+ }
+ namespace ns {
+ void f() {
+   foo::^
+ }
+ }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(
+  &FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::";
+}
+
+TEST(CompletionTest, UnresolvedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("bar::";
+}
+
+TEST(CompletionTest, EmptyQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("", "ns::";
+}
+
+TEST(CompletionTest, GlobalQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -309,23 +309,100 @@
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
+// Scopes of the paritial identifier we're trying to complete.
+// It is used when we query the index for more completion results.
 struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", the
-  /// written scope specifier is "ns::".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Resolved;
-
-  llvm::StringRef forIndex() {
-return Resolved.empty() ? StringRef(Written).ltrim("::")
-: StringRef(Resolved);
+  // The scopes we should look in, determined by Sema.
+  //
+  // If the qualifier was fully resolved, we look for completions in these
+  // scopes; if there is an unresolved part of the qualifier, it should be
+  // resolved within these scopes.
+  //
+  // Examples of qualified completion:
+  //
+  //   "::vec"  => {""}
+  //   "using namespace std; ::vec^"=> {"", "std::"}
+  //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
+  //   "std::vec^"  => {""}  // "std" unresolved
+  //
+  // Examples of unqualified completion:
+  //
+  //   "vec^"   => {""}
+

[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 131018.
hokein added a comment.

remove the leading "::".


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -58,6 +58,7 @@
 using ::testing::ElementsAre;
 using ::testing::Not;
 using ::testing::UnorderedElementsAre;
+using ::testing::Field;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
   void
@@ -676,6 +677,123 @@
   EXPECT_EQ(1, Results.activeParameter);
 }
 
+class IndexRequestCollector : public SymbolIndex {
+public:
+  bool
+  fuzzyFind(const Context &Ctx, const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+Requests.push_back(Req);
+return false;
+  }
+
+  const std::vector allRequests() const { return Requests; }
+
+private:
+  mutable std::vector Requests;
+};
+
+std::vector captureIndexRequests(llvm::StringRef Code) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+  completions(Code, {}, Opts);
+  return Requests.allRequests();
+}
+
+TEST(CompletionTest, UnqualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+ namespace std {}
+ using namespace std;
+ namespace ns {
+ void f() {
+   vec^
+ }
+ }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns::", "std::";
+}
+
+TEST(CompletionTest, ResolvedQualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+ namespace ns1 {}
+ namespace ns2 {} // ignore
+ namespace ns3 { namespace nns3 {} }
+ namespace foo {
+ using namespace ns1;
+ using namespace ns3::nns3;
+ }
+ namespace ns {
+ void f() {
+   foo::^
+ }
+ }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(
+  &FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::";
+}
+
+TEST(CompletionTest, UnresolvedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("bar::";
+}
+
+TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  ::a::bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("a::bar::";
+}
+
+TEST(CompletionTest, EmptyQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("", "ns::";
+}
+
+TEST(CompletionTest, GlobalQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -309,23 +309,100 @@
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
+// Scopes of the paritial identifier we're trying to complete.
+// It is used when we query the index for more completion results.
 struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", the
-  /// written scope specifier is "ns::".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Resolved;
-
-  llvm::StringRef forIndex() {
-return Resolved.empty() ? StringRef(Written).ltrim("::")
-: StringRef(Resolved);
+  // The scopes we should look in, determined by Sema.
+  //
+  // If the qualifier was fully resolved, we look for completions in these
+  // scopes; if there is an unresolved part of the qualifier, it should be
+  // resolved within these scopes.
+  //
+  // Examples of qualified completion:

[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/CodeComplete.cpp:695
+  Info.UnresolvedQualifier =
+  Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
+   S.getSourceManager(), clang::LangOptions());

hokein wrote:
> sammccall wrote:
> > do you need to remove any leading :: here?
> Not needed, as Sema exclues the trailing "::". Added a comment.
Aha, sorry -- I misread the comment. Yeah, we need to remove the leading "::", 
added a test to catch this bug.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073



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


[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:1579
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0

krasimir wrote:
> djasper wrote:
> > I think a comment might help here. Specifically, it should mention that 
> > this is required for the special case where there is an unbreakable tail 
> > only if certain other formatting decisions have been taken. The 
> > UnbreakableTailLength is an overapproximation in that case and we need to 
> > be correct here.
> > 
> > Thinking about this some more, there might actually be cases where this is 
> > still not correct as the unbreakable tail is neither 0 nor the precomputed 
> > value.
> > 
> > E.g. can we construct a case where there is a trailing comma in a braced 
> > list? Maybe this:
> > 
> > vector x = {"aa",};
> > 
> > In this case, I think the comma will always be part of the string literal, 
> > but the "};" only get part of the tail if we don't wrap after the "{".
> In the `vector x = {"a",};` only the comma is part of the 
> `UnbreakableTailLength` of the string:
> ```
> M=1 C=1 T=Unknown S=0 B=0 BK=0 P=59 Name=string_literal L=100 PPK=2 
> FakeLParens=1/ FakeRParens=0 Text='"a"'
> M=0 C=0 T=Unknown S=0 B=0 BK=0 P=41 Name=comma L=101 PPK=2 FakeLParens= 
> FakeRParens=1 Text=','
> M=1 C=1 T=Unknown S=1 B=0 BK=0 P=41 Name=r_brace L=181 PPK=2 FakeLParens= 
> FakeRParens=1 Text='}'
> M=0 C=0 T=Unknown S=0 B=0 BK=0 P=23 Name=semi L=182 PPK=2 FakeLParens= 
> FakeRParens=0 Text=';'
> 
> breakProtrudingToken: CanBreak=0, UnbreakableTailLength=1
> ```
> 
Ok. The comma works around this by forcing a break before the "}". But what 
about:

  vector x = {"abc" /*comment*/};

The comment should be an unbreakable tail.


Repository:
  rC Clang

https://reviews.llvm.org/D42376



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


[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 131019.
hokein added a comment.

Format the test code.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -58,6 +58,7 @@
 using ::testing::ElementsAre;
 using ::testing::Not;
 using ::testing::UnorderedElementsAre;
+using ::testing::Field;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
   void
@@ -676,6 +677,123 @@
   EXPECT_EQ(1, Results.activeParameter);
 }
 
+class IndexRequestCollector : public SymbolIndex {
+public:
+  bool
+  fuzzyFind(const Context &Ctx, const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+Requests.push_back(Req);
+return false;
+  }
+
+  const std::vector allRequests() const { return Requests; }
+
+private:
+  mutable std::vector Requests;
+};
+
+std::vector captureIndexRequests(llvm::StringRef Code) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+  completions(Code, {}, Opts);
+  return Requests.allRequests();
+}
+
+TEST(CompletionTest, UnqualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace std {}
+  using namespace std;
+  namespace ns {
+  void f() {
+vec^
+  }
+  }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns::", "std::";
+}
+
+TEST(CompletionTest, ResolvedQualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns1 {}
+  namespace ns2 {} // ignore
+  namespace ns3 { namespace nns3 {} }
+  namespace foo {
+  using namespace ns1;
+  using namespace ns3::nns3;
+  }
+  namespace ns {
+  void f() {
+foo::^
+  }
+  }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(
+  &FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::";
+}
+
+TEST(CompletionTest, UnresolvedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("bar::";
+}
+
+TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  ::a::bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("a::bar::";
+}
+
+TEST(CompletionTest, EmptyQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("", "ns::";
+}
+
+TEST(CompletionTest, GlobalQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -309,23 +309,100 @@
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
+// Scopes of the paritial identifier we're trying to complete.
+// It is used when we query the index for more completion results.
 struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", the
-  /// written scope specifier is "ns::".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Resolved;
-
-  llvm::StringRef forIndex() {
-return Resolved.empty() ? StringRef(Written).ltrim("::")
-: StringRef(Resolved);
+  // The scopes we should look in, determined by Sema.
+  //
+  // If the qualifier was fully resolved, we look for completions in these
+  // scopes; if there is an unresolved part o

[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:1579
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0

djasper wrote:
> krasimir wrote:
> > djasper wrote:
> > > I think a comment might help here. Specifically, it should mention that 
> > > this is required for the special case where there is an unbreakable tail 
> > > only if certain other formatting decisions have been taken. The 
> > > UnbreakableTailLength is an overapproximation in that case and we need to 
> > > be correct here.
> > > 
> > > Thinking about this some more, there might actually be cases where this 
> > > is still not correct as the unbreakable tail is neither 0 nor the 
> > > precomputed value.
> > > 
> > > E.g. can we construct a case where there is a trailing comma in a braced 
> > > list? Maybe this:
> > > 
> > > vector x = {"aa",};
> > > 
> > > In this case, I think the comma will always be part of the string 
> > > literal, but the "};" only get part of the tail if we don't wrap after 
> > > the "{".
> > In the `vector x = {"a",};` only the comma is part of the 
> > `UnbreakableTailLength` of the string:
> > ```
> > M=1 C=1 T=Unknown S=0 B=0 BK=0 P=59 Name=string_literal L=100 PPK=2 
> > FakeLParens=1/ FakeRParens=0 Text='"a"'
> > M=0 C=0 T=Unknown S=0 B=0 BK=0 P=41 Name=comma L=101 PPK=2 FakeLParens= 
> > FakeRParens=1 Text=','
> > M=1 C=1 T=Unknown S=1 B=0 BK=0 P=41 Name=r_brace L=181 PPK=2 FakeLParens= 
> > FakeRParens=1 Text='}'
> > M=0 C=0 T=Unknown S=0 B=0 BK=0 P=23 Name=semi L=182 PPK=2 FakeLParens= 
> > FakeRParens=0 Text=';'
> > 
> > breakProtrudingToken: CanBreak=0, UnbreakableTailLength=1
> > ```
> > 
> Ok. The comma works around this by forcing a break before the "}". But what 
> about:
> 
>   vector x = {"abc" /*comment*/};
> 
> The comment should be an unbreakable tail.
As you discovered, the comment-in-tail case is special-cased in the unbreakable 
tail computation, so this is not an issue.


Repository:
  rC Clang

https://reviews.llvm.org/D42376



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


[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Happy to go forward with this. I think we might also wanna investigate whether 
entirely removing UnbreakableTailLength would be beneficial. I think we 
implemented it as an optimization, but I can actually imagine it saving much. 
Plus the code would be simpler and we would conserve some memory.


Repository:
  rC Clang

https://reviews.llvm.org/D42376



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


[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 131023.
krasimir marked 3 inline comments as done.
krasimir added a comment.

- Update comment


Repository:
  rC Clang

https://reviews.llvm.org/D42376

Files:
  lib/Format/BreakableToken.cpp
  lib/Format/BreakableToken.h
  lib/Format/ContinuationIndenter.cpp
  unittests/Format/FormatTestTextProto.cpp


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -290,5 +290,17 @@
"  product_data \n"
">");
 }
+
+TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
+  // The two closing braces count towards the string UnbreakableTailLength, but
+  // since we have broken after the corresponding opening braces, we don't
+  // consider that length for string breaking.
+  verifyFormat(
+  "foo: {\n"
+  "  bar: {\n"
+  "text: \"\"\n"
+  "  }\n"
+  "}");
+}
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1576,9 +1576,16 @@
   Text.startswith(Prefix = "u8\"") ||
   Text.startswith(Prefix = "L\""))) ||
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  // We need this to address the case where there is an unbreakable tail
+  // only if certain other formatting decisions have been taken. The
+  // UnbreakableTailLength of Current is an overapproximation is that case
+  // and we need to be correct here.
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0
+   : Current.UnbreakableTailLength;
   return llvm::make_unique(
-  Current, StartColumn, Prefix, Postfix, State.Line->InPPDirective,
-  Encoding, Style);
+  Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
+  State.Line->InPPDirective, Encoding, Style);
 }
   } else if (Current.is(TT_BlockComment)) {
 if (!Style.ReflowComments ||
Index: lib/Format/BreakableToken.h
===
--- lib/Format/BreakableToken.h
+++ lib/Format/BreakableToken.h
@@ -238,8 +238,8 @@
   /// after formatting.
   BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn,
  StringRef Prefix, StringRef Postfix,
- bool InPPDirective, encoding::Encoding Encoding,
- const FormatStyle &Style);
+ unsigned UnbreakableTailLength, bool InPPDirective,
+ encoding::Encoding Encoding, const FormatStyle 
&Style);
 
   Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  unsigned ReflowColumn,
Index: lib/Format/BreakableToken.cpp
===
--- lib/Format/BreakableToken.cpp
+++ lib/Format/BreakableToken.cpp
@@ -214,11 +214,11 @@
 
 BreakableStringLiteral::BreakableStringLiteral(
 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
-StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
-const FormatStyle &Style)
+StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
+encoding::Encoding Encoding, const FormatStyle &Style)
 : BreakableToken(Tok, InPPDirective, Encoding, Style),
   StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
-  UnbreakableTailLength(Tok.UnbreakableTailLength) {
+  UnbreakableTailLength(UnbreakableTailLength) {
   assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
   Line = Tok.TokenText.substr(
   Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -290,5 +290,17 @@
"  product_data \n"
">");
 }
+
+TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
+  // The two closing braces count towards the string UnbreakableTailLength, but
+  // since we have broken after the corresponding opening braces, we don't
+  // consider that length for string breaking.
+  verifyFormat(
+  "foo: {\n"
+  "  bar: {\n"
+  "text: \"\"\n"
+  "  }\n"
+  "}");
+}
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/

[PATCH] D42373: [clang-format] Disable string literal breaking for text protos

2018-01-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

Let's not do this then. For reflowing string literals, it could take a 
two-three months.


Repository:
  rC Clang

https://reviews.llvm.org/D42373



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


r323188 - [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Jan 23 03:26:19 2018
New Revision: 323188

URL: http://llvm.org/viewvc/llvm-project?rev=323188&view=rev
Log:
[clang-format] Ignore UnbreakableTailLength sometimes during breaking

Summary:
This patch fixes an issue where the UnbreakableTailLength would be counted 
towards
the length of a token during breaking, even though we can break after the token.

For example, this proto text with column limit 20
```
# ColumnLimit: 20  V
foo: {
  bar: {
bazoo: "aaa"
  }
}
```
was broken:
```
# ColumnLimit: 20  V
foo: {
  bar: {
bazoo:
"aaa"
  }
}
```
because the 2 closing `}` were counted towards the string literal's 
`UnbreakableTailLength`.

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/lib/Format/BreakableToken.h
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=323188&r1=323187&r2=323188&view=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Tue Jan 23 03:26:19 2018
@@ -214,11 +214,11 @@ unsigned BreakableStringLiteral::getCont
 
 BreakableStringLiteral::BreakableStringLiteral(
 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
-StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
-const FormatStyle &Style)
+StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
+encoding::Encoding Encoding, const FormatStyle &Style)
 : BreakableToken(Tok, InPPDirective, Encoding, Style),
   StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
-  UnbreakableTailLength(Tok.UnbreakableTailLength) {
+  UnbreakableTailLength(UnbreakableTailLength) {
   assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
   Line = Tok.TokenText.substr(
   Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());

Modified: cfe/trunk/lib/Format/BreakableToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.h?rev=323188&r1=323187&r2=323188&view=diff
==
--- cfe/trunk/lib/Format/BreakableToken.h (original)
+++ cfe/trunk/lib/Format/BreakableToken.h Tue Jan 23 03:26:19 2018
@@ -238,8 +238,8 @@ public:
   /// after formatting.
   BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn,
  StringRef Prefix, StringRef Postfix,
- bool InPPDirective, encoding::Encoding Encoding,
- const FormatStyle &Style);
+ unsigned UnbreakableTailLength, bool InPPDirective,
+ encoding::Encoding Encoding, const FormatStyle 
&Style);
 
   Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  unsigned ReflowColumn,

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=323188&r1=323187&r2=323188&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Tue Jan 23 03:26:19 2018
@@ -1576,9 +1576,16 @@ std::unique_ptr Continua
   Text.startswith(Prefix = "u8\"") ||
   Text.startswith(Prefix = "L\""))) ||
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  // We need this to address the case where there is an unbreakable tail
+  // only if certain other formatting decisions have been taken. The
+  // UnbreakableTailLength of Current is an overapproximation is that case
+  // and we need to be correct here.
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0
+   : Current.UnbreakableTailLength;
   return llvm::make_unique(
-  Current, StartColumn, Prefix, Postfix, State.Line->InPPDirective,
-  Encoding, Style);
+  Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
+  State.Line->InPPDirective, Encoding, Style);
 }
   } else if (Current.is(TT_BlockComment)) {
 if (!Style.ReflowComments ||

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=323188&r1=323187&r2=323188&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestTex

[PATCH] D42376: [clang-format] Ignore UnbreakableTailLength sometimes during breaking

2018-01-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323188: [clang-format] Ignore UnbreakableTailLength 
sometimes during breaking (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42376

Files:
  cfe/trunk/lib/Format/BreakableToken.cpp
  cfe/trunk/lib/Format/BreakableToken.h
  cfe/trunk/lib/Format/ContinuationIndenter.cpp
  cfe/trunk/unittests/Format/FormatTestTextProto.cpp


Index: cfe/trunk/lib/Format/BreakableToken.cpp
===
--- cfe/trunk/lib/Format/BreakableToken.cpp
+++ cfe/trunk/lib/Format/BreakableToken.cpp
@@ -214,11 +214,11 @@
 
 BreakableStringLiteral::BreakableStringLiteral(
 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
-StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
-const FormatStyle &Style)
+StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
+encoding::Encoding Encoding, const FormatStyle &Style)
 : BreakableToken(Tok, InPPDirective, Encoding, Style),
   StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
-  UnbreakableTailLength(Tok.UnbreakableTailLength) {
+  UnbreakableTailLength(UnbreakableTailLength) {
   assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
   Line = Tok.TokenText.substr(
   Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
Index: cfe/trunk/lib/Format/ContinuationIndenter.cpp
===
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp
@@ -1576,9 +1576,16 @@
   Text.startswith(Prefix = "u8\"") ||
   Text.startswith(Prefix = "L\""))) ||
 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) 
{
+  // We need this to address the case where there is an unbreakable tail
+  // only if certain other formatting decisions have been taken. The
+  // UnbreakableTailLength of Current is an overapproximation is that case
+  // and we need to be correct here.
+  unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
+   ? 0
+   : Current.UnbreakableTailLength;
   return llvm::make_unique(
-  Current, StartColumn, Prefix, Postfix, State.Line->InPPDirective,
-  Encoding, Style);
+  Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
+  State.Line->InPPDirective, Encoding, Style);
 }
   } else if (Current.is(TT_BlockComment)) {
 if (!Style.ReflowComments ||
Index: cfe/trunk/lib/Format/BreakableToken.h
===
--- cfe/trunk/lib/Format/BreakableToken.h
+++ cfe/trunk/lib/Format/BreakableToken.h
@@ -238,8 +238,8 @@
   /// after formatting.
   BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn,
  StringRef Prefix, StringRef Postfix,
- bool InPPDirective, encoding::Encoding Encoding,
- const FormatStyle &Style);
+ unsigned UnbreakableTailLength, bool InPPDirective,
+ encoding::Encoding Encoding, const FormatStyle 
&Style);
 
   Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  unsigned ReflowColumn,
Index: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
===
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp
@@ -290,5 +290,17 @@
"  product_data \n"
">");
 }
+
+TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
+  // The two closing braces count towards the string UnbreakableTailLength, but
+  // since we have broken after the corresponding opening braces, we don't
+  // consider that length for string breaking.
+  verifyFormat(
+  "foo: {\n"
+  "  bar: {\n"
+  "text: \"\"\n"
+  "  }\n"
+  "}");
+}
 } // end namespace tooling
 } // end namespace clang


Index: cfe/trunk/lib/Format/BreakableToken.cpp
===
--- cfe/trunk/lib/Format/BreakableToken.cpp
+++ cfe/trunk/lib/Format/BreakableToken.cpp
@@ -214,11 +214,11 @@
 
 BreakableStringLiteral::BreakableStringLiteral(
 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
-StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
-const FormatStyle &Style)
+StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
+encoding::Encoding Encoding, const FormatStyle &Style)
 : BreakableToken(Tok, InPPDirective, Enc

[PATCH] D41629: [libcxx] Improve accuracy of complex asinh and acosh

2018-01-23 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki added a comment.

ping^2


https://reviews.llvm.org/D41629



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


[clang-tools-extra] r323189 - [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Jan 23 03:37:26 2018
New Revision: 323189

URL: http://llvm.org/viewvc/llvm-project?rev=323189&view=rev
Log:
[clangd] Use accessible scopes to query indexes for global code completion.

Summary:
 * For qualified completion (foo::a^)
   * unresolved qualifier - use global namespace ("::")
   * resolved qualifier - use all accessible namespaces inside the resolved 
qualifier.
 * For unqualified completion (vec^), use scopes that are accessible from the
  scope from which code completion occurs.

Reviewers: sammccall, ilya-biryukov

Reviewed By: sammccall

Subscribers: jkorous-apple, ioeric, klimek, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=323189&r1=323188&r2=323189&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Tue Jan 23 03:37:26 2018
@@ -309,23 +309,100 @@ llvm::Optional getSymbolID(con
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
+// Scopes of the paritial identifier we're trying to complete.
+// It is used when we query the index for more completion results.
 struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", 
the
-  /// written scope specifier is "ns::".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Resolved;
-
-  llvm::StringRef forIndex() {
-return Resolved.empty() ? StringRef(Written).ltrim("::")
-: StringRef(Resolved);
+  // The scopes we should look in, determined by Sema.
+  //
+  // If the qualifier was fully resolved, we look for completions in these
+  // scopes; if there is an unresolved part of the qualifier, it should be
+  // resolved within these scopes.
+  //
+  // Examples of qualified completion:
+  //
+  //   "::vec"  => {""}
+  //   "using namespace std; ::vec^"=> {"", "std::"}
+  //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
+  //   "std::vec^"  => {""}  // "std" 
unresolved
+  //
+  // Examples of unqualified completion:
+  //
+  //   "vec^"   => {""}
+  //   "using namespace std; vec^"  => {"", "std::"}
+  //   "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
+  //
+  // "" for global namespace, "ns::" for normal namespace.
+  std::vector AccessibleScopes;
+  // The full scope qualifier as typed by the user (without the leading "::").
+  // Set if the qualifier is not fully resolved by Sema.
+  llvm::Optional UnresolvedQualifier;
+
+  // Construct scopes being queried in indexes.
+  // This method format the scopes to match the index request representation.
+  std::vector scopesForIndexQuery() {
+std::vector Results;
+for (llvm::StringRef AS : AccessibleScopes) {
+  Results.push_back(AS);
+  if (UnresolvedQualifier)
+Results.back() += *UnresolvedQualifier;
+}
+return Results;
   }
 };
 
+// Get all scopes that will be queried in indexes.
+std::vector getQueryScopes(CodeCompletionContext &CCContext,
+const SourceManager& SM) {
+  auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) {
+SpecifiedScope Info;
+for (auto* Context : CCContext.getVisitedContexts()) {
+  if (isa(Context))
+Info.AccessibleScopes.push_back(""); // global namespace
+  else if (const auto*NS = dyn_cast(Context))
+Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
+}
+return Info;
+  };
+
+  auto SS = CCContext.getCXXScopeSpecifier();
+
+  // Unqualified completion (e.g. "vec^").
+  if (!SS) {
+// FIXME: Once we can insert namespace qualifiers and use the in-scope
+//namespaces for scoring, search in all namespaces.
+// FIXME: Capture scopes and use for scoring, for example,
+//"using namespace std; namespace foo {v^}" =>
+//foo::value > std::vector > boost::variant
+return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
+  }
+
+  // Qualified completion ("std::vec^"), we have two cases depending on whether
+  // the qualifier can be resolved by Sema.
+  if ((*SS)->isValid()) { // Resolved qualifier.
+// FIXME: Disable Sema typo correction during code completion.
+//

[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323189: [clangd] Use accessible scopes to query indexes for 
global code completion. (authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42073

Files:
  clang-tools-extra/trunk/clangd/CodeComplete.cpp
  clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
@@ -58,6 +58,7 @@
 using ::testing::ElementsAre;
 using ::testing::Not;
 using ::testing::UnorderedElementsAre;
+using ::testing::Field;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
   void
@@ -676,6 +677,123 @@
   EXPECT_EQ(1, Results.activeParameter);
 }
 
+class IndexRequestCollector : public SymbolIndex {
+public:
+  bool
+  fuzzyFind(const Context &Ctx, const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+Requests.push_back(Req);
+return false;
+  }
+
+  const std::vector allRequests() const { return Requests; }
+
+private:
+  mutable std::vector Requests;
+};
+
+std::vector captureIndexRequests(llvm::StringRef Code) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+  completions(Code, {}, Opts);
+  return Requests.allRequests();
+}
+
+TEST(CompletionTest, UnqualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace std {}
+  using namespace std;
+  namespace ns {
+  void f() {
+vec^
+  }
+  }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns::", "std::";
+}
+
+TEST(CompletionTest, ResolvedQualifiedIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns1 {}
+  namespace ns2 {} // ignore
+  namespace ns3 { namespace nns3 {} }
+  namespace foo {
+  using namespace ns1;
+  using namespace ns3::nns3;
+  }
+  namespace ns {
+  void f() {
+foo::^
+  }
+  }
+  )cpp");
+
+  EXPECT_THAT(Requests,
+  ElementsAre(Field(
+  &FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::";
+}
+
+TEST(CompletionTest, UnresolvedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("bar::";
+}
+
+TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  ::a::bar::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("a::bar::";
+}
+
+TEST(CompletionTest, EmptyQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("", "ns::";
+}
+
+TEST(CompletionTest, GlobalQualifiedQuery) {
+  auto Requests = captureIndexRequests(R"cpp(
+  namespace ns {
+  void f() {
+  ::^
+  }
+  } // namespace ns
+  )cpp");
+
+  EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
+  UnorderedElementsAre("";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/CodeComplete.cpp
===
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp
@@ -309,23 +309,100 @@
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
+// Scopes of the paritial identifier we're trying to complete.
+// It is used when we query the index for more completion results.
 struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", the
-  /// written scope specifier is "ns::".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Re

[PATCH] D42413: [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via Phabricator via cfe-commits
malcolm.parsons created this revision.
malcolm.parsons added reviewers: aaron.ballman, alexfh.
Herald added subscribers: cfe-commits, xazax.hun, klimek.

C++2a allows bitfields to have default member initializers.
Add support for this to clang-tidy's modernize-use-default-member-init check.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42413

Files:
  clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  test/clang-tidy/modernize-use-default-member-init-bitfield.cpp


Index: test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- 
-std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};
Index: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -162,17 +162,29 @@
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
 declRefExpr(to(enumConstantDecl(;
 
-  Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
-  .bind("default"))),
-  this);
+  if (getLangOpts().CPlusPlus2a)
+Finder->addMatcher(
+cxxConstructorDecl(
+isDefaultConstructor(), unless(isInstantiated()),
+forEachConstructorInitializer(
+cxxCtorInitializer(
+forField(unless(anyOf(hasInClassInitializer(anything()),
+  hasParent(recordDecl(isUnion()),
+isWritten(), withInitializer(ignoringImplicit(Init)))
+.bind("default"))),
+this);
+  else
+Finder->addMatcher(
+cxxConstructorDecl(
+isDefaultConstructor(), unless(isInstantiated()),
+forEachConstructorInitializer(
+cxxCtorInitializer(
+forField(unless(anyOf(isBitField(),
+  hasInClassInitializer(anything()),
+  hasParent(recordDecl(isUnion()),
+isWritten(), withInitializer(ignoringImplicit(Init)))
+.bind("default"))),
+this);
 
   Finder->addMatcher(
   cxxConstructorDecl(


Index: test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- -std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};
Index: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -162,17 +162,29 @@
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
 declRefExpr(to(enumConstantDecl(;
 
-  Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
-  .bind("default"))),
-  this);
+  if (getLangOpts().CPlusPlus2a)
+Finder->addMatcher(
+cxxConstructorDecl(
+isDefaultConstructor(), unless(isInstantiated()),
+forEachConstructorInitializer(
+cxxCtorInitializer(
+forField(unless(anyOf(hasInClassInitializer(anything()),
+ 

[clang-tools-extra] r323191 - [clang-tidy] Don't generate fixes for invalid new expr location in modernize-make-unique.

2018-01-23 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Jan 23 03:43:18 2018
New Revision: 323191

URL: http://llvm.org/viewvc/llvm-project?rev=323191&view=rev
Log:
[clang-tidy] Don't generate fixes for invalid new expr location in 
modernize-make-unique.

Reviewers: ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: klimek, xazax.hun, cfe-commits

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

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp?rev=323191&r1=323190&r2=323191&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp Tue Jan 
23 03:43:18 2018
@@ -241,6 +241,10 @@ bool MakeSmartPtrCheck::replaceNew(Diagn
   SourceLocation NewStart = New->getSourceRange().getBegin();
   SourceLocation NewEnd = New->getSourceRange().getEnd();
 
+  // Skip when the source location of the new expression is invalid.
+  if (NewStart.isInvalid() || NewEnd.isInvalid())
+return false;
+
   std::string ArraySizeExpr;
   if (const auto* ArraySize = New->getArraySize()) {
 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange(

Modified: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp?rev=323191&r1=323190&r2=323191&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp (original)
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp Tue Jan 
23 03:43:18 2018
@@ -498,3 +498,12 @@ void invoke_template() {
   Foo* foo;
   template_fun(foo);
 }
+
+void no_fix_for_invalid_new_loc() {
+  // FIXME: Although the code is valid, the end location of `new struct Base` 
is
+  // invalid. Correct it once https://bugs.llvm.org/show_bug.cgi?id=35952 is
+  // fixed.
+  auto T = std::unique_ptr(new struct Base);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::make_unique instead
+  // CHECK-FIXES: auto T = std::unique_ptr(new struct Base);
+}


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


[PATCH] D42363: [clang-tidy] Don't generate fixes for invalid new expr location in modernize-make-unique.

2018-01-23 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323191: [clang-tidy] Don't generate fixes for invalid 
new expr location in modernize… (authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42363

Files:
  clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp


Index: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -241,6 +241,10 @@
   SourceLocation NewStart = New->getSourceRange().getBegin();
   SourceLocation NewEnd = New->getSourceRange().getEnd();
 
+  // Skip when the source location of the new expression is invalid.
+  if (NewStart.isInvalid() || NewEnd.isInvalid())
+return false;
+
   std::string ArraySizeExpr;
   if (const auto* ArraySize = New->getArraySize()) {
 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange(
Index: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
@@ -498,3 +498,12 @@
   Foo* foo;
   template_fun(foo);
 }
+
+void no_fix_for_invalid_new_loc() {
+  // FIXME: Although the code is valid, the end location of `new struct Base` 
is
+  // invalid. Correct it once https://bugs.llvm.org/show_bug.cgi?id=35952 is
+  // fixed.
+  auto T = std::unique_ptr(new struct Base);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::make_unique instead
+  // CHECK-FIXES: auto T = std::unique_ptr(new struct Base);
+}


Index: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -241,6 +241,10 @@
   SourceLocation NewStart = New->getSourceRange().getBegin();
   SourceLocation NewEnd = New->getSourceRange().getEnd();
 
+  // Skip when the source location of the new expression is invalid.
+  if (NewStart.isInvalid() || NewEnd.isInvalid())
+return false;
+
   std::string ArraySizeExpr;
   if (const auto* ArraySize = New->getArraySize()) {
 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange(
Index: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
@@ -498,3 +498,12 @@
   Foo* foo;
   template_fun(foo);
 }
+
+void no_fix_for_invalid_new_loc() {
+  // FIXME: Although the code is valid, the end location of `new struct Base` is
+  // invalid. Correct it once https://bugs.llvm.org/show_bug.cgi?id=35952 is
+  // fixed.
+  auto T = std::unique_ptr(new struct Base);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::make_unique instead
+  // CHECK-FIXES: auto T = std::unique_ptr(new struct Base);
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42170: Fixit for 'typedef' instead of 'typename' typo

2018-01-23 Thread Jan Korous via Phabricator via cfe-commits
jkorous-apple added inline comments.



Comment at: Parse/ParseTemplate.cpp:492
+  // Is there just a typo in the input code? ('typedef' instead of 'typename')
+  if (Tok.is(tok::kw_typedef)) {
+Diag(Tok.getLocation(), diag::err_expected_template_parameter);

vsapsai wrote:
> How does it work when you have `typedef` for the first template parameter?
It works all right but I am puzzled by your question now :-)


```
/Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp:3:11:
 error: expected template parameter
template  struct Foo {
  ^
/Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp:3:11:
 note: Did you mean to use 'typename'?
template  struct Foo {
  ^~~
  typename
fix-it:"/Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp":{3:11-3:18}:"typename"
/Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp:4:3:
 error: unknown type name 'a'
  a
  ^

```

I am probably not following you here. Do you have any specific reason on your 
mind? Anything I should think about or check in the source code?



Comment at: Parser/typedef-instead-of-typename-typo.hpp:3
+
+template  struct Foo {
+  a

vsapsai wrote:
> Maybe put this test in clang/test/FixIt ?
> 
> Also please check what file extensions are used for testing templates. .hpp 
> reflects real-life usage but  most tests are .cpp. Or maybe I wasn't paying 
> attention.
Oh, I completely missed that directory! Thanks.

It seems like there are some header files with ".h" extension but these are 
usually somehow special (empty file or something) so I figure you are right and 
the extension should be ".cpp".



Comment at: Parser/typedef-instead-of-typename-typo.hpp:5
+  a
+}; // CHECK: expected-error{{expected template parameter}} \
+// CHECK: expected-note{{Did you mean to use 'typename'?}} \

vsapsai wrote:
> It is a little bit confusing to what lines the messages would be attributed 
> to. Need to check locally because not sure I interpret all those backslashes 
> the same way lit does.
> 
> Also idea for the test. To check that the fix-it was applied properly you can 
> add a member like `B b;` and it shouldn't trigger any errors.
I am totally open to suggestions how to write better tests using FileCheck. As 
far as I understand it I have to keep the expected-* macro on the same line as 
the code. Or is there any better way?

Do I understand it right that you suggest to create another test in which to 
try applying fixit and check that compilation was successful? Do you mean to 
create compile_commands.json temporarily and use clang-check -fixit?





Comment at: clang/Basic/DiagnosticParseKinds.td:1167
+def note_meant_to_use_typename : Note<
+  "Did you mean to use 'typename'?">;
 }

vsapsai wrote:
> Looks like other diagnostic messages "did you mean to use …" have lowercase 
> "d" in "did". Though I haven't checked how it looks in various situations.
You are right. Thanks.


https://reviews.llvm.org/D42170



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


[PATCH] D42170: Fixit for 'typedef' instead of 'typename' typo

2018-01-23 Thread Jan Korous via Phabricator via cfe-commits
jkorous-apple updated this revision to Diff 131041.
jkorous-apple added a comment.

Changes based on Volodymyr's comments.


https://reviews.llvm.org/D42170

Files:
  FixIt/fixit-typedef-instead-of-typename-typo.cpp
  Parse/ParseTemplate.cpp
  clang/Basic/DiagnosticParseKinds.td


Index: FixIt/fixit-typedef-instead-of-typename-typo.cpp
===
--- /dev/null
+++ FixIt/fixit-typedef-instead-of-typename-typo.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -verify %s
+
+template  struct Foo {
+  a
+}; // CHECK: expected-error{{expected template parameter}} \
+// CHECK: expected-note{{did you mean to use 'typename'?}} \
+// CHECK: fix-it:{{.*}}:{4:23-4:30}:"typename" \
+// Check that we are speculatively (with fixit applied) trying to parse the 
rest. \
+// CHECK: expected-error{{unknown type name 'a'}} \
+// CHECK: expected-error{{expected member name or ';' after declaration 
specifiers}}
Index: Parse/ParseTemplate.cpp
===
--- Parse/ParseTemplate.cpp
+++ Parse/ParseTemplate.cpp
@@ -488,6 +488,20 @@
   if (Tok.is(tok::kw_template))
 return ParseTemplateTemplateParameter(Depth, Position);
 
+  // Is there just a typo in the input code? ('typedef' instead of 'typename')
+  if (Tok.is(tok::kw_typedef)) {
+Diag(Tok.getLocation(), diag::err_expected_template_parameter);
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+<< FixItHint::CreateReplacement(CharSourceRange::getCharRange(
+Tok.getLocation(), 
Tok.getEndLoc()),
+"typename");
+
+Tok.setKind(tok::kw_typename);
+
+return ParseTypeParameter(Depth, Position);
+  }
+
   // If it's none of the above, then it must be a parameter declaration.
   // NOTE: This will pick up errors in the closure of the template parameter
   // list (e.g., template < ; Check here to implement >> style closures.
Index: clang/Basic/DiagnosticParseKinds.td
===
--- clang/Basic/DiagnosticParseKinds.td
+++ clang/Basic/DiagnosticParseKinds.td
@@ -1162,6 +1162,9 @@
 
 def err_objc_type_args_after_protocols : Error<
   "protocol qualifiers must precede type arguments">;
+
+def note_meant_to_use_typename : Note<
+  "did you mean to use 'typename'?">;
 }
 
 let CategoryName = "Coroutines Issue" in {


Index: FixIt/fixit-typedef-instead-of-typename-typo.cpp
===
--- /dev/null
+++ FixIt/fixit-typedef-instead-of-typename-typo.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -verify %s
+
+template  struct Foo {
+  a
+}; // CHECK: expected-error{{expected template parameter}} \
+// CHECK: expected-note{{did you mean to use 'typename'?}} \
+// CHECK: fix-it:{{.*}}:{4:23-4:30}:"typename" \
+// Check that we are speculatively (with fixit applied) trying to parse the rest. \
+// CHECK: expected-error{{unknown type name 'a'}} \
+// CHECK: expected-error{{expected member name or ';' after declaration specifiers}}
Index: Parse/ParseTemplate.cpp
===
--- Parse/ParseTemplate.cpp
+++ Parse/ParseTemplate.cpp
@@ -488,6 +488,20 @@
   if (Tok.is(tok::kw_template))
 return ParseTemplateTemplateParameter(Depth, Position);
 
+  // Is there just a typo in the input code? ('typedef' instead of 'typename')
+  if (Tok.is(tok::kw_typedef)) {
+Diag(Tok.getLocation(), diag::err_expected_template_parameter);
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+<< FixItHint::CreateReplacement(CharSourceRange::getCharRange(
+Tok.getLocation(), Tok.getEndLoc()),
+"typename");
+
+Tok.setKind(tok::kw_typename);
+
+return ParseTypeParameter(Depth, Position);
+  }
+
   // If it's none of the above, then it must be a parameter declaration.
   // NOTE: This will pick up errors in the closure of the template parameter
   // list (e.g., template < ; Check here to implement >> style closures.
Index: clang/Basic/DiagnosticParseKinds.td
===
--- clang/Basic/DiagnosticParseKinds.td
+++ clang/Basic/DiagnosticParseKinds.td
@@ -1162,6 +1162,9 @@
 
 def err_objc_type_args_after_protocols : Error<
   "protocol qualifiers must precede type arguments">;
+
+def note_meant_to_use_typename : Note<
+  "did you mean to use 'typename'?">;
 }
 
 let CategoryName = "Coroutines Issue" in {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323194 - [Solaris] Make RHEL devtoolsets handling Linux-specific

2018-01-23 Thread Fedor Sergeev via cfe-commits
Author: fedor.sergeev
Date: Tue Jan 23 04:24:01 2018
New Revision: 323194

URL: http://llvm.org/viewvc/llvm-project?rev=323194&view=rev
Log:
[Solaris] Make RHEL devtoolsets handling Linux-specific

Summary:
This patch is meant to address the last outstanding review comment on the 
already approved
(but not yet commited) https://reviews.llvm.org/D35755, namely making the 
handling of the RHEL
devtoolsets Linux-specific.

Don't know if it's best integrated into the former or applied subsequently.

Tested on i386-pc-solaris2.11 and x86_64-pc-linux-gnu.

Reviewers: fedor.sergeev, tstellar, jyknight

Reviewed By: fedor.sergeev

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Gnu.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Gnu.cpp?rev=323194&r1=323193&r2=323194&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp Tue Jan 23 04:24:01 2018
@@ -1788,17 +1788,14 @@ void Generic_GCC::GCCInstallationDetecto
   }
 
   // Non-Solaris is much simpler - most systems just go with "/usr".
-  if (SysRoot.empty()) {
-// Yet, still look for RHEL devtoolsets
-// (should it be done Linux-only??)
+  if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
+// Yet, still look for RHEL devtoolsets.
 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
-Prefixes.push_back("/usr");
-  } else {
-Prefixes.push_back(SysRoot.str() + "/usr");
   }
+  Prefixes.push_back(SysRoot.str() + "/usr");
 }
 
 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(


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


r323193 - [Solaris] gcc toolchain handling revamp

2018-01-23 Thread Fedor Sergeev via cfe-commits
Author: fedor.sergeev
Date: Tue Jan 23 04:23:52 2018
New Revision: 323193

URL: http://llvm.org/viewvc/llvm-project?rev=323193&view=rev
Log:
[Solaris] gcc toolchain handling revamp

Summary:
General idea is to utilize generic (mostly Generic_GCC) code
and get rid of Solaris-specific handling as much as possible.

In particular:
- scanLibDirForGCCTripleSolaris was removed, relying on generic
  CollectLibDirsAndTriples

- findBiarchMultilibs is now properly utilized to switch between
   m32 and m64 include & lib paths on Solaris

- C system include handling copied from Linux (bar multilib hacks)

Fixes PR24606.

Reviewers: dlj, rafael, jyknight, theraven, tstellar

Reviewed By: jyknight

Subscribers: aaron.ballman, mgorny, krytarowski, ro, joerg, cfe-commits

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

Added:
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/sparc-sun-solaris2.11/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/sparc-sun-solaris2.11/bits/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/sparc-sun-solaris2.11/bits/gthr.h
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crt1.o

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/typeinfo
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtbegin.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crt1.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crt1.o

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtbegin.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtbegin.o

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtend.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtend.o

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/crt1.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crt1.o

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/crtbegin.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtbegin.o

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/crtend.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtend.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/libatomic.a
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/crti.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/sparcv9/

cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/sparcv9/libatomic.a
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/crtn.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/crti.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/crti.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/crtn.o
  - copied, changed from r323188, 
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/crtn.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/ld.so.1
  - copied, changed from r323

[PATCH] D42029: [Solaris] Make RHEL devtoolsets handling Linux-specific

2018-01-23 Thread Fedor Sergeev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323194: [Solaris] Make RHEL devtoolsets handling 
Linux-specific (authored by fedor.sergeev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42029?vs=129762&id=131044#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42029

Files:
  cfe/trunk/lib/Driver/ToolChains/Gnu.cpp


Index: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
@@ -1788,17 +1788,14 @@
   }
 
   // Non-Solaris is much simpler - most systems just go with "/usr".
-  if (SysRoot.empty()) {
-// Yet, still look for RHEL devtoolsets
-// (should it be done Linux-only??)
+  if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
+// Yet, still look for RHEL devtoolsets.
 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
-Prefixes.push_back("/usr");
-  } else {
-Prefixes.push_back(SysRoot.str() + "/usr");
   }
+  Prefixes.push_back(SysRoot.str() + "/usr");
 }
 
 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(


Index: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
@@ -1788,17 +1788,14 @@
   }
 
   // Non-Solaris is much simpler - most systems just go with "/usr".
-  if (SysRoot.empty()) {
-// Yet, still look for RHEL devtoolsets
-// (should it be done Linux-only??)
+  if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
+// Yet, still look for RHEL devtoolsets.
 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
-Prefixes.push_back("/usr");
-  } else {
-Prefixes.push_back(SysRoot.str() + "/usr");
   }
+  Prefixes.push_back(SysRoot.str() + "/usr");
 }
 
 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35755: [Solaris] gcc toolchain handling revamp

2018-01-23 Thread Fedor Sergeev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323193: [Solaris] gcc toolchain handling revamp (authored by 
fedor.sergeev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D35755?vs=110194&id=131043#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35755

Files:
  cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
  cfe/trunk/lib/Driver/ToolChains/Gnu.h
  cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
  cfe/trunk/lib/Driver/ToolChains/Solaris.h
  cfe/trunk/lib/Frontend/InitHeaderSearch.cpp
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/sparc-sun-solaris2.11/bits/gthr.h
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/include/c++/4.8.2/typeinfo
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crt1.o
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtbegin.o
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtend.o
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/crt1.o
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/crtbegin.o
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/sparcv9/crtend.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/libatomic.a
  
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/gcc/4.8/lib/sparcv9/libatomic.a
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/crti.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/crtn.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/ld.so.1
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/sparcv9/crti.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/sparcv9/crtn.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/sparcv9/ld.so.1
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/include/c++/4.9.4/i386-pc-solaris2.11/bits/gthr.h
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/include/c++/4.9.4/typeinfo
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/lib/amd64/libatomic.a
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/lib/gcc/i386-pc-solaris2.11/4.9.4/amd64/crtbegin.o
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/lib/gcc/i386-pc-solaris2.11/4.9.4/amd64/crtend.o
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/lib/gcc/i386-pc-solaris2.11/4.9.4/crtbegin.o
  
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/lib/gcc/i386-pc-solaris2.11/4.9.4/crtend.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/gcc/4.9/lib/libatomic.a
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/amd64/crt1.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/amd64/crti.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/amd64/crtn.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/amd64/ld.so.1
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/crt1.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/crti.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/crtn.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/ld.so.1
  
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crt1.o
  
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtbegin.o
  
cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/gcc/4.8/lib/gcc/sparc-sun-solaris2.11/4.8.2/crtend.o
  cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/crti.o
  cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/crtn.o
  cfe/trunk/test/Driver/Inputs/sparc-sun-solaris2.11/usr/lib/ld.so.1
  cfe/trunk/test/Driver/solaris-header-search.cpp
  cfe/trunk/test/Driver/solaris-ld.c

Index: cfe/trunk/test/Driver/solaris-header-search.cpp
===
--- cfe/trunk/test/Driver/solaris-header-search.cpp
+++ cfe/trunk/test/Driver/solaris-header-search.cpp
@@ -1,11 +1,41 @@
-// Test that the C++ headers are found.
+// Test that the C++ headers are found on Solaris with gcc toolchain detection
 //
-// RUN: %clang -no-canonical-prefixes %s -### 2>&1 \
+// Sparc, 32bit
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN: --target=sparc-sun-solaris2.11 \
-// RUN: --gcc-toolchain="" \
-// RUN: --sysroot=%S/Inputs/sparc-sun-solaris2.11 \
-// RUN:   | FileCheck %s
-// CHECK: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
-// CHECK: "-internal-isystem" "{{.*}}/usr/include/c++/v1/support/solaris"
-// CHECK: "-internal-isystem" "{{.*}}/usr/gcc/4.8/include/c++/4.8.2"
-// CHECK: "-internal-isystem" "{{.*}}/usr/gcc/4.8/include/c++/4.8.2/sparc-sun-solaris2.11"
+// RUN: --sysroot=%S/Inputs/solaris_sparc_tr

[PATCH] D41947: Provide default virtual filesystem argument to ClangTool constructor

2018-01-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323195: [Tooling] Added a VFS parameter to ClangTool 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41947?vs=130573&id=131045#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41947

Files:
  include/clang/Tooling/Tooling.h
  lib/Tooling/Tooling.cpp
  unittests/Tooling/ToolingTest.cpp


Index: include/clang/Tooling/Tooling.h
===
--- include/clang/Tooling/Tooling.h
+++ include/clang/Tooling/Tooling.h
@@ -296,10 +296,14 @@
   ///not found in Compilations, it is skipped.
   /// \param PCHContainerOps The PCHContainerOperations for loading and 
creating
   /// clang modules.
+  /// \param BaseFS VFS used for all underlying file accesses when running the
+  /// tool.
   ClangTool(const CompilationDatabase &Compilations,
 ArrayRef SourcePaths,
 std::shared_ptr PCHContainerOps =
-std::make_shared());
+std::make_shared(),
+IntrusiveRefCntPtr BaseFS =
+vfs::getRealFileSystem());
 
   ~ClangTool();
 
Index: lib/Tooling/Tooling.cpp
===
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -328,10 +328,11 @@
 
 ClangTool::ClangTool(const CompilationDatabase &Compilations,
  ArrayRef SourcePaths,
- std::shared_ptr PCHContainerOps)
+ std::shared_ptr PCHContainerOps,
+ IntrusiveRefCntPtr BaseFS)
 : Compilations(Compilations), SourcePaths(SourcePaths),
   PCHContainerOps(std::move(PCHContainerOps)),
-  OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
+  OverlayFileSystem(new vfs::OverlayFileSystem(BaseFS)),
   InMemoryFileSystem(new vfs::InMemoryFileSystem),
   Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
   DiagConsumer(nullptr) {
Index: unittests/Tooling/ToolingTest.cpp
===
--- unittests/Tooling/ToolingTest.cpp
+++ unittests/Tooling/ToolingTest.cpp
@@ -402,6 +402,24 @@
   EXPECT_FALSE(Found);
 }
 
+TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
+  FixedCompilationDatabase Compilations("/", std::vector());
+  llvm::IntrusiveRefCntPtr OverlayFileSystem(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::IntrusiveRefCntPtr InMemoryFileSystem(
+  new vfs::InMemoryFileSystem);
+  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
+
+  InMemoryFileSystem->addFile(
+  "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));
+
+  ClangTool Tool(Compilations, std::vector(1, "a.cpp"),
+ std::make_shared(), 
OverlayFileSystem);
+  std::unique_ptr Action(
+  newFrontendActionFactory());
+  EXPECT_EQ(0, Tool.run(Action.get()));
+}
+
 // Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
 TEST(ClangToolTest, StripDependencyFileAdjuster) {
   FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});


Index: include/clang/Tooling/Tooling.h
===
--- include/clang/Tooling/Tooling.h
+++ include/clang/Tooling/Tooling.h
@@ -296,10 +296,14 @@
   ///not found in Compilations, it is skipped.
   /// \param PCHContainerOps The PCHContainerOperations for loading and creating
   /// clang modules.
+  /// \param BaseFS VFS used for all underlying file accesses when running the
+  /// tool.
   ClangTool(const CompilationDatabase &Compilations,
 ArrayRef SourcePaths,
 std::shared_ptr PCHContainerOps =
-std::make_shared());
+std::make_shared(),
+IntrusiveRefCntPtr BaseFS =
+vfs::getRealFileSystem());
 
   ~ClangTool();
 
Index: lib/Tooling/Tooling.cpp
===
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -328,10 +328,11 @@
 
 ClangTool::ClangTool(const CompilationDatabase &Compilations,
  ArrayRef SourcePaths,
- std::shared_ptr PCHContainerOps)
+ std::shared_ptr PCHContainerOps,
+ IntrusiveRefCntPtr BaseFS)
 : Compilations(Compilations), SourcePaths(SourcePaths),
   PCHContainerOps(std::move(PCHContainerOps)),
-  OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
+  OverlayFileSystem(new vfs::OverlayFileSystem(BaseFS)),
   InMemoryFileSystem(new vfs::InMemoryFileSystem),
   Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
   DiagConsumer(nullptr) {
Index: unittests/Tooling/ToolingTest.cpp
===
--- unittests/Tooling/ToolingTest.cpp
+++ unittests/Tooli

r323195 - [Tooling] Added a VFS parameter to ClangTool

2018-01-23 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Jan 23 04:30:02 2018
New Revision: 323195

URL: http://llvm.org/viewvc/llvm-project?rev=323195&view=rev
Log:
[Tooling] Added a VFS parameter to ClangTool

Summary:
The parameter overrides the underlying vfs used by ClangTool for
filesystem operations.

Patch by Vladimir Plyashkun.

Reviewers: alexfh, ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/include/clang/Tooling/Tooling.h
cfe/trunk/lib/Tooling/Tooling.cpp
cfe/trunk/unittests/Tooling/ToolingTest.cpp

Modified: cfe/trunk/include/clang/Tooling/Tooling.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Tooling.h?rev=323195&r1=323194&r2=323195&view=diff
==
--- cfe/trunk/include/clang/Tooling/Tooling.h (original)
+++ cfe/trunk/include/clang/Tooling/Tooling.h Tue Jan 23 04:30:02 2018
@@ -296,10 +296,14 @@ class ClangTool {
   ///not found in Compilations, it is skipped.
   /// \param PCHContainerOps The PCHContainerOperations for loading and 
creating
   /// clang modules.
+  /// \param BaseFS VFS used for all underlying file accesses when running the
+  /// tool.
   ClangTool(const CompilationDatabase &Compilations,
 ArrayRef SourcePaths,
 std::shared_ptr PCHContainerOps =
-std::make_shared());
+std::make_shared(),
+IntrusiveRefCntPtr BaseFS =
+vfs::getRealFileSystem());
 
   ~ClangTool();
 

Modified: cfe/trunk/lib/Tooling/Tooling.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Tooling.cpp?rev=323195&r1=323194&r2=323195&view=diff
==
--- cfe/trunk/lib/Tooling/Tooling.cpp (original)
+++ cfe/trunk/lib/Tooling/Tooling.cpp Tue Jan 23 04:30:02 2018
@@ -328,10 +328,11 @@ bool FrontendActionFactory::runInvocatio
 
 ClangTool::ClangTool(const CompilationDatabase &Compilations,
  ArrayRef SourcePaths,
- std::shared_ptr PCHContainerOps)
+ std::shared_ptr PCHContainerOps,
+ IntrusiveRefCntPtr BaseFS)
 : Compilations(Compilations), SourcePaths(SourcePaths),
   PCHContainerOps(std::move(PCHContainerOps)),
-  OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
+  OverlayFileSystem(new vfs::OverlayFileSystem(BaseFS)),
   InMemoryFileSystem(new vfs::InMemoryFileSystem),
   Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
   DiagConsumer(nullptr) {

Modified: cfe/trunk/unittests/Tooling/ToolingTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/ToolingTest.cpp?rev=323195&r1=323194&r2=323195&view=diff
==
--- cfe/trunk/unittests/Tooling/ToolingTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/ToolingTest.cpp Tue Jan 23 04:30:02 2018
@@ -402,6 +402,24 @@ TEST(ClangToolTest, ArgumentAdjusters) {
   EXPECT_FALSE(Found);
 }
 
+TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
+  FixedCompilationDatabase Compilations("/", std::vector());
+  llvm::IntrusiveRefCntPtr OverlayFileSystem(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::IntrusiveRefCntPtr InMemoryFileSystem(
+  new vfs::InMemoryFileSystem);
+  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
+
+  InMemoryFileSystem->addFile(
+  "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));
+
+  ClangTool Tool(Compilations, std::vector(1, "a.cpp"),
+ std::make_shared(), 
OverlayFileSystem);
+  std::unique_ptr Action(
+  newFrontendActionFactory());
+  EXPECT_EQ(0, Tool.run(Action.get()));
+}
+
 // Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
 TEST(ClangToolTest, StripDependencyFileAdjuster) {
   FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});


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


[clang-tools-extra] r323196 - [clang-tidy] Add -vfsoverlay flag

2018-01-23 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Jan 23 04:31:06 2018
New Revision: 323196

URL: http://llvm.org/viewvc/llvm-project?rev=323196&view=rev
Log:
[clang-tidy] Add -vfsoverlay flag

Summary:
It allows to remap and override files and directories on disk when
running clang-tidy. The intended use case for the flag is running
standalone clang-tidy binary for IDE and editor integration.

Patch by Vladimir Plyashkun.

Reviewers: alexfh, benlangmuir, ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: ilya-biryukov, cfe-commits

Tags: #clang-tools-extra

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

Added:
clang-tools-extra/trunk/test/clang-tidy/Inputs/vfsoverlay/
clang-tools-extra/trunk/test/clang-tidy/Inputs/vfsoverlay/actual_header.h
clang-tools-extra/trunk/test/clang-tidy/Inputs/vfsoverlay/vfsoverlay.yaml
clang-tools-extra/trunk/test/clang-tidy/vfsoverlay.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp
clang-tools-extra/trunk/clang-tidy/ClangTidy.h
clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp?rev=323196&r1=323195&r2=323196&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp Tue Jan 23 04:31:06 2018
@@ -89,8 +89,9 @@ private:
 
 class ErrorReporter {
 public:
-  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes)
-  : Files(FileSystemOptions()), DiagOpts(new DiagnosticOptions()),
+  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes,
+llvm::IntrusiveRefCntPtr BaseFS)
+  : Files(FileSystemOptions(), BaseFS), DiagOpts(new DiagnosticOptions()),
 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)),
 Diags(IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts,
   DiagPrinter),
@@ -474,8 +475,11 @@ ClangTidyOptions::OptionMap getCheckOpti
 
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const CompilationDatabase &Compilations,
-  ArrayRef InputFiles, ProfileData *Profile) {
-  ClangTool Tool(Compilations, InputFiles);
+  ArrayRef InputFiles,
+  llvm::IntrusiveRefCntPtr BaseFS,
+  ProfileData *Profile) {
+  ClangTool Tool(Compilations, InputFiles,
+ std::make_shared(), BaseFS);
 
   // Add extra arguments passed by the clang-tidy command-line.
   ArgumentsAdjuster PerFileExtraArgumentsInserter =
@@ -546,8 +550,9 @@ void runClangTidy(clang::tidy::ClangTidy
 }
 
 void handleErrors(ClangTidyContext &Context, bool Fix,
-  unsigned &WarningsAsErrorsCount) {
-  ErrorReporter Reporter(Context, Fix);
+  unsigned &WarningsAsErrorsCount,
+  llvm::IntrusiveRefCntPtr BaseFS) {
+  ErrorReporter Reporter(Context, Fix, BaseFS);
   vfs::FileSystem &FileSystem =
   *Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
   auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidy.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidy.h?rev=323196&r1=323195&r2=323196&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidy.h (original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidy.h Tue Jan 23 04:31:06 2018
@@ -227,6 +227,7 @@ ClangTidyOptions::OptionMap getCheckOpti
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const tooling::CompilationDatabase &Compilations,
   ArrayRef InputFiles,
+  llvm::IntrusiveRefCntPtr BaseFS,
   ProfileData *Profile = nullptr);
 
 // FIXME: This interface will need to be significantly extended to be useful.
@@ -236,7 +237,8 @@ void runClangTidy(clang::tidy::ClangTidy
 /// Errors containing fixes are automatically applied and reformatted. If no
 /// clang-format configuration file is found, the given \P FormatStyle is used.
 void handleErrors(ClangTidyContext &Context, bool Fix,
-  unsigned &WarningsAsErrorsCount);
+  unsigned &WarningsAsErrorsCount,
+  llvm::IntrusiveRefCntPtr BaseFS);
 
 /// \brief Serializes replacements into YAML and writes them to the specified
 /// output stream.

Modified: clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp?rev=323196&r1=323195&r2=323196&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp

[PATCH] D41535: Add -vfsoverlay option for Clang-Tidy

2018-01-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323196: [clang-tidy] Add -vfsoverlay flag (authored by 
ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41535?vs=130891&id=131046#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41535

Files:
  clang-tidy/ClangTidy.cpp
  clang-tidy/ClangTidy.h
  clang-tidy/tool/ClangTidyMain.cpp
  test/clang-tidy/Inputs/vfsoverlay/actual_header.h
  test/clang-tidy/Inputs/vfsoverlay/vfsoverlay.yaml
  test/clang-tidy/vfsoverlay.cpp

Index: clang-tidy/ClangTidy.h
===
--- clang-tidy/ClangTidy.h
+++ clang-tidy/ClangTidy.h
@@ -227,6 +227,7 @@
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const tooling::CompilationDatabase &Compilations,
   ArrayRef InputFiles,
+  llvm::IntrusiveRefCntPtr BaseFS,
   ProfileData *Profile = nullptr);
 
 // FIXME: This interface will need to be significantly extended to be useful.
@@ -236,7 +237,8 @@
 /// Errors containing fixes are automatically applied and reformatted. If no
 /// clang-format configuration file is found, the given \P FormatStyle is used.
 void handleErrors(ClangTidyContext &Context, bool Fix,
-  unsigned &WarningsAsErrorsCount);
+  unsigned &WarningsAsErrorsCount,
+  llvm::IntrusiveRefCntPtr BaseFS);
 
 /// \brief Serializes replacements into YAML and writes them to the specified
 /// output stream.
Index: clang-tidy/ClangTidy.cpp
===
--- clang-tidy/ClangTidy.cpp
+++ clang-tidy/ClangTidy.cpp
@@ -89,8 +89,9 @@
 
 class ErrorReporter {
 public:
-  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes)
-  : Files(FileSystemOptions()), DiagOpts(new DiagnosticOptions()),
+  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes,
+llvm::IntrusiveRefCntPtr BaseFS)
+  : Files(FileSystemOptions(), BaseFS), DiagOpts(new DiagnosticOptions()),
 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)),
 Diags(IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts,
   DiagPrinter),
@@ -474,8 +475,11 @@
 
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const CompilationDatabase &Compilations,
-  ArrayRef InputFiles, ProfileData *Profile) {
-  ClangTool Tool(Compilations, InputFiles);
+  ArrayRef InputFiles,
+  llvm::IntrusiveRefCntPtr BaseFS,
+  ProfileData *Profile) {
+  ClangTool Tool(Compilations, InputFiles,
+ std::make_shared(), BaseFS);
 
   // Add extra arguments passed by the clang-tidy command-line.
   ArgumentsAdjuster PerFileExtraArgumentsInserter =
@@ -546,8 +550,9 @@
 }
 
 void handleErrors(ClangTidyContext &Context, bool Fix,
-  unsigned &WarningsAsErrorsCount) {
-  ErrorReporter Reporter(Context, Fix);
+  unsigned &WarningsAsErrorsCount,
+  llvm::IntrusiveRefCntPtr BaseFS) {
+  ErrorReporter Reporter(Context, Fix, BaseFS);
   vfs::FileSystem &FileSystem =
   *Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
   auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
Index: clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tidy/tool/ClangTidyMain.cpp
@@ -209,6 +209,13 @@
cl::init(false),
cl::cat(ClangTidyCategory));
 
+static cl::opt VfsOverlay("vfsoverlay", cl::desc(R"(
+Overlay the virtual filesystem described by file
+over the real file system.
+)"),
+   cl::value_desc("filename"),
+   cl::cat(ClangTidyCategory));
+
 namespace clang {
 namespace tidy {
 
@@ -330,6 +337,30 @@
 OverrideOptions);
 }
 
+llvm::IntrusiveRefCntPtr
+getVfsOverlayFromFile(const std::string &OverlayFile) {
+  llvm::IntrusiveRefCntPtr OverlayFS(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::ErrorOr> Buffer =
+  OverlayFS->getBufferForFile(OverlayFile);
+  if (!Buffer) {
+llvm::errs() << "Can't load virtual filesystem overlay file '"
+ << OverlayFile << "': " << Buffer.getError().message()
+ << ".\n";
+return nullptr;
+  }
+
+  IntrusiveRefCntPtr FS = vfs::getVFSFromYAML(
+  std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
+  if (!FS) {
+llvm::errs() << "Error: invalid virtual filesystem overlay file '"
+ << OverlayFile << "'.\n";
+return nullptr;
+  }
+  OverlayFS->pushOverlay(FS);
+  return OverlayFS;
+}
+
 static int clangTidyMain(int argc, const char **argv) {
   CommonOptionsPar

[PATCH] D42416: [Driver] Add support for mips32 and scudo

2018-01-23 Thread Simon Dardis via Phabricator via cfe-commits
sdardis created this revision.
sdardis added reviewers: cryptoad, atanasyan.
Herald added a subscriber: arichardson.

r317337 missed that scudo is supported on MIPS32, so permit that option for
MIPS32.


Repository:
  rC Clang

https://reviews.llvm.org/D42416

Files:
  lib/Driver/ToolChains/Linux.cpp
  test/Driver/fsanitize.c


Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -628,6 +628,10 @@
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target i386-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mips64-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mips64el-unknown-linux-gnu -fsanitize=scudo %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mips-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mipsel-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-SCUDO
 // CHECK-SCUDO: "-fsanitize=scudo"
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO-PIE
Index: lib/Driver/ToolChains/Linux.cpp
===
--- lib/Driver/ToolChains/Linux.cpp
+++ lib/Driver/ToolChains/Linux.cpp
@@ -846,6 +846,8 @@
 SanitizerMask Linux::getSupportedSanitizers() const {
   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
+  const bool IsMIPS = getTriple().getArch() == llvm::Triple::mips ||
+getTriple().getArch() == llvm::Triple::mipsel;
   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
 getTriple().getArch() == llvm::Triple::mips64el;
   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
@@ -875,7 +877,7 @@
 Res |= SanitizerKind::Efficiency;
   if (IsX86 || IsX86_64)
 Res |= SanitizerKind::Function;
-  if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch)
+  if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch)
 Res |= SanitizerKind::Scudo;
   if (IsAArch64)
 Res |= SanitizerKind::HWAddress;


Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -628,6 +628,10 @@
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target i386-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mips64-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mips64el-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mips-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
+// RUN: %clang -target mipsel-unknown-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // CHECK-SCUDO: "-fsanitize=scudo"
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO-PIE
Index: lib/Driver/ToolChains/Linux.cpp
===
--- lib/Driver/ToolChains/Linux.cpp
+++ lib/Driver/ToolChains/Linux.cpp
@@ -846,6 +846,8 @@
 SanitizerMask Linux::getSupportedSanitizers() const {
   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
+  const bool IsMIPS = getTriple().getArch() == llvm::Triple::mips ||
+getTriple().getArch() == llvm::Triple::mipsel;
   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
 getTriple().getArch() == llvm::Triple::mips64el;
   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
@@ -875,7 +877,7 @@
 Res |= SanitizerKind::Efficiency;
   if (IsX86 || IsX86_64)
 Res |= SanitizerKind::Function;
-  if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch)
+  if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch)
 Res |= SanitizerKind::Scudo;
   if (IsAArch64)
 Res |= SanitizerKind::HWAddress;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin

[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-01-23 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 131051.
simark added a comment.
Herald added subscribers: ioeric, jkorous-apple.

I just got familiar with the patch, I cleaned up the bits that I thought were
unnecessary for this change.  For example, we don't need a toJSON function for
DidChangeConfigurationParams, or explicit constructors to
DidChangeConfigurationParams, etc.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D39571

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/DraftStore.cpp
  clangd/DraftStore.h
  clangd/GlobalCompilationDatabase.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h
  test/clangd/initialize-params-invalid.test
  test/clangd/initialize-params.test

Index: test/clangd/initialize-params.test
===
--- test/clangd/initialize-params.test
+++ test/clangd/initialize-params.test
@@ -18,9 +18,10 @@
 # CHECK-NEXT:  ":"
 # CHECK-NEXT:]
 # CHECK-NEXT:  },
+# CHECK-NEXT:  "configurationChangeProvider": true,
 # CHECK-NEXT:  "definitionProvider": true,
 # CHECK-NEXT:  "documentFormattingProvider": true,
-# CHECK-NEXT:  "documentHighlightProvider": true,
+# CHECK-NEXT:	   "documentHighlightProvider": true,
 # CHECK-NEXT:  "documentOnTypeFormattingProvider": {
 # CHECK-NEXT:"firstTriggerCharacter": "}",
 # CHECK-NEXT:"moreTriggerCharacter": []
@@ -49,4 +50,4 @@
 # CHECK-NEXT:  "result": null
 Content-Length: 33
 
-{"jsonrpc":"2.0":"method":"exit"}
+{"jsonrpc":"2.0":"method":"exit"}
\ No newline at end of file
Index: test/clangd/initialize-params-invalid.test
===
--- test/clangd/initialize-params-invalid.test
+++ test/clangd/initialize-params-invalid.test
@@ -18,9 +18,10 @@
 # CHECK-NEXT:  ":"
 # CHECK-NEXT:]
 # CHECK-NEXT:  },
+# CHECK-NEXT:  "configurationChangeProvider": true,
 # CHECK-NEXT:  "definitionProvider": true,
 # CHECK-NEXT:  "documentFormattingProvider": true,
-# CHECK-NEXT:  "documentHighlightProvider": true,
+# CHECK-NEXT:	   "documentHighlightProvider": true,
 # CHECK-NEXT:  "documentOnTypeFormattingProvider": {
 # CHECK-NEXT:"firstTriggerCharacter": "}",
 # CHECK-NEXT:"moreTriggerCharacter": []
Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -57,6 +57,8 @@
   virtual void onRename(Ctx C, RenameParams &Parames) = 0;
   virtual void onDocumentHighlight(Ctx C,
TextDocumentPositionParams &Params) = 0;
+  virtual void onChangeConfiguration(Ctx C,
+ DidChangeConfigurationParams &Params) = 0;
 };
 
 void registerCallbackHandlers(JSONRPCDispatcher &Dispatcher, JSONOutput &Out,
Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -73,4 +73,6 @@
   Register("workspace/executeCommand", &ProtocolCallbacks::onCommand);
   Register("textDocument/documentHighlight",
&ProtocolCallbacks::onDocumentHighlight);
+  Register("workspace/didChangeConfiguration",
+   &ProtocolCallbacks::onChangeConfiguration);
 }
Index: clangd/Protocol.h
===
--- clangd/Protocol.h
+++ clangd/Protocol.h
@@ -264,6 +264,20 @@
 };
 bool fromJSON(const json::Expr &, DidChangeWatchedFilesParams &);
 
+/// Clangd extension to manage a workspace/didChangeConfiguration notification
+/// since the data received is described as 'any' type in LSP.
+struct ClangdConfigurationParamsChange {
+  llvm::Optional compilationDatabasePath;
+};
+bool fromJSON(const json::Expr &, ClangdConfigurationParamsChange &);
+
+struct DidChangeConfigurationParams {
+  // We use this predefined struct because it is easier to use
+  // than the protocol specified type of 'any'.
+  ClangdConfigurationParamsChange settings;
+};
+bool fromJSON(const json::Expr &, DidChangeConfigurationParams &);
+
 struct FormattingOptions {
   /// Size of a tab in spaces.
   int tabSize;
Index: clangd/Protocol.cpp
===
--- clangd/Protocol.cpp
+++ clangd/Protocol.cpp
@@ -381,5 +381,16 @@
   };
 }
 
+bool fromJSON(const json::Expr &Params, DidChangeConfigurationParams &CCP) {
+  json::ObjectMapper O(Params);
+  return O && O.map("settings", CCP.settings);
+}
+
+
+bool fromJSON(const json::Expr &Params, ClangdConfigurationParamsChange &CCPC) {
+  json::ObjectMapper O(Params);
+  return O && O.map("compilationDatabasePath", CCPC.compilationDatabasePath);
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/GlobalCompilationDatabase.h

[PATCH] D42416: [Driver] Add support for mips32 and scudo

2018-01-23 Thread Simon Atanasyan via Phabricator via cfe-commits
atanasyan accepted this revision.
atanasyan added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rC Clang

https://reviews.llvm.org/D42416



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


r323199 - Fix Driver/solaris-ld.c test on Windows

2018-01-23 Thread Fedor Sergeev via cfe-commits
Author: fedor.sergeev
Date: Tue Jan 23 05:59:11 2018
New Revision: 323199

URL: http://llvm.org/viewvc/llvm-project?rev=323199&view=rev
Log:
Fix Driver/solaris-ld.c test on Windows

Fixing failure introduced with r323193.

Modified:
cfe/trunk/test/Driver/solaris-ld.c

Modified: cfe/trunk/test/Driver/solaris-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/solaris-ld.c?rev=323199&r1=323198&r2=323199&view=diff
==
--- cfe/trunk/test/Driver/solaris-ld.c (original)
+++ cfe/trunk/test/Driver/solaris-ld.c Tue Jan 23 05:59:11 2018
@@ -4,6 +4,7 @@
 // Check sparc-sun-solaris2.11, 32bit
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-SPARC32 %s
 // CHECK-LD-SPARC32-NOT: warning:
@@ -27,6 +28,7 @@
 // Check sparc-sun-solaris2.11, 64bit
 // RUN: %clang -no-canonical-prefixes -m64 %s -### -o %t.o 2>&1 \
 // RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-SPARC64 %s
 // CHECK-LD-SPARC64-NOT: warning:
@@ -50,6 +52,7 @@
 // Check i386-pc-solaris2.11, 32bit
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: --target=i386-pc-solaris2.11 \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/solaris_x86_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-X32 %s
 // CHECK-LD-X32-NOT: warning:
@@ -73,6 +76,7 @@
 // Check i386-pc-solaris2.11, 64bit
 // RUN: %clang -no-canonical-prefixes -m64 %s -### -o %t.o 2>&1 \
 // RUN: --target=i386-pc-solaris2.11 \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/solaris_x86_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-X64 %s
 // CHECK-LD-X64-NOT: warning:
@@ -96,6 +100,7 @@
 // Check the right -l flags are present with -shared
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o -shared 2>&1 \
 // RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-SPARC32-SHARED %s
 // CHECK-SPARC32-SHARED: {{.*/ld}}"


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


[PATCH] D42413: [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

2018-01-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:165
 
-  Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
-  .bind("default"))),
-  this);
+  if (getLangOpts().CPlusPlus2a)
+Finder->addMatcher(

I wonder if we could add a `nothing()` matcher (sibling to the `anything()` 
matcher) so that this could be rewritten as:

`unless(anyOf(getLangOpts().CPlusPlus2a ? nothing() : isBitField()))`

The duplication here adds complexity if we decide to change the matchers in the 
future.



Comment at: test/clang-tidy/modernize-use-default-member-init-bitfield.cpp:1
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- 
-std=c++2a
+

I'd like to see a test where C++2a is not enabled to ensure that the fix is not 
suggested in that case.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42413



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


[PATCH] D42419: [clangd] Use new URI with scheme support in place of the existing LSP URI

2018-01-23 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: sammccall.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

o Replace the existing clangd::URI with a wrapper of FileURI which also
carries a resolved file path.
o s/FileURI/URI/


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42419

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/URI.cpp
  clangd/URI.h
  clangd/XRefs.cpp
  unittests/clangd/URITests.cpp
  unittests/clangd/XRefsTests.cpp

Index: unittests/clangd/XRefsTests.cpp
===
--- unittests/clangd/XRefsTests.cpp
+++ unittests/clangd/XRefsTests.cpp
@@ -9,6 +9,7 @@
 #include "Annotations.h"
 #include "ClangdUnit.h"
 #include "Matchers.h"
+#include "TestFS.h"
 #include "XRefs.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/PCHContainerOperations.h"
@@ -38,7 +39,9 @@
 
 // FIXME: this is duplicated with FileIndexTests. Share it.
 ParsedAST build(StringRef Code) {
-  auto CI = createInvocationFromCommandLine({"clang", "-xc++", "Foo.cpp"});
+  auto TestFile = getVirtualTestFilePath("Foo.cpp");
+  auto CI =
+  createInvocationFromCommandLine({"clang", "-xc++", TestFile.c_str()});
   auto Buf = MemoryBuffer::getMemBuffer(Code);
   auto AST = ParsedAST::Build(
   Context::empty(), std::move(CI), nullptr, std::move(Buf),
Index: unittests/clangd/URITests.cpp
===
--- unittests/clangd/URITests.cpp
+++ unittests/clangd/URITests.cpp
@@ -40,11 +40,11 @@
 .str();
   }
 
-  llvm::Expected
+  llvm::Expected
   uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
 auto Pos = AbsolutePath.find(TestRoot);
 assert(Pos != llvm::StringRef::npos);
-return FileURI::create(
+return URI::create(
 Scheme, /*Authority=*/"",
 AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
   }
@@ -57,22 +57,22 @@
 
 std::string createOrDie(llvm::StringRef AbsolutePath,
 llvm::StringRef Scheme = "file") {
-  auto Uri = FileURI::create(AbsolutePath, Scheme);
+  auto Uri = URI::create(AbsolutePath, Scheme);
   if (!Uri)
 llvm_unreachable(llvm::toString(Uri.takeError()).c_str());
   return Uri->toString();
 }
 
 std::string createOrDie(llvm::StringRef Scheme, llvm::StringRef Authority,
 llvm::StringRef Body) {
-  auto Uri = FileURI::create(Scheme, Authority, Body);
+  auto Uri = URI::create(Scheme, Authority, Body);
   if (!Uri)
 llvm_unreachable(llvm::toString(Uri.takeError()).c_str());
   return Uri->toString();
 }
 
-FileURI parseOrDie(llvm::StringRef Uri) {
-  auto U = FileURI::parse(Uri);
+URI parseOrDie(llvm::StringRef Uri) {
+  auto U = URI::parse(Uri);
   if (!U)
 llvm_unreachable(llvm::toString(U.takeError()).c_str());
   return *U;
@@ -93,8 +93,8 @@
   EXPECT_EQ(parseOrDie("x:a%21b%3ac~").body(), "a!b:c~");
 }
 
-std::string resolveOrDie(const FileURI &U, llvm::StringRef HintPath = "") {
-  auto Path = FileURI::resolve(U, HintPath);
+std::string resolveOrDie(const URI &U, llvm::StringRef HintPath = "") {
+  auto Path = URI::resolve(U, HintPath);
   if (!Path)
 llvm_unreachable(llvm::toString(Path.takeError()).c_str());
   return *Path;
@@ -110,7 +110,7 @@
 }
 
 TEST(URITest, FailedCreate) {
-  auto Fail = [](llvm::Expected U) {
+  auto Fail = [](llvm::Expected U) {
 if (!U) {
   llvm::consumeError(U.takeError());
   return true;
@@ -120,15 +120,15 @@
   // Create from scheme+authority+body:
   //
   // Scheme must be provided.
-  EXPECT_TRUE(Fail(FileURI::create("", "auth", "/a")));
+  EXPECT_TRUE(Fail(URI::create("", "auth", "/a")));
   // Body must start with '/' if authority is present.
-  EXPECT_TRUE(Fail(FileURI::create("scheme", "auth", "x/y/z")));
+  EXPECT_TRUE(Fail(URI::create("scheme", "auth", "x/y/z")));
 
   // Create from scheme registry:
   //
-  EXPECT_TRUE(Fail(FileURI::create("/x/y/z", "no")));
+  EXPECT_TRUE(Fail(URI::create("/x/y/z", "no")));
   // Path has to be absolute.
-  EXPECT_TRUE(Fail(FileURI::create("x/y/z")));
+  EXPECT_TRUE(Fail(URI::create("x/y/z")));
 }
 
 TEST(URITest, Parse) {
@@ -163,7 +163,7 @@
 
 TEST(URITest, ParseFailed) {
   auto FailedParse = [](llvm::StringRef U) {
-auto URI = FileURI::parse(U);
+auto URI = URI::parse(U);
 if (!URI) {
   llvm::consumeError(URI.takeError());
   return true;
@@ -194,14 +194,14 @@
 
 TEST(URITest, Platform) {
   auto Path = getVirtualTestFilePath("x");
-  auto U = FileURI::create(Path, "file");
+  auto U = URI::create(Path, "file");
   EXPECT_TRUE(static_cast(U));
   EXPECT_THAT(resolveOrDie(*U), Path.str());
 }
 
 TEST(URITest, ResolveFailed) {
   auto FailedResolve = [](llvm::StringRef Uri) {
-auto Path = FileURI::resolve(parseOrDie(Uri));
+auto Path = URI::resolve(parseOrDie(Uri));
 if (!Path) {
   llvm::consumeError(Path.takeError());
   

[PATCH] D42419: [clangd] Use new URI with scheme support in place of the existing LSP URI

2018-01-23 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:386
+  if (!U)
+llvm_unreachable(
+"onDiagnosticsReady: Expect creating URI for file to always work.");

not sure if this is the right thing to do. idea?



Comment at: clangd/URI.h:32
+  // By default, create a simplest valid file URI.
+  URI() : Scheme("file") {}
+

same here. There are many default constructions of structures that contain URIs 
in ClangdLSPServer.cpp...


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42419



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


[PATCH] D42335: [ASTImporter] Supporting CXXOperatorCallExpr, SizeOfPackExpr, DependentTemplateSpecializationType, DependentSizedArray importing.

2018-01-23 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 131059.
xazax.hun added a comment.

- Added import for CXXTypeidExpr. What is the best way to test this?  
 header is required for using the typeid operator, but relying on the 
presence of an STL library in tests is usually considered as a bad practice. 
Should we mock a typeinfo implementation just for this purpose?


https://reviews.llvm.org/D42335

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

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -480,6 +480,16 @@
  vaArgExpr(;
 }
 
+TEST(ImportExpr, CXXTemporaryObjectExpr) {
+  MatchVerifier Verifier;
+  testImport("struct C {};"
+ "void declToImport() { C c = C(); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(has(
+ declStmt(has(varDecl(has(exprWithCleanups(has(cxxConstructExpr(
+ has(materializeTemporaryExpr(has(implicitCastExpr(
+ has(cxxTemporaryObjectExpr());
+}
 
 TEST(ImportType, ImportAtomicType) {
   MatchVerifier Verifier;
@@ -564,6 +574,50 @@
  declRefExpr());
 }
 
+const internal::VariadicDynCastAllOfMatcher
+dependentTemplateSpecializationType;
+
+TEST(ImportType, ImportDependentTemplateSpecialization) {
+  MatchVerifier Verifier;
+  testImport("template"
+ "struct A;"
+ "template"
+ "struct declToImport {"
+ "  typename A::template B a;"
+ "};",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ classTemplateDecl(has(cxxRecordDecl(has(
+ fieldDecl(hasType(dependentTemplateSpecializationType(;
+}
+
+const internal::VariadicDynCastAllOfMatcher
+sizeOfPackExpr;
+
+TEST(ImportExpr, ImportSizeOfPackExpr) {
+  MatchVerifier Verifier;
+  testImport("template "
+ "void declToImport() {"
+ "  const int i = sizeof...(Ts);"
+ "};"
+ "void g() { declToImport(); }",
+ Lang_CXX11, "", Lang_CXX11, Verifier,
+ functionTemplateDecl(has(functionDecl(
+ hasBody(compoundStmt(has(declStmt(has(varDecl(hasInitializer(
+ implicitCastExpr(has(sizeOfPackExpr());
+  testImport(
+  "template "
+  "using X = int[sizeof...(Ts)];"
+  "template "
+  "struct Y {"
+  "  X f;"
+  "};"
+  "Y declToImport;",
+  Lang_CXX11, "", Lang_CXX11, Verifier,
+  varDecl(hasType(classTemplateSpecializationDecl(has(fieldDecl(hasType(
+  hasUnqualifiedDesugaredType(constantArrayType(hasSize(7));
+}
+
 /// \brief Matches __builtin_types_compatible_p:
 /// GNU extension to check equivalent types
 /// Given
@@ -691,5 +745,25 @@
  binaryOperator(has(cxxUnresolvedConstructExpr());
 }
 
+TEST(ImportExpr, CXXOperatorCallExpr) {
+  MatchVerifier Verifier;
+  testImport("class declToImport {"
+ "  void f() { *this = declToImport(); }"
+ "};",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ cxxRecordDecl(has(cxxMethodDecl(hasBody(compoundStmt(
+ has(exprWithCleanups(has(cxxOperatorCallExpr());
+}
+
+TEST(ImportExpr, DependentSizedArrayType) {
+  MatchVerifier Verifier;
+  testImport("template class declToImport {"
+ "  T data[Size];"
+ "};",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ classTemplateDecl(has(cxxRecordDecl(
+ has(fieldDecl(hasType(dependentSizedArrayType(;
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -52,7 +52,7 @@
 QualType VisitConstantArrayType(const ConstantArrayType *T);
 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
 QualType VisitVariableArrayType(const VariableArrayType *T);
-// FIXME: DependentSizedArrayType
+QualType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
 // FIXME: DependentSizedExtVectorType
 QualType VisitVectorType(const VectorType *T);
 QualType VisitExtVectorType(const ExtVectorType *T);
@@ -78,7 +78,8 @@
 QualType VisitElaboratedType(const ElaboratedType *T);
 // FIXME: DependentNameType
 QualType VisitPackExpansionType(const PackExpansionType *T);
-// FIXME: DependentTemplateSpecializationType
+QualType VisitDependentTemplateSpecializationType(
+const DependentTemplateSpecializationType *T);
 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 QualType VisitObjCObjectType(const ObjCObjectType *T);
 QualType VisitObjCObjectPointerType(const ObjCObject

[PATCH] D42173: [clangd] Simplify code handling compile commands

2018-01-23 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 131062.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Unwrap the comment
- Remove ParseInputs constructor
- Document the CppFile invariant


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42173

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h

Index: clangd/ClangdUnitStore.h
===
--- clangd/ClangdUnitStore.h
+++ clangd/ClangdUnitStore.h
@@ -32,42 +32,19 @@
 
   std::shared_ptr
   getOrCreateFile(PathRef File, PathRef ResourceDir,
-  GlobalCompilationDatabase &CDB, bool StorePreamblesInMemory,
+  bool StorePreamblesInMemory,
   std::shared_ptr PCHs) {
 std::lock_guard Lock(Mutex);
-
 auto It = OpenedFiles.find(File);
 if (It == OpenedFiles.end()) {
-  auto Command = getCompileCommand(CDB, File, ResourceDir);
-
   It = OpenedFiles
-   .try_emplace(File, CppFile::Create(File, std::move(Command),
-  StorePreamblesInMemory,
+   .try_emplace(File, CppFile::Create(File, StorePreamblesInMemory,
   std::move(PCHs), ASTCallback))
.first;
 }
 return It->second;
   }
 
-  struct RecreateResult {
-/// A CppFile, stored in this CppFileCollection for the corresponding
-/// filepath after calling recreateFileIfCompileCommandChanged.
-std::shared_ptr FileInCollection;
-/// If a new CppFile had to be created to account for changed
-/// CompileCommand, a previous CppFile instance will be returned in this
-/// field.
-std::shared_ptr RemovedFile;
-  };
-
-  /// Similar to getOrCreateFile, but will replace a current CppFile for \p File
-  /// with a new one if CompileCommand, provided by \p CDB has changed.
-  /// If a currently stored CppFile had to be replaced, the previous instance
-  /// will be returned in RecreateResult.RemovedFile.
-  RecreateResult recreateFileIfCompileCommandChanged(
-  PathRef File, PathRef ResourceDir, GlobalCompilationDatabase &CDB,
-  bool StorePreamblesInMemory,
-  std::shared_ptr PCHs);
-
   std::shared_ptr getFile(PathRef File) {
 std::lock_guard Lock(Mutex);
 
@@ -82,12 +59,6 @@
   std::shared_ptr removeIfPresent(PathRef File);
 
 private:
-  tooling::CompileCommand getCompileCommand(GlobalCompilationDatabase &CDB,
-PathRef File, PathRef ResourceDir);
-
-  bool compileCommandsAreEqual(tooling::CompileCommand const &LHS,
-   tooling::CompileCommand const &RHS);
-
   std::mutex Mutex;
   llvm::StringMap> OpenedFiles;
   ASTParsedCallback ASTCallback;
Index: clangd/ClangdUnitStore.cpp
===
--- clangd/ClangdUnitStore.cpp
+++ clangd/ClangdUnitStore.cpp
@@ -25,53 +25,3 @@
   OpenedFiles.erase(It);
   return Result;
 }
-
-CppFileCollection::RecreateResult
-CppFileCollection::recreateFileIfCompileCommandChanged(
-PathRef File, PathRef ResourceDir, GlobalCompilationDatabase &CDB,
-bool StorePreamblesInMemory, std::shared_ptr PCHs) {
-  auto NewCommand = getCompileCommand(CDB, File, ResourceDir);
-
-  std::lock_guard Lock(Mutex);
-
-  RecreateResult Result;
-
-  auto It = OpenedFiles.find(File);
-  if (It == OpenedFiles.end()) {
-It = OpenedFiles
- .try_emplace(File, CppFile::Create(File, std::move(NewCommand),
-StorePreamblesInMemory,
-std::move(PCHs), ASTCallback))
- .first;
-  } else if (!compileCommandsAreEqual(It->second->getCompileCommand(),
-  NewCommand)) {
-Result.RemovedFile = std::move(It->second);
-It->second =
-CppFile::Create(File, std::move(NewCommand), StorePreamblesInMemory,
-std::move(PCHs), ASTCallback);
-  }
-  Result.FileInCollection = It->second;
-  return Result;
-}
-
-tooling::CompileCommand
-CppFileCollection::getCompileCommand(GlobalCompilationDatabase &CDB,
- PathRef File, PathRef ResourceDir) {
-  llvm::Optional C = CDB.getCompileCommand(File);
-  if (!C) // FIXME: Suppress diagnostics? Let the user know?
-C = CDB.getFallbackCommand(File);
-
-  // Inject the resource dir.
-  // FIXME: Don't overwrite it if it's already there.
-  C->CommandLine.push_back("-resource-dir=" + ResourceDir.str());
-  return std::move(*C);
-}
-
-bool CppFileCollection::compileCommandsAreEqual(
-tooling::CompileCommand const &LHS, tooling::CompileCommand const &RHS) {
-  // tooling::CompileCommand.Output is ignored, it's not relevant for clangd.
-  return LHS.Directory == RHS.Directory &&
- LHS.C

[PATCH] D42173: [clangd] Simplify code handling compile commands

2018-01-23 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked an inline comment as done.
ilya-biryukov added inline comments.



Comment at: clangd/ClangdUnit.h:62
+/// Information required to run clang (e.g., to parse AST or do code
+/// completion).
+struct ParseInputs {

sammccall wrote:
> sammccall wrote:
> > unwrap?
> This is not done. Is clang-format doing this?
> 
> (It looks like exactly 80 cols, but in any case the second comma shouldn't be 
> there :-))
Sorry, my mistake. Fixed now.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42173



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


[clang-tools-extra] r323204 - [clangd] Simplify code handling compile commands

2018-01-23 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Jan 23 07:07:52 2018
New Revision: 323204

URL: http://llvm.org/viewvc/llvm-project?rev=323204&view=rev
Log:
[clangd] Simplify code handling compile commands

Summary:
CppFile can now change compilation arguments during rebuild. This allows
simplifying code that manages CppFiles.

Reviewers: sammccall, bkramer, jkorous-apple

Reviewed By: sammccall

Subscribers: ioeric, jkorous-apple, klimek, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/clangd/ClangdUnit.h
clang-tools-extra/trunk/clangd/ClangdUnitStore.cpp
clang-tools-extra/trunk/clangd/ClangdUnitStore.h

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=323204&r1=323203&r2=323204&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Tue Jan 23 07:07:52 2018
@@ -32,6 +32,18 @@ using namespace clang::clangd;
 
 namespace {
 
+tooling::CompileCommand getCompileCommand(GlobalCompilationDatabase &CDB,
+  PathRef File, PathRef ResourceDir) {
+  llvm::Optional C = CDB.getCompileCommand(File);
+  if (!C) // FIXME: Suppress diagnostics? Let the user know?
+C = CDB.getFallbackCommand(File);
+
+  // Inject the resource dir.
+  // FIXME: Don't overwrite it if it's already there.
+  C->CommandLine.push_back("-resource-dir=" + ResourceDir.str());
+  return std::move(*C);
+}
+
 std::string getStandardResourceDir() {
   static int Dummy; // Just an address in this process.
   return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
@@ -175,11 +187,12 @@ std::future ClangdServer::addDo
   DocVersion Version = DraftMgr.updateDraft(File, Contents);
 
   auto TaggedFS = FSProvider.getTaggedFileSystem(File);
-  std::shared_ptr Resources = Units.getOrCreateFile(
-  File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
+  std::shared_ptr Resources =
+  Units.getOrCreateFile(File, ResourceDir, StorePreamblesInMemory, PCHs);
   return scheduleReparseAndDiags(std::move(Ctx), File,
  VersionedDraft{Version, Contents.str()},
- std::move(Resources), std::move(TaggedFS));
+ std::move(Resources), std::move(TaggedFS),
+ /*AllowCachedCompileFlags=*/true);
 }
 
 std::future ClangdServer::removeDocument(Context Ctx, PathRef File) {
@@ -194,15 +207,11 @@ std::future ClangdServer::force
  "forceReparse() was called for non-added document");
 
   auto TaggedFS = FSProvider.getTaggedFileSystem(File);
-  auto Recreated = Units.recreateFileIfCompileCommandChanged(
-  File, ResourceDir, CDB, StorePreamblesInMemory, PCHs);
-
-  // Note that std::future from this cleanup action is ignored.
-  scheduleCancelRebuild(Ctx.clone(), std::move(Recreated.RemovedFile));
-  // Schedule a reparse.
-  return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
- std::move(Recreated.FileInCollection),
- std::move(TaggedFS));
+  std::shared_ptr Resources =
+  Units.getOrCreateFile(File, ResourceDir, StorePreamblesInMemory, PCHs);
+  return scheduleReparseAndDiags(std::move(Ctx), File, FileContents,
+ std::move(Resources), std::move(TaggedFS),
+ /*AllowCachedCompileFlags=*/false);
 }
 
 std::future>>
@@ -268,20 +277,24 @@ void ClangdServer::codeComplete(
   Path FileStr = File;
   // Copy PCHs to avoid accessing this->PCHs concurrently
   std::shared_ptr PCHs = this->PCHs;
+
+  assert(Resources->getLastCommand() &&
+ "CppFile is in inconsistent state, missing CompileCommand");
+  tooling::CompileCommand CompileCommand = *Resources->getLastCommand();
+
   // A task that will be run asynchronously.
   auto Task =
   // 'mutable' to reassign Preamble variable.
   [FileStr, Preamble, Resources, Contents, Pos, CodeCompleteOpts, TaggedFS,
-   PCHs](Context Ctx, CallbackType Callback) mutable {
+   PCHs, CompileCommand](Context Ctx, CallbackType Callback) mutable {
 if (!Preamble) {
   // Maybe we built some preamble before processing this request.
   Preamble = Resources->getPossiblyStalePreamble();
 }
 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
 // both the old and the new version in case only one of them matches.
-
 CompletionList Result = clangd::codeComplete(
-Ctx, FileStr, Resources->getCompileCommand(),
+Ctx, FileStr, CompileCommand,
  

[PATCH] D42173: [clangd] Simplify code handling compile commands

2018-01-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323204: [clangd] Simplify code handling compile commands 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42173?vs=131062&id=131067#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42173

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h

Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -273,7 +273,6 @@
   return Mgr.getMacroArgExpandedLocation(InputLoc);
 }
 
-
 } // namespace
 
 void ParsedAST::ensurePreambleDeclsDeserialized() {
@@ -359,27 +358,22 @@
 : AST(std::move(AST)) {}
 
 std::shared_ptr
-CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
-bool StorePreamblesInMemory,
+CppFile::Create(PathRef FileName, bool StorePreamblesInMemory,
 std::shared_ptr PCHs,
 ASTParsedCallback ASTCallback) {
-  return std::shared_ptr(
-  new CppFile(FileName, std::move(Command), StorePreamblesInMemory,
-  std::move(PCHs), std::move(ASTCallback)));
+  return std::shared_ptr(new CppFile(FileName, StorePreamblesInMemory,
+  std::move(PCHs),
+  std::move(ASTCallback)));
 }
 
-CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
- bool StorePreamblesInMemory,
+CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
  std::shared_ptr PCHs,
  ASTParsedCallback ASTCallback)
-: FileName(FileName), Command(std::move(Command)),
-  StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
-  RebuildInProgress(false), PCHs(std::move(PCHs)),
+: FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
+  RebuildCounter(0), RebuildInProgress(false), PCHs(std::move(PCHs)),
   ASTCallback(std::move(ASTCallback)) {
   // FIXME(ibiryukov): we should pass a proper Context here.
-  log(Context::empty(), "Opened file " + FileName + " with command [" +
-this->Command.Directory + "] " +
-llvm::join(this->Command.CommandLine, " "));
+  log(Context::empty(), "Created CppFile for " + FileName);
 
   std::lock_guard Lock(Mutex);
   LatestAvailablePreamble = nullptr;
@@ -431,14 +425,12 @@
 }
 
 llvm::Optional>
-CppFile::rebuild(const Context &Ctx, StringRef NewContents,
- IntrusiveRefCntPtr VFS) {
-  return deferRebuild(NewContents, std::move(VFS))(Ctx);
+CppFile::rebuild(const Context &Ctx, ParseInputs &&Inputs) {
+  return deferRebuild(std::move(Inputs))(Ctx);
 }
 
 UniqueFunction>(const Context &)>
-CppFile::deferRebuild(StringRef NewContents,
-  IntrusiveRefCntPtr VFS) {
+CppFile::deferRebuild(ParseInputs &&Inputs) {
   std::shared_ptr OldPreamble;
   std::shared_ptr PCHs;
   unsigned RequestRebuildCounter;
@@ -463,6 +455,7 @@
   this->ASTPromise = std::promise>();
   this->ASTFuture = this->ASTPromise.get_future();
 }
+this->LastCommand = Inputs.CompileCommand;
   } // unlock Mutex.
   // Notify about changes to RebuildCounter.
   RebuildCond.notify_all();
@@ -473,22 +466,27 @@
   // Don't let this CppFile die before rebuild is finished.
   std::shared_ptr That = shared_from_this();
   auto FinishRebuild =
-  [OldPreamble, VFS, RequestRebuildCounter, PCHs,
-   That](std::string NewContents,
+  [OldPreamble, RequestRebuildCounter, PCHs,
+   That](ParseInputs Inputs,
  const Context &Ctx) mutable /* to allow changing OldPreamble. */
   -> llvm::Optional> {
+log(Context::empty(),
+"Rebuilding file " + That->FileName + " with command [" +
+Inputs.CompileCommand.Directory + "] " +
+llvm::join(Inputs.CompileCommand.CommandLine, " "));
+
 // Only one execution of this method is possible at a time.
 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
 // into a state for doing a rebuild.
 RebuildGuard Rebuild(*That, RequestRebuildCounter);
 if (Rebuild.wasCancelledBeforeConstruction())
   return llvm::None;
 
 std::vector ArgStrs;
-for (const auto &S : That->Command.CommandLine)
+for (const auto &S : Inputs.CompileCommand.CommandLine)
   ArgStrs.push_back(S.c_str());
 
-VFS->setCurrentWorkingDirectory(That->Command.Directory);
+Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
 
 std::unique_ptr CI;
 {
@@ -498,25 +496,26 @@
   IntrusiveRefCntPtr CommandLineDiagsEngine =
   CompilerInstance::createDiagnostics(new DiagnosticOptions,
   &IgnoreDiagnostics, false);
-  CI =
-  c

[PATCH] D42173: [clangd] Simplify code handling compile commands

2018-01-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323204: [clangd] Simplify code handling compile commands 
(authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42173

Files:
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/ClangdServer.h
  clang-tools-extra/trunk/clangd/ClangdUnit.cpp
  clang-tools-extra/trunk/clangd/ClangdUnit.h
  clang-tools-extra/trunk/clangd/ClangdUnitStore.cpp
  clang-tools-extra/trunk/clangd/ClangdUnitStore.h

Index: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp
@@ -273,7 +273,6 @@
   return Mgr.getMacroArgExpandedLocation(InputLoc);
 }
 
-
 } // namespace
 
 void ParsedAST::ensurePreambleDeclsDeserialized() {
@@ -359,27 +358,22 @@
 : AST(std::move(AST)) {}
 
 std::shared_ptr
-CppFile::Create(PathRef FileName, tooling::CompileCommand Command,
-bool StorePreamblesInMemory,
+CppFile::Create(PathRef FileName, bool StorePreamblesInMemory,
 std::shared_ptr PCHs,
 ASTParsedCallback ASTCallback) {
-  return std::shared_ptr(
-  new CppFile(FileName, std::move(Command), StorePreamblesInMemory,
-  std::move(PCHs), std::move(ASTCallback)));
+  return std::shared_ptr(new CppFile(FileName, StorePreamblesInMemory,
+  std::move(PCHs),
+  std::move(ASTCallback)));
 }
 
-CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command,
- bool StorePreamblesInMemory,
+CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
  std::shared_ptr PCHs,
  ASTParsedCallback ASTCallback)
-: FileName(FileName), Command(std::move(Command)),
-  StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0),
-  RebuildInProgress(false), PCHs(std::move(PCHs)),
+: FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
+  RebuildCounter(0), RebuildInProgress(false), PCHs(std::move(PCHs)),
   ASTCallback(std::move(ASTCallback)) {
   // FIXME(ibiryukov): we should pass a proper Context here.
-  log(Context::empty(), "Opened file " + FileName + " with command [" +
-this->Command.Directory + "] " +
-llvm::join(this->Command.CommandLine, " "));
+  log(Context::empty(), "Created CppFile for " + FileName);
 
   std::lock_guard Lock(Mutex);
   LatestAvailablePreamble = nullptr;
@@ -431,14 +425,12 @@
 }
 
 llvm::Optional>
-CppFile::rebuild(const Context &Ctx, StringRef NewContents,
- IntrusiveRefCntPtr VFS) {
-  return deferRebuild(NewContents, std::move(VFS))(Ctx);
+CppFile::rebuild(const Context &Ctx, ParseInputs &&Inputs) {
+  return deferRebuild(std::move(Inputs))(Ctx);
 }
 
 UniqueFunction>(const Context &)>
-CppFile::deferRebuild(StringRef NewContents,
-  IntrusiveRefCntPtr VFS) {
+CppFile::deferRebuild(ParseInputs &&Inputs) {
   std::shared_ptr OldPreamble;
   std::shared_ptr PCHs;
   unsigned RequestRebuildCounter;
@@ -463,6 +455,7 @@
   this->ASTPromise = std::promise>();
   this->ASTFuture = this->ASTPromise.get_future();
 }
+this->LastCommand = Inputs.CompileCommand;
   } // unlock Mutex.
   // Notify about changes to RebuildCounter.
   RebuildCond.notify_all();
@@ -473,22 +466,27 @@
   // Don't let this CppFile die before rebuild is finished.
   std::shared_ptr That = shared_from_this();
   auto FinishRebuild =
-  [OldPreamble, VFS, RequestRebuildCounter, PCHs,
-   That](std::string NewContents,
+  [OldPreamble, RequestRebuildCounter, PCHs,
+   That](ParseInputs Inputs,
  const Context &Ctx) mutable /* to allow changing OldPreamble. */
   -> llvm::Optional> {
+log(Context::empty(),
+"Rebuilding file " + That->FileName + " with command [" +
+Inputs.CompileCommand.Directory + "] " +
+llvm::join(Inputs.CompileCommand.CommandLine, " "));
+
 // Only one execution of this method is possible at a time.
 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
 // into a state for doing a rebuild.
 RebuildGuard Rebuild(*That, RequestRebuildCounter);
 if (Rebuild.wasCancelledBeforeConstruction())
   return llvm::None;
 
 std::vector ArgStrs;
-for (const auto &S : That->Command.CommandLine)
+for (const auto &S : Inputs.CompileCommand.CommandLine)
   ArgStrs.push_back(S.c_str());
 
-VFS->setCurrentWorkingDirectory(That->Command.Directory);
+Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
 
 std::unique_ptr CI;
 {
@@ -498,25 +496,26 @@
   IntrusiveRefCntPtr CommandLineDiagsEngine 

[PATCH] D42335: [ASTImporter] Supporting CXXOperatorCallExpr, SizeOfPackExpr, DependentTemplateSpecializationType, DependentSizedArray, CXXTypeidExpr importing.

2018-01-23 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 131065.
xazax.hun retitled this revision from "[ASTImporter] Supporting 
CXXOperatorCallExpr, SizeOfPackExpr, DependentTemplateSpecializationType, 
DependentSizedArray importing." to "[ASTImporter] Supporting 
CXXOperatorCallExpr, SizeOfPackExpr, DependentTemplateSpecializationType, 
DependentSizedArray, CXXTypeidExpr importing.".
xazax.hun added a comment.

- Added test for CXXTypeIdExpr import.


https://reviews.llvm.org/D42335

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

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -480,6 +480,16 @@
  vaArgExpr(;
 }
 
+TEST(ImportExpr, CXXTemporaryObjectExpr) {
+  MatchVerifier Verifier;
+  testImport("struct C {};"
+ "void declToImport() { C c = C(); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(has(
+ declStmt(has(varDecl(has(exprWithCleanups(has(cxxConstructExpr(
+ has(materializeTemporaryExpr(has(implicitCastExpr(
+ has(cxxTemporaryObjectExpr());
+}
 
 TEST(ImportType, ImportAtomicType) {
   MatchVerifier Verifier;
@@ -564,6 +574,50 @@
  declRefExpr());
 }
 
+const internal::VariadicDynCastAllOfMatcher
+dependentTemplateSpecializationType;
+
+TEST(ImportType, ImportDependentTemplateSpecialization) {
+  MatchVerifier Verifier;
+  testImport("template"
+ "struct A;"
+ "template"
+ "struct declToImport {"
+ "  typename A::template B a;"
+ "};",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ classTemplateDecl(has(cxxRecordDecl(has(
+ fieldDecl(hasType(dependentTemplateSpecializationType(;
+}
+
+const internal::VariadicDynCastAllOfMatcher
+sizeOfPackExpr;
+
+TEST(ImportExpr, ImportSizeOfPackExpr) {
+  MatchVerifier Verifier;
+  testImport("template "
+ "void declToImport() {"
+ "  const int i = sizeof...(Ts);"
+ "};"
+ "void g() { declToImport(); }",
+ Lang_CXX11, "", Lang_CXX11, Verifier,
+ functionTemplateDecl(has(functionDecl(
+ hasBody(compoundStmt(has(declStmt(has(varDecl(hasInitializer(
+ implicitCastExpr(has(sizeOfPackExpr());
+  testImport(
+  "template "
+  "using X = int[sizeof...(Ts)];"
+  "template "
+  "struct Y {"
+  "  X f;"
+  "};"
+  "Y declToImport;",
+  Lang_CXX11, "", Lang_CXX11, Verifier,
+  varDecl(hasType(classTemplateSpecializationDecl(has(fieldDecl(hasType(
+  hasUnqualifiedDesugaredType(constantArrayType(hasSize(7));
+}
+
 /// \brief Matches __builtin_types_compatible_p:
 /// GNU extension to check equivalent types
 /// Given
@@ -586,6 +640,19 @@
  typeTraitExpr(hasType(asString("int";
 }
 
+const internal::VariadicDynCastAllOfMatcher cxxTypeidExpr;
+
+TEST(ImportExpr, ImportCXXTypeidExpr) {
+  MatchVerifier Verifier;
+  testImport("namespace std { class type_info {}; }"
+ "void declToImport() {"
+ "  int x;"
+ "  (void)typeid(int); (void)typeid(x);"
+ "}",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasDescendant(cxxTypeidExpr(;
+}
+
 TEST(ImportExpr, ImportTypeTraitExprValDep) {
   MatchVerifier Verifier;
   testImport("template struct declToImport {"
@@ -691,5 +758,25 @@
  binaryOperator(has(cxxUnresolvedConstructExpr());
 }
 
+TEST(ImportExpr, CXXOperatorCallExpr) {
+  MatchVerifier Verifier;
+  testImport("class declToImport {"
+ "  void f() { *this = declToImport(); }"
+ "};",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ cxxRecordDecl(has(cxxMethodDecl(hasBody(compoundStmt(
+ has(exprWithCleanups(has(cxxOperatorCallExpr());
+}
+
+TEST(ImportExpr, DependentSizedArrayType) {
+  MatchVerifier Verifier;
+  testImport("template class declToImport {"
+ "  T data[Size];"
+ "};",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ classTemplateDecl(has(cxxRecordDecl(
+ has(fieldDecl(hasType(dependentSizedArrayType(;
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -52,7 +52,7 @@
 QualType VisitConstantArrayType(const ConstantArrayType *T);
 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
 QualType VisitVariableArrayType(const VariableArrayType *T);
-// FIXME: DependentSizedArrayType
+QualType VisitDepend

[PATCH] D42413: [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via Phabricator via cfe-commits
malcolm.parsons updated this revision to Diff 131069.
malcolm.parsons added a comment.

Use ternary operator.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42413

Files:
  clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  test/clang-tidy/modernize-use-default-member-init-bitfield.cpp


Index: test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- 
-std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};
Index: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -167,7 +167,9 @@
   isDefaultConstructor(), unless(isInstantiated()),
   forEachConstructorInitializer(
   cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
+  forField(unless(anyOf(getLangOpts().CPlusPlus2a
+? unless(anything())
+: isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
   isWritten(), withInitializer(ignoringImplicit(Init)))


Index: test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- -std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};
Index: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -167,7 +167,9 @@
   isDefaultConstructor(), unless(isInstantiated()),
   forEachConstructorInitializer(
   cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
+  forField(unless(anyOf(getLangOpts().CPlusPlus2a
+? unless(anything())
+: isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
   isWritten(), withInitializer(ignoringImplicit(Init)))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42413: [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via Phabricator via cfe-commits
malcolm.parsons added inline comments.



Comment at: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:165
 
-  Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
-  .bind("default"))),
-  this);
+  if (getLangOpts().CPlusPlus2a)
+Finder->addMatcher(

aaron.ballman wrote:
> I wonder if we could add a `nothing()` matcher (sibling to the `anything()` 
> matcher) so that this could be rewritten as:
> 
> `unless(anyOf(getLangOpts().CPlusPlus2a ? nothing() : isBitField()))`
> 
> The duplication here adds complexity if we decide to change the matchers in 
> the future.
`unless(anything())` is equivalent to `nothing()`.



Comment at: test/clang-tidy/modernize-use-default-member-init-bitfield.cpp:1
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- 
-std=c++2a
+

aaron.ballman wrote:
> I'd like to see a test where C++2a is not enabled to ensure that the fix is 
> not suggested in that case.
See [[ 
https://reviews.llvm.org/source/clang-tools-extra/browse/clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init.cpp;323204$222
 | modernize-use-default-member-init.cpp:222 ]]



Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42413



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


[PATCH] D42413: [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

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

LGTM!




Comment at: clang-tidy/modernize/UseDefaultMemberInitCheck.cpp:165
 
-  Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
-  .bind("default"))),
-  this);
+  if (getLangOpts().CPlusPlus2a)
+Finder->addMatcher(

malcolm.parsons wrote:
> aaron.ballman wrote:
> > I wonder if we could add a `nothing()` matcher (sibling to the `anything()` 
> > matcher) so that this could be rewritten as:
> > 
> > `unless(anyOf(getLangOpts().CPlusPlus2a ? nothing() : isBitField()))`
> > 
> > The duplication here adds complexity if we decide to change the matchers in 
> > the future.
> `unless(anything())` is equivalent to `nothing()`.
Ah, good point! Nice, this is much more clean.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42413



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


[clang-tools-extra] r323208 - [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via cfe-commits
Author: malcolm.parsons
Date: Tue Jan 23 07:32:42 2018
New Revision: 323208

URL: http://llvm.org/viewvc/llvm-project?rev=323208&view=rev
Log:
[clang-tidy] Handle bitfields in modernize-use-default-member-init if using 
C++2a

Summary:
C++2a allows bitfields to have default member initializers.
Add support for this to clang-tidy's modernize-use-default-member-init check.

Reviewers: aaron.ballman, alexfh

Reviewed By: aaron.ballman

Subscribers: klimek, xazax.hun, cfe-commits

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

Added:

clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp?rev=323208&r1=323207&r2=323208&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
Tue Jan 23 07:32:42 2018
@@ -167,7 +167,9 @@ void UseDefaultMemberInitCheck::register
   isDefaultConstructor(), unless(isInstantiated()),
   forEachConstructorInitializer(
   cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
+  forField(unless(anyOf(getLangOpts().CPlusPlus2a
+? unless(anything())
+: isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
   isWritten(), withInitializer(ignoringImplicit(Init)))

Added: 
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp?rev=323208&view=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
 Tue Jan 23 07:32:42 2018
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- 
-std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};


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


[PATCH] D42413: [clang-tidy] Handle bitfields in modernize-use-default-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323208: [clang-tidy] Handle bitfields in 
modernize-use-default-member-init if using… (authored by malcolm.parsons, 
committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42413

Files:
  clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp


Index: 
clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -167,7 +167,9 @@
   isDefaultConstructor(), unless(isInstantiated()),
   forEachConstructorInitializer(
   cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
+  forField(unless(anyOf(getLangOpts().CPlusPlus2a
+? unless(anything())
+: isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
   isWritten(), withInitializer(ignoringImplicit(Init)))
Index: 
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
===
--- 
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
+++ 
clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- 
-std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};


Index: clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -167,7 +167,9 @@
   isDefaultConstructor(), unless(isInstantiated()),
   forEachConstructorInitializer(
   cxxCtorInitializer(
-  forField(unless(anyOf(isBitField(),
+  forField(unless(anyOf(getLangOpts().CPlusPlus2a
+? unless(anything())
+: isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
   isWritten(), withInitializer(ignoringImplicit(Init)))
Index: clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-use-default-member-init-bitfield.cpp
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s modernize-use-default-member-init %t -- -- -std=c++2a
+
+struct PositiveBitField
+{
+  PositiveBitField() : i(6) {}
+  // CHECK-FIXES: PositiveBitField()  {}
+  int i : 5;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i' [modernize-use-default-member-init]
+  // CHECK-FIXES: int i : 5{6};
+};
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42043: c-index: CXString: fix MSAN read-past-end bug

2018-01-23 Thread Steve O'Brien via Phabricator via cfe-commits
elsteveogrande added a comment.

Hi @vsk + @arphaman : I did find such problems with either MSAN (with 
poison-in-dtor) and ASAN, so we should be able to discover these instances 
pretty easily :)


Repository:
  rC Clang

https://reviews.llvm.org/D42043



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


r323157 - [ASTMatchers] [NFC] Fix code examples

2018-01-23 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Mon Jan 22 14:34:15 2018
New Revision: 323157

URL: http://llvm.org/viewvc/llvm-project?rev=323157&view=rev
Log:
[ASTMatchers] [NFC] Fix code examples

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=323157&r1=323156&r2=323157&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Mon Jan 22 14:34:15 2018
@@ -700,7 +700,7 @@ Example matches x.y() and y()
 Given
   switch(a) { case 42: break; default: break; }
 caseStmt()
-  matches 'case 42: break;'.
+  matches 'case 42:'.
 
 
 
@@ -741,7 +741,7 @@ Example match: {1}, (1, 2)
 MatcherStmt>compoundStmtMatcherCompoundStmt>...
 Matches compound 
statements.
 
-Example matches '{}' and '{{}}'in 'for (;;) {{}}'
+Example matches '{}' and '{{}}' in 'for (;;) {{}}'
   for (;;) {{}}
 
 
@@ -1028,7 +1028,7 @@ declStmt()
 Given
   switch(a) { case 42: break; default: break; }
 defaultStmt()
-  matches 'default: break;'.
+  matches 'default:'.
 
 
 
@@ -1197,9 +1197,9 @@ Example: Given
 materializeTemporaryExpr() matches 'f()' in these statements
   T u(f());
   g(f());
+  f().func();
 but does not match
   f();
-  f().func();
 
 
 
@@ -1369,7 +1369,7 @@ substNonTypeTemplateParmExpr()
 Given
   switch(a) { case 42: break; default: break; }
 switchCase()
-  matches 'case 42: break;' and 'default: break;'.
+  matches 'case 42:' and 'default:'.
 
 
 
@@ -2940,11 +2940,11 @@ Given
   void j(int i);
   void k(int x, int y, int z, ...);
 functionDecl(parameterCountIs(2))
-  matches void g(int i, int j) {}
+  matches g and h
 functionProtoType(parameterCountIs(2))
-  matches void h(int i, int j)
+  matches g and h
 functionProtoType(parameterCountIs(3))
-  matches void k(int x, int y, int z, ...);
+  matches k
 
 
 
@@ -2990,11 +2990,11 @@ Given
   void j(int i);
   void k(int x, int y, int z, ...);
 functionDecl(parameterCountIs(2))
-  matches void g(int i, int j) {}
+  matches g and h
 functionProtoType(parameterCountIs(2))
-  matches void h(int i, int j)
+  matches g and h
 functionProtoType(parameterCountIs(3))
-  matches void k(int x, int y, int z, ...);
+  matches k
 
 
 
@@ -3534,7 +3534,7 @@ an arbitrary precision integer. 'Value'
 representation of that integral value in base 10.
 
 Given
-  template struct A {};
+  template struct C {};
   C<42> c;
 classTemplateSpecializationDecl(
   hasAnyTemplateArgument(equalsIntegralValue("42")))
@@ -3546,7 +3546,7 @@ classTemplateSpecializationDecl(
 Matches a 
TemplateArgument that is an integral value.
 
 Given
-  template struct A {};
+  template struct C {};
   C<42> c;
 classTemplateSpecializationDecl(
   hasAnyTemplateArgument(isIntegral()))
@@ -3973,10 +3973,11 @@ Usable as: Any Matcher
 Matches AST nodes 
that have descendant AST nodes that match the
 provided matcher.
 
-Example matches X, A, B, C
+Example matches X, A, A::X, B, B::C, B::C::X
   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")
-  class X {};  Matches X, because X::X is a class of name X inside X.
-  class A { class X {}; };
+  class X {};
+  class A { class X {}; };  Matches A, because A::X is a class of name
+X inside A.
   class B { class C { class X {}; }; };
 
 DescendantT must be an AST base type.
@@ -3999,10 +4000,11 @@ Usable as: Any Matcher
 Matches AST nodes that have 
child AST nodes that match the
 provided matcher.
 
-Example matches X, Y
+Example matches X, Y, Y::X, Z::Y, Z::Y::X
   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
-  class X {};  Matches X, because X::X is a class of name X inside X.
-  class Y { class X {}; };
+  class X {};
+  class Y { class X {}; };  Matches Y, because Y::X is a class of name X
+inside Y.
   class Z { class Y { class X {}; }; };  Does not match Z.
 
 ChildT must be an AST base type.
@@ -4479,7 +4481,7 @@ matches 'a' in
 Example matches y.x()
   (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))
   class Y { public: void x(); };
-  void z() { Y y; y.x(); }",
+  void z() { Y y; y.x(); }
 
 FIXME: Overload to allow directly matching types?
 
@@ -4795,7 +4797,7 @@ Given
   A b;
   A c;
 
-  template f() {};
+  template void f() {}
   void func() { f(); };
 classTemplateSpecializationDecl(hasTemplateArgument(
 1, refersToType(asString("int"
@@ -5312,7 +5314,7 @@ Given
   A b;
   A c;
 
-  template f() 

[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-01-23 Thread Simon Marchi via Phabricator via cfe-commits
simark added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:78
 {"documentHighlightProvider", true},
+{"configurationChangeProvider", true},
 {"renameProvider", true},

I find `configurationChangeProvider` a bit weird.  It makes it sound like 
clangd can provide configuration changes.  In reality, it can accept 
configuration changes.  So I think this should be named something else.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D39571



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


[PATCH] D42416: [Driver] Add support for mips32 and scudo

2018-01-23 Thread Kostya Kortchinsky via Phabricator via cfe-commits
cryptoad accepted this revision.
cryptoad added a comment.

Cool thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D42416



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


[PATCH] D42416: [Driver] Add support for mips32 and scudo

2018-01-23 Thread Kostya Kortchinsky via Phabricator via cfe-commits
cryptoad added inline comments.



Comment at: lib/Driver/ToolChains/Linux.cpp:850
+  const bool IsMIPS = getTriple().getArch() == llvm::Triple::mips ||
+getTriple().getArch() == llvm::Triple::mipsel;
   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||

nit: get rid of 2 extra spaces here.


Repository:
  rC Clang

https://reviews.llvm.org/D42416



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


r323218 - clang-format: Support formatting Java 8 interface default methods.

2018-01-23 Thread Nico Weber via cfe-commits
Author: nico
Date: Tue Jan 23 08:30:56 2018
New Revision: 323218

URL: http://llvm.org/viewvc/llvm-project?rev=323218&view=rev
Log:
clang-format: Support formatting Java 8 interface default methods.

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTestJava.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=323218&r1=323217&r2=323218&view=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Tue Jan 23 08:30:56 2018
@@ -333,7 +333,18 @@ void UnwrappedLineParser::parseLevel(boo
   nextToken();
   addUnwrappedLine();
   break;
-case tok::kw_default:
+case tok::kw_default: {
+  unsigned StoredPosition = Tokens->getPosition();
+  FormatToken *Next = Tokens->getNextToken();
+  FormatTok = Tokens->setPosition(StoredPosition);
+  if (Next && Next->isNot(tok::colon)) {
+// default not followed by ':' is not a case label; treat it like
+// an identifier.
+parseStructuralElement();
+break;
+  }
+  // Else, if it is 'default:', fall through to the case handling.
+}
 case tok::kw_case:
   if (Style.Language == FormatStyle::LK_JavaScript &&
   Line->MustBeDeclaration) {
@@ -1032,8 +1043,12 @@ void UnwrappedLineParser::parseStructura
   // 'default: string' field declaration.
   break;
 nextToken();
-parseLabel();
-return;
+if (FormatTok->is(tok::colon)) {
+  parseLabel();
+  return;
+}
+// e.g. "default void f() {}" in a Java interface.
+break;
   case tok::kw_case:
 if (Style.Language == FormatStyle::LK_JavaScript && 
Line->MustBeDeclaration)
   // 'case: string' field declaration.

Modified: cfe/trunk/unittests/Format/FormatTestJava.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJava.cpp?rev=323218&r1=323217&r2=323218&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestJava.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJava.cpp Tue Jan 23 08:30:56 2018
@@ -144,6 +144,7 @@ TEST_F(FormatTestJava, ClassDeclarations
   verifyFormat("public interface SomeInterface {\n"
"  void doStuff(int theStuff);\n"
"  void doMoreStuff(int moreStuff);\n"
+   "  default void doStuffWithDefault() {}\n"
"}");
   verifyFormat("@interface SomeInterface {\n"
"  void doStuff(int theStuff);\n"


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


[PATCH] D42426: [clang-tidy] Handle bitfields in cppcoreguidelines-pro-type-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via Phabricator via cfe-commits
malcolm.parsons created this revision.
malcolm.parsons added reviewers: aaron.ballman, alexfh.
Herald added subscribers: cfe-commits, kbarton, xazax.hun, nemanjai, klimek.

C++2a allows bitfields to have default member initializers.
Add support for this to clang-tidy's cppcoreguidelines-pro-type-member-init 
check.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42426

Files:
  clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
  test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
  test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp


Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
@@ -474,6 +474,7 @@
   PositiveBitfieldMember() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these fields: F
   unsigned F : 5;
+  // CHECK-FIXES-NOT: unsigned F : 5{};
 };
 
 struct NegativeUnnamedBitfieldMember {
Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -- 
-std=c++2a -fno-delayed-template-parsing
+
+struct PositiveBitfieldMember {
+  PositiveBitfieldMember() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these fields: F
+  unsigned F : 5;
+  // CHECK-FIXES: unsigned F : 5{};
+};
+
+struct NegativeUnnamedBitfieldMember {
+  NegativeUnnamedBitfieldMember() {}
+  unsigned : 5;
+};
+
+struct NegativeInitializedBitfieldMembers {
+  NegativeInitializedBitfieldMembers() : F(3) { G = 2; }
+  unsigned F : 5;
+  unsigned G : 5;
+};
Index: clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -404,8 +404,9 @@
   return;
 // Don't suggest fixes for enums because we don't know a good default.
 // Don't suggest fixes for bitfields because in-class initialization is not
-// possible.
-if (F->getType()->isEnumeralType() || F->isBitField())
+// possible until C++2a.
+if (F->getType()->isEnumeralType() ||
+(!getLangOpts().CPlusPlus2a && F->isBitField()))
   return;
 if (!F->getParent()->isUnion() || UnionsSeen.insert(F->getParent()).second)
   FieldsToFix.insert(F);


Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
@@ -474,6 +474,7 @@
   PositiveBitfieldMember() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: F
   unsigned F : 5;
+  // CHECK-FIXES-NOT: unsigned F : 5{};
 };
 
 struct NegativeUnnamedBitfieldMember {
Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -- -std=c++2a -fno-delayed-template-parsing
+
+struct PositiveBitfieldMember {
+  PositiveBitfieldMember() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: F
+  unsigned F : 5;
+  // CHECK-FIXES: unsigned F : 5{};
+};
+
+struct NegativeUnnamedBitfieldMember {
+  NegativeUnnamedBitfieldMember() {}
+  unsigned : 5;
+};
+
+struct NegativeInitializedBitfieldMembers {
+  NegativeInitializedBitfieldMembers() : F(3) { G = 2; }
+  unsigned F : 5;
+  unsigned G : 5;
+};
Index: clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -404,8 +404,9 @@
   return;
 // Don't suggest fixes for enums because we don't know a good default.
 // Don't suggest fixes for bitfields because in-class initialization is not
-// possible.
-if (F->getType()->isEnumeralType() || F->isBitField())
+// possible until C++2a.
+if (F->getType()->isEnumeralType() ||
+(!getLangOpts().CPlusPlus2a && F->isBitField()))
   return;
 if (!F->getParent()->isUnion() || UnionsSeen.insert(F->getParent()).second)
   FieldsToFix.insert(F);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42426: [clang-tidy] Handle bitfields in cppcoreguidelines-pro-type-member-init if using C++2a

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

LGTM!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42426



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


[PATCH] D42428: [CodeComplete] only respect LoadExternal hint at namespace/tu scope

2018-01-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D42428

Files:
  include/clang-c/Index.h
  include/clang/Sema/CodeCompleteOptions.h
  lib/Sema/SemaLookup.cpp
  test/Index/complete-pch-skip.cpp


Index: test/Index/complete-pch-skip.cpp
===
--- test/Index/complete-pch-skip.cpp
+++ test/Index/complete-pch-skip.cpp
@@ -3,8 +3,9 @@
 }
 
 int main() { return ns:: }
+int main2() { return ns::foo(). }
 
-// RUN: echo "namespace ns { int foo; }" > %t.h
+// RUN: echo "namespace ns { struct foo { int baz }; }" > %t.h
 // RUN: c-index-test -write-pch %t.h.pch -x c++-header %t.h
 //
 // RUN: c-index-test -code-completion-at=%s:5:26 -include %t.h %s | FileCheck 
-check-prefix=WITH-PCH %s
@@ -23,3 +24,7 @@
 // NO-PCH: {TypedText bar}
 // NO-PCH-NOT: foo
 
+// Verify that we still get member results from the preamble.
+// RUN: env CINDEXTEST_COMPLETION_SKIP_PREAMBLE=1 c-index-test 
-code-completion-at=%s:6:32 -include %t.h %s | FileCheck -check-prefix=MEMBER %s
+// MEMBER: {TypedText baz}
+
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -3543,10 +3543,13 @@
   if (CXXRecordDecl *Class = dyn_cast(Ctx))
 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
 
+  // We sometimes skip loading namespace-level results (they tend to be huge).
+  bool Load = LoadExternal ||
+  !(isa(Ctx) || isa(Ctx));
   // Enumerate all of the results in this context.
   for (DeclContextLookupResult R :
-   LoadExternal ? Ctx->lookups()
-: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
+   Load ? Ctx->lookups()
+: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
 for (auto *D : R) {
   if (auto *ND = Result.getAcceptableDecl(D)) {
 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
Index: include/clang/Sema/CodeCompleteOptions.h
===
--- include/clang/Sema/CodeCompleteOptions.h
+++ include/clang/Sema/CodeCompleteOptions.h
@@ -35,8 +35,8 @@
   /// Show brief documentation comments in code completion results.
   unsigned IncludeBriefComments : 1;
 
-  /// Hint whether to load data from the external AST in order to provide
-  /// full results. If false, declarations from the preamble may be omitted.
+  /// Hint whether to load data from the external AST to provide full results.
+  /// If false, namespace-level declarations from the preamble may be omitted.
   unsigned LoadExternal : 1;
 
   CodeCompleteOptions()
Index: include/clang-c/Index.h
===
--- include/clang-c/Index.h
+++ include/clang-c/Index.h
@@ -5247,9 +5247,9 @@
   CXCodeComplete_IncludeBriefComments = 0x04,
 
   /**
-   * \brief Whether to speed up completion by omitting some entities which are
-   * defined in the preamble. There's no guarantee any particular entity will
-   * be omitted. This may be useful if the headers are indexed externally.
+   * Whether to speed up completion by omitting top- or namespace-level 
entities
+   * defined in the preamble. There's no guarantee any particular entity is
+   * omitted. This may be useful if the headers are indexed externally.
*/
   CXCodeComplete_SkipPreamble = 0x08
 };


Index: test/Index/complete-pch-skip.cpp
===
--- test/Index/complete-pch-skip.cpp
+++ test/Index/complete-pch-skip.cpp
@@ -3,8 +3,9 @@
 }
 
 int main() { return ns:: }
+int main2() { return ns::foo(). }
 
-// RUN: echo "namespace ns { int foo; }" > %t.h
+// RUN: echo "namespace ns { struct foo { int baz }; }" > %t.h
 // RUN: c-index-test -write-pch %t.h.pch -x c++-header %t.h
 //
 // RUN: c-index-test -code-completion-at=%s:5:26 -include %t.h %s | FileCheck -check-prefix=WITH-PCH %s
@@ -23,3 +24,7 @@
 // NO-PCH: {TypedText bar}
 // NO-PCH-NOT: foo
 
+// Verify that we still get member results from the preamble.
+// RUN: env CINDEXTEST_COMPLETION_SKIP_PREAMBLE=1 c-index-test -code-completion-at=%s:6:32 -include %t.h %s | FileCheck -check-prefix=MEMBER %s
+// MEMBER: {TypedText baz}
+
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -3543,10 +3543,13 @@
   if (CXXRecordDecl *Class = dyn_cast(Ctx))
 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
 
+  // We sometimes skip loading namespace-level results (they tend to be huge).
+  bool Load = LoadExternal ||
+  !(isa(Ctx) || isa(Ctx));
   // Enumerate all of the results in this context.
   for (DeclContextLookupResult R :
-   LoadExternal ? Ctx->lookups()
-: Ctx->noload_lookups(/*Pr

[PATCH] D16403: Add scope information to CFG

2018-01-23 Thread Maxim Ostapenko via Phabricator via cfe-commits
m.ostapenko updated this revision to Diff 131091.
m.ostapenko added a comment.
Herald added a subscriber: llvm-commits.

Rebased and ping.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403

Files:
  include/clang/Analysis/AnalysisDeclContext.h
  include/clang/Analysis/CFG.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/Analysis/AnalysisDeclContext.cpp
  lib/Analysis/CFG.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/scopes-cfg-output.cpp

Index: test/Analysis/scopes-cfg-output.cpp
===
--- /dev/null
+++ test/Analysis/scopes-cfg-output.cpp
@@ -0,0 +1,1171 @@
+// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -analyze -analyzer-checker=debug.DumpCFG -analyzer-config cfg-scopes=true %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s
+
+class A {
+public:
+// CHECK:  [B1 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+  A() {}
+
+// CHECK:  [B1 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+  ~A() {}
+
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// CHECK-NEXT:   1: 1
+// CHECK-NEXT:   2: return [B1.1];
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+  operator int() const { return 1; }
+};
+
+int getX();
+extern const bool UV;
+
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeBegin(a)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A [2])
+// CHECK-NEXT:   3: A a[2];
+// CHECK-NEXT:   4:  (CXXConstructExpr, class A [0])
+// CHECK-NEXT:   5: A b[0];
+// CHECK-NEXT:   6: CFGScopeEnd(a)
+// CHECK-NEXT:   7: [B1.3].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+void test_array() {
+  A a[2];
+  A b[0];
+}
+
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeBegin(a)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   3: A a;
+// CHECK-NEXT:   4: CFGScopeBegin(c)
+// CHECK-NEXT:   5:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   6: A c;
+// CHECK-NEXT:   7:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   8: A d;
+// CHECK-NEXT:   9: CFGScopeEnd(c)
+// CHECK-NEXT:  10: [B1.8].~A() (Implicit destructor)
+// CHECK-NEXT:  11: [B1.6].~A() (Implicit destructor)
+// CHECK-NEXT:  12:  (CXXConstructExpr, class A)
+// CHECK-NEXT:  13: A b;
+// CHECK-NEXT:  14: CFGScopeEnd(a)
+// CHECK-NEXT:  15: [B1.13].~A() (Implicit destructor)
+// CHECK-NEXT:  16: [B1.3].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+void test_scope() {
+  A a;
+  { A c;
+A d;
+  }
+  A b;
+}
+
+// CHECK:  [B4 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B3
+// CHECK:  [B1]
+// CHECK-NEXT:   1:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   2: A c;
+// CHECK-NEXT:   3: CFGScopeEnd(a)
+// CHECK-NEXT:   4: [B1.2].~A() (Implicit destructor)
+// CHECK-NEXT:   5: [B3.5].~A() (Implicit destructor)
+// CHECK-NEXT:   6: [B3.3].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B3
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B2]
+// CHECK-NEXT:   1: return;
+// CHECK-NEXT:   2: CFGScopeEnd(a)
+// CHECK-NEXT:   3: [B3.5].~A() (Implicit destructor)
+// CHECK-NEXT:   4: [B3.3].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B3
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B3]
+// CHECK-NEXT:   1: CFGScopeBegin(a)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   3: A a;
+// CHECK-NEXT:   4:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   5: A b;
+// CHECK-NEXT:   6: UV
+// CHECK-NEXT:   7: [B3.6] (ImplicitCastExpr, LValueToRValue, _Bool)
+// CHECK-NEXT:   T: if [B3.7]
+// CHECK-NEXT:   Preds (1): B4
+// CHECK-NEXT:   Succs (2): B2 B1
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (2): B1 B2
+void test_return() {
+  A a;
+  A b;
+  if (UV) return;
+  A c;
+}
+
+// CHECK:  [B5 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B4
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeEnd(b)
+// CHECK-NEXT:   2: [B4.8].~A() (Implicit destructor)
+// CHECK-NEXT:   3: CFGScopeEnd(a)
+// CHECK-NEXT:   4: [B4.3].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (2): B2 B3
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B2]
+// CHECK-NEXT:   1: CFGScopeBegin(c)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   3: A c;
+// CHECK-NEXT:   4: CFGScopeEnd(c)
+// CHECK-NEXT:   5: [B2.3].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B4
+// CHECK-NEXT: 

r323224 - [WebAssembly] Add mem.* builtin functions.

2018-01-23 Thread Dan Gohman via cfe-commits
Author: djg
Date: Tue Jan 23 09:04:04 2018
New Revision: 323224

URL: http://llvm.org/viewvc/llvm-project?rev=323224&view=rev
Log:
[WebAssembly] Add mem.* builtin functions.

This corresponds to r323222 in LLVM. The new names are not yet
finalized, so use them at your own risk.

Modified:
cfe/trunk/include/clang/Basic/BuiltinsWebAssembly.def
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/builtins-wasm.c
cfe/trunk/test/CodeGen/wasm-arguments.c

Modified: cfe/trunk/include/clang/Basic/BuiltinsWebAssembly.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/BuiltinsWebAssembly.def?rev=323224&r1=323223&r2=323224&view=diff
==
--- cfe/trunk/include/clang/Basic/BuiltinsWebAssembly.def (original)
+++ cfe/trunk/include/clang/Basic/BuiltinsWebAssembly.def Tue Jan 23 09:04:04 
2018
@@ -16,8 +16,16 @@
 
 // The format of this database matches clang/Basic/Builtins.def.
 
-// Note that current_memory is not "c" (readnone) because it must be sequenced
+// Query the current memory size, and increase the current memory size.
+// Note that mem.size is not "c" (readnone) because it must be sequenced
 // with respect to grow_memory calls.
+// These are the new proposed names, which aren't yet official. Use at your own
+// risk.
+BUILTIN(__builtin_wasm_mem_size, "zIi", "n")
+BUILTIN(__builtin_wasm_mem_grow, "zIiz", "n")
+
+// These are the existing names, which are currently official, but expected
+// to be deprecated in the future. They also lack the immediate field.
 BUILTIN(__builtin_wasm_current_memory, "z", "n")
 BUILTIN(__builtin_wasm_grow_memory, "zz", "n")
 

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=323224&r1=323223&r2=323224&view=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Tue Jan 23 09:04:04 2018
@@ -10495,6 +10495,21 @@ Value *CodeGenFunction::EmitNVPTXBuiltin
 Value *CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
const CallExpr *E) {
   switch (BuiltinID) {
+  case WebAssembly::BI__builtin_wasm_mem_size: {
+llvm::Type *ResultType = ConvertType(E->getType());
+Value *I = EmitScalarExpr(E->getArg(0));
+Value *Callee = CGM.getIntrinsic(Intrinsic::wasm_mem_size, ResultType);
+return Builder.CreateCall(Callee, I);
+  }
+  case WebAssembly::BI__builtin_wasm_mem_grow: {
+llvm::Type *ResultType = ConvertType(E->getType());
+Value *Args[] = {
+  EmitScalarExpr(E->getArg(0)),
+  EmitScalarExpr(E->getArg(1))
+};
+Value *Callee = CGM.getIntrinsic(Intrinsic::wasm_mem_grow, ResultType);
+return Builder.CreateCall(Callee, Args);
+  }
   case WebAssembly::BI__builtin_wasm_current_memory: {
 llvm::Type *ResultType = ConvertType(E->getType());
 Value *Callee = CGM.getIntrinsic(Intrinsic::wasm_current_memory, 
ResultType);

Modified: cfe/trunk/test/CodeGen/builtins-wasm.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtins-wasm.c?rev=323224&r1=323223&r2=323224&view=diff
==
--- cfe/trunk/test/CodeGen/builtins-wasm.c (original)
+++ cfe/trunk/test/CodeGen/builtins-wasm.c Tue Jan 23 09:04:04 2018
@@ -3,25 +3,37 @@
 // RUN: %clang_cc1 -triple wasm64-unknown-unknown -O3 -emit-llvm -o - %s \
 // RUN:   | FileCheck %s -check-prefix=WEBASSEMBLY64
 
-__SIZE_TYPE__ f1(void) {
+__SIZE_TYPE__ f0(void) {
+  return __builtin_wasm_mem_size(0);
+// WEBASSEMBLY32: call {{i.*}} @llvm.wasm.mem.size.i32(i32 0)
+// WEBASSEMBLY64: call {{i.*}} @llvm.wasm.mem.size.i64(i32 0)
+}
+
+__SIZE_TYPE__ f1(__SIZE_TYPE__ delta) {
+  return __builtin_wasm_mem_grow(0, delta);
+// WEBASSEMBLY32: call i32 @llvm.wasm.mem.grow.i32(i32 0, i32 %{{.*}})
+// WEBASSEMBLY64: call i64 @llvm.wasm.mem.grow.i64(i32 0, i64 %{{.*}})
+}
+
+__SIZE_TYPE__ f2(void) {
   return __builtin_wasm_current_memory();
 // WEBASSEMBLY32: call {{i.*}} @llvm.wasm.current.memory.i32()
 // WEBASSEMBLY64: call {{i.*}} @llvm.wasm.current.memory.i64()
 }
 
-__SIZE_TYPE__ f2(__SIZE_TYPE__ delta) {
+__SIZE_TYPE__ f3(__SIZE_TYPE__ delta) {
   return __builtin_wasm_grow_memory(delta);
 // WEBASSEMBLY32: call i32 @llvm.wasm.grow.memory.i32(i32 %{{.*}})
 // WEBASSEMBLY64: call i64 @llvm.wasm.grow.memory.i64(i64 %{{.*}})
 }
 
-void f3(unsigned int tag, void *obj) {
+void f4(unsigned int tag, void *obj) {
   return __builtin_wasm_throw(tag, obj);
 // WEBASSEMBLY32: call void @llvm.wasm.throw(i32 %{{.*}}, i8* %{{.*}})
 // WEBASSEMBLY64: call void @llvm.wasm.throw(i32 %{{.*}}, i8* %{{.*}})
 }
 
-void f4() {
+void f5(void) {
   return __builtin_wasm_rethrow();
 // WEBASSEMBLY32: call void @llvm.wasm.rethrow()
 // WEBASSEMBLY64: call void @llvm.wasm.rethrow()

Mod

r323225 - test: adjust the target for some Windows tests

2018-01-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Jan 23 09:05:57 2018
New Revision: 323225

URL: http://llvm.org/viewvc/llvm-project?rev=323225&view=rev
Log:
test: adjust the target for some Windows tests

The tests are targeting Windows but do not specify an environment.  When
executed on Linux, they would use an ELF output rather than the COFF
output.  Explicitly provide an environment.

Modified:
cfe/trunk/test/Driver/cl-pch-search.cpp
cfe/trunk/test/Driver/cl-pch-showincludes.cpp

Modified: cfe/trunk/test/Driver/cl-pch-search.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-pch-search.cpp?rev=323225&r1=323224&r2=323225&view=diff
==
--- cfe/trunk/test/Driver/cl-pch-search.cpp (original)
+++ cfe/trunk/test/Driver/cl-pch-search.cpp Tue Jan 23 09:05:57 2018
@@ -3,4 +3,4 @@
 
 // REQUIRES: x86-registered-target
 // Check that pchfile.h next to to pchfile.cc is found correctly.
-// RUN: %clang_cl -Werror --target=x86_64 /Ycpchfile.h /FIpchfile.h /c 
/Fo%t.obj /Fp%t.pch -- %S/Inputs/pchfile.cpp
+// RUN: %clang_cl -Werror --target=x86_64-windows /Ycpchfile.h /FIpchfile.h /c 
/Fo%t.obj /Fp%t.pch -- %S/Inputs/pchfile.cpp

Modified: cfe/trunk/test/Driver/cl-pch-showincludes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-pch-showincludes.cpp?rev=323225&r1=323224&r2=323225&view=diff
==
--- cfe/trunk/test/Driver/cl-pch-showincludes.cpp (original)
+++ cfe/trunk/test/Driver/cl-pch-showincludes.cpp Tue Jan 23 09:05:57 2018
@@ -8,14 +8,14 @@
 
 // When building the pch, header1.h (included by header2.h), header2.h (the pch
 // input itself) and header3.h (included directly, above) should be printed.
-// RUN: %clang_cl -Werror --target=x86_64 /showIncludes /I%S/Inputs 
/Ycheader2.h /FIheader2.h /Fp%t.pch /c /Fo%t -- %s \
+// RUN: %clang_cl -Werror --target=x86_64-windows /showIncludes /I%S/Inputs 
/Ycheader2.h /FIheader2.h /Fp%t.pch /c /Fo%t -- %s \
 // RUN:   | FileCheck --strict-whitespace -check-prefix=CHECK-YC %s
 // CHECK-YC: Note: including file: {{[^ ]*header2.h}}
 // CHECK-YC: Note: including file:  {{[^ ]*header1.h}}
 // CHECK-YC: Note: including file: {{[^ ]*header3.h}}
 
 // When using the pch, only the direct include is printed.
-// RUN: %clang_cl -Werror --target=x86_64 /showIncludes /I%S/Inputs 
/Yuheader2.h /FIheader2.h /Fp%t.pch /c /Fo%t -- %s \
+// RUN: %clang_cl -Werror --target=x86_64-windows /showIncludes /I%S/Inputs 
/Yuheader2.h /FIheader2.h /Fp%t.pch /c /Fo%t -- %s \
 // RUN:   | FileCheck --strict-whitespace -check-prefix=CHECK-YU %s
 // CHECK-YU-NOT: Note: including file: {{.*pch}}
 // CHECK-YU-NOT: Note: including file: {{.*header1.h}}
@@ -23,7 +23,7 @@
 // CHECK-YU: Note: including file: {{[^ ]*header3.h}}
 
 // When not using pch at all, all the /FI files are printed.
-// RUN: %clang_cl -Werror --target=x86_64 /showIncludes /I%S/Inputs 
/FIheader2.h /c /Fo%t -- %s \
+// RUN: %clang_cl -Werror --target=x86_64-windows /showIncludes /I%S/Inputs 
/FIheader2.h /c /Fo%t -- %s \
 // RUN:   | FileCheck --strict-whitespace -check-prefix=CHECK-FI %s
 // CHECK-FI: Note: including file: {{[^ ]*header2.h}}
 // CHECK-FI: Note: including file:  {{[^ ]*header1.h}}
@@ -32,7 +32,7 @@
 // Also check that /FI arguments before the /Yc / /Yu flags are printed right.
 
 // /FI flags before the /Yc arg should be printed, /FI flags after it 
shouldn't.
-// RUN: %clang_cl -Werror --target=x86_64 /showIncludes /I%S/Inputs 
/Ycheader2.h /FIheader0.h /FIheader2.h /FIheader4.h /Fp%t.pch /c /Fo%t -- %s \
+// RUN: %clang_cl -Werror --target=x86_64-windows /showIncludes /I%S/Inputs 
/Ycheader2.h /FIheader0.h /FIheader2.h /FIheader4.h /Fp%t.pch /c /Fo%t -- %s \
 // RUN:   | FileCheck --strict-whitespace -check-prefix=CHECK-YCFI %s
 // CHECK-YCFI: Note: including file: {{[^ ]*header0.h}}
 // CHECK-YCFI: Note: including file: {{[^ ]*header2.h}}
@@ -40,7 +40,7 @@
 // CHECK-YCFI: Note: including file: {{[^ ]*header4.h}}
 // CHECK-YCFI: Note: including file: {{[^ ]*header3.h}}
 
-// RUN: %clang_cl -Werror --target=x86_64 /showIncludes /I%S/Inputs 
/Yuheader2.h /FIheader0.h /FIheader2.h /FIheader4.h /Fp%t.pch /c /Fo%t -- %s \
+// RUN: %clang_cl -Werror --target=x86_64-windows /showIncludes /I%S/Inputs 
/Yuheader2.h /FIheader0.h /FIheader2.h /FIheader4.h /Fp%t.pch /c /Fo%t -- %s \
 // RUN:   | FileCheck --strict-whitespace -check-prefix=CHECK-YUFI %s
 // CHECK-YUFI-NOT: Note: including file: {{.*pch}}
 // CHECK-YUFI-NOT: Note: including file: {{.*header0.h}}


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


r323226 - clang-format: Support macros in front of @interface / @protocol for ObjC code.

2018-01-23 Thread Nico Weber via cfe-commits
Author: nico
Date: Tue Jan 23 09:10:25 2018
New Revision: 323226

URL: http://llvm.org/viewvc/llvm-project?rev=323226&view=rev
Log:
clang-format: Support macros in front of @interface / @protocol for ObjC code.

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/lib/Format/UnwrappedLineParser.h
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=323226&r1=323225&r2=323226&view=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Tue Jan 23 09:10:25 2018
@@ -943,49 +943,6 @@ void UnwrappedLineParser::parseStructura
 return;
   }
   switch (FormatTok->Tok.getKind()) {
-  case tok::at:
-nextToken();
-if (FormatTok->Tok.is(tok::l_brace)) {
-  nextToken();
-  parseBracedList();
-  break;
-}
-switch (FormatTok->Tok.getObjCKeywordID()) {
-case tok::objc_public:
-case tok::objc_protected:
-case tok::objc_package:
-case tok::objc_private:
-  return parseAccessSpecifier();
-case tok::objc_interface:
-case tok::objc_implementation:
-  return parseObjCInterfaceOrImplementation();
-case tok::objc_protocol:
-  return parseObjCProtocol();
-case tok::objc_end:
-  return; // Handled by the caller.
-case tok::objc_optional:
-case tok::objc_required:
-  nextToken();
-  addUnwrappedLine();
-  return;
-case tok::objc_autoreleasepool:
-  nextToken();
-  if (FormatTok->Tok.is(tok::l_brace)) {
-if (Style.BraceWrapping.AfterObjCDeclaration)
-  addUnwrappedLine();
-parseBlock(/*MustBeDeclaration=*/false);
-  }
-  addUnwrappedLine();
-  return;
-case tok::objc_try:
-  // This branch isn't strictly necessary (the kw_try case below would
-  // do this too after the tok::at is parsed above).  But be explicit.
-  parseTryCatch();
-  return;
-default:
-  break;
-}
-break;
   case tok::kw_asm:
 nextToken();
 if (FormatTok->is(tok::l_brace)) {
@@ -1132,6 +1089,44 @@ void UnwrappedLineParser::parseStructura
   if (FormatTok->Tok.is(tok::l_brace)) {
 nextToken();
 parseBracedList();
+break;
+  }
+  switch (FormatTok->Tok.getObjCKeywordID()) {
+  case tok::objc_public:
+  case tok::objc_protected:
+  case tok::objc_package:
+  case tok::objc_private:
+return parseAccessSpecifier();
+  case tok::objc_interface:
+  case tok::objc_implementation:
+return parseObjCInterfaceOrImplementation();
+  case tok::objc_protocol:
+if (parseObjCProtocol())
+  return;
+break;
+  case tok::objc_end:
+return; // Handled by the caller.
+  case tok::objc_optional:
+  case tok::objc_required:
+nextToken();
+addUnwrappedLine();
+return;
+  case tok::objc_autoreleasepool:
+nextToken();
+if (FormatTok->Tok.is(tok::l_brace)) {
+  if (Style.BraceWrapping.AfterObjCDeclaration)
+addUnwrappedLine();
+  parseBlock(/*MustBeDeclaration=*/false);
+}
+addUnwrappedLine();
+return;
+  case tok::objc_try:
+// This branch isn't strictly necessary (the kw_try case below would
+// do this too after the tok::at is parsed above).  But be explicit.
+parseTryCatch();
+return;
+  default:
+break;
   }
   break;
 case tok::kw_enum:
@@ -2128,6 +2123,8 @@ void UnwrappedLineParser::parseObjCUntil
 }
 
 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
+  assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
+ FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
   nextToken();
   nextToken(); // interface name
 
@@ -2155,8 +2152,21 @@ void UnwrappedLineParser::parseObjCInter
   parseObjCUntilAtEnd();
 }
 
-void UnwrappedLineParser::parseObjCProtocol() {
+// Returns true for the declaration/definition form of @protocol,
+// false for the expression form.
+bool UnwrappedLineParser::parseObjCProtocol() {
+  assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
   nextToken();
+
+  if (FormatTok->is(tok::l_paren))
+// The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
+return false;
+
+  // The definition/declaration form,
+  // @protocol Foo
+  // - (int)someMethod;
+  // @end
+
   nextToken(); // protocol name
 
   if (FormatTok->Tok.is(tok::less))
@@ -2165,11 +2175,13 @@ void UnwrappedLineParser::parseObjCProto
   // Check for protocol declaration.
   if (FormatTok->Tok.is(tok::semi)) {
 nextToken();
-return addUnwrappedLine();
+addUnwrappedLine();
+return true;
   }
 
   addUnwrappedLine();
   parseObjCUntilAtEnd();
+  return

[clang-tools-extra] r323227 - [clang-tidy] Handle bitfields in cppcoreguidelines-pro-type-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via cfe-commits
Author: malcolm.parsons
Date: Tue Jan 23 09:13:57 2018
New Revision: 323227

URL: http://llvm.org/viewvc/llvm-project?rev=323227&view=rev
Log:
[clang-tidy] Handle bitfields in cppcoreguidelines-pro-type-member-init if 
using C++2a

Summary:
C++2a allows bitfields to have default member initializers.
Add support for this to clang-tidy's cppcoreguidelines-pro-type-member-init 
check.

Reviewers: aaron.ballman, alexfh

Reviewed By: aaron.ballman

Subscribers: klimek, nemanjai, xazax.hun, kbarton, cfe-commits

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

Added:

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
Modified:

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp?rev=323227&r1=323226&r2=323227&view=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp 
Tue Jan 23 09:13:57 2018
@@ -404,8 +404,9 @@ void ProTypeMemberInitCheck::checkMissin
   return;
 // Don't suggest fixes for enums because we don't know a good default.
 // Don't suggest fixes for bitfields because in-class initialization is not
-// possible.
-if (F->getType()->isEnumeralType() || F->isBitField())
+// possible until C++2a.
+if (F->getType()->isEnumeralType() ||
+(!getLangOpts().CPlusPlus2a && F->isBitField()))
   return;
 if (!F->getParent()->isUnion() || UnionsSeen.insert(F->getParent()).second)
   FieldsToFix.insert(F);

Added: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp?rev=323227&view=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
 Tue Jan 23 09:13:57 2018
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -- 
-std=c++2a -fno-delayed-template-parsing
+
+struct PositiveBitfieldMember {
+  PositiveBitfieldMember() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these fields: F
+  unsigned F : 5;
+  // CHECK-FIXES: unsigned F : 5{};
+};
+
+struct NegativeUnnamedBitfieldMember {
+  NegativeUnnamedBitfieldMember() {}
+  unsigned : 5;
+};
+
+struct NegativeInitializedBitfieldMembers {
+  NegativeInitializedBitfieldMembers() : F(3) { G = 2; }
+  unsigned F : 5;
+  unsigned G : 5;
+};

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp?rev=323227&r1=323226&r2=323227&view=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
 Tue Jan 23 09:13:57 2018
@@ -474,6 +474,7 @@ struct PositiveBitfieldMember {
   PositiveBitfieldMember() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these fields: F
   unsigned F : 5;
+  // CHECK-FIXES-NOT: unsigned F : 5{};
 };
 
 struct NegativeUnnamedBitfieldMember {


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


[PATCH] D42426: [clang-tidy] Handle bitfields in cppcoreguidelines-pro-type-member-init if using C++2a

2018-01-23 Thread Malcolm Parsons via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323227: [clang-tidy] Handle bitfields in 
cppcoreguidelines-pro-type-member-init if… (authored by malcolm.parsons, 
committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42426?vs=131088&id=131093#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42426

Files:
  clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
  test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
  test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp


Index: clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -404,8 +404,9 @@
   return;
 // Don't suggest fixes for enums because we don't know a good default.
 // Don't suggest fixes for bitfields because in-class initialization is not
-// possible.
-if (F->getType()->isEnumeralType() || F->isBitField())
+// possible until C++2a.
+if (F->getType()->isEnumeralType() ||
+(!getLangOpts().CPlusPlus2a && F->isBitField()))
   return;
 if (!F->getParent()->isUnion() || UnionsSeen.insert(F->getParent()).second)
   FieldsToFix.insert(F);
Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
@@ -474,6 +474,7 @@
   PositiveBitfieldMember() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these fields: F
   unsigned F : 5;
+  // CHECK-FIXES-NOT: unsigned F : 5{};
 };
 
 struct NegativeUnnamedBitfieldMember {
Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -- 
-std=c++2a -fno-delayed-template-parsing
+
+struct PositiveBitfieldMember {
+  PositiveBitfieldMember() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these fields: F
+  unsigned F : 5;
+  // CHECK-FIXES: unsigned F : 5{};
+};
+
+struct NegativeUnnamedBitfieldMember {
+  NegativeUnnamedBitfieldMember() {}
+  unsigned : 5;
+};
+
+struct NegativeInitializedBitfieldMembers {
+  NegativeInitializedBitfieldMembers() : F(3) { G = 2; }
+  unsigned F : 5;
+  unsigned G : 5;
+};


Index: clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -404,8 +404,9 @@
   return;
 // Don't suggest fixes for enums because we don't know a good default.
 // Don't suggest fixes for bitfields because in-class initialization is not
-// possible.
-if (F->getType()->isEnumeralType() || F->isBitField())
+// possible until C++2a.
+if (F->getType()->isEnumeralType() ||
+(!getLangOpts().CPlusPlus2a && F->isBitField()))
   return;
 if (!F->getParent()->isUnion() || UnionsSeen.insert(F->getParent()).second)
   FieldsToFix.insert(F);
Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp
@@ -474,6 +474,7 @@
   PositiveBitfieldMember() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: F
   unsigned F : 5;
+  // CHECK-FIXES-NOT: unsigned F : 5{};
 };
 
 struct NegativeUnnamedBitfieldMember {
Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-type-member-init-cxx2a.cpp
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -- -std=c++2a -fno-delayed-template-parsing
+
+struct PositiveBitfieldMember {
+  PositiveBitfieldMember() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: F
+  unsigned F : 5;
+  // CHECK-FIXES: unsigned F : 5{};
+};
+
+struct NegativeUnnamedBitfieldMember {
+  NegativeUnnamedBitfieldMember() {}
+  unsigned : 5;
+};
+
+struct NegativeInitializedBitfieldMembers {
+  NegativeInitializedBitfieldMembers() : F(3) { G = 2; }
+  unsigned F : 5;
+  unsigned G : 5;
+};
___
cfe-commits mailing li

[PATCH] D42429: [clangd] Moved caching of compile commands to ClangdServer

2018-01-23 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added subscribers: ioeric, jkorous-apple, klimek.

It allows to get rid of CppFile::getLastCommand and simplify the
code in the upcoming threading patch.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42429

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/ClangdUnitStore.h

Index: clangd/ClangdUnitStore.h
===
--- clangd/ClangdUnitStore.h
+++ clangd/ClangdUnitStore.h
@@ -31,8 +31,7 @@
   : ASTCallback(std::move(ASTCallback)) {}
 
   std::shared_ptr
-  getOrCreateFile(PathRef File, PathRef ResourceDir,
-  bool StorePreamblesInMemory,
+  getOrCreateFile(PathRef File, bool StorePreamblesInMemory,
   std::shared_ptr PCHs) {
 std::lock_guard Lock(Mutex);
 auto It = OpenedFiles.find(File);
Index: clangd/ClangdUnit.h
===
--- clangd/ClangdUnit.h
+++ clangd/ClangdUnit.h
@@ -216,14 +216,6 @@
   /// always be non-null.
   std::shared_future> getAST() const;
 
-  /// Get the latest CompileCommand used to build this CppFile. Returns
-  /// llvm::None before first call to rebuild() or after calls to
-  /// cancelRebuild().
-  // In practice we always call rebuild() when adding a CppFile to the
-  // CppFileCollection, and only `cancelRebuild()` after removing it. This means
-  // files in the CppFileCollection always have a compile command available.
-  llvm::Optional getLastCommand() const;
-
 private:
   /// A helper guard that manages the state of CppFile during rebuild.
   class RebuildGuard {
@@ -251,7 +243,6 @@
   bool RebuildInProgress;
   /// Condition variable to indicate changes to RebuildInProgress.
   std::condition_variable RebuildCond;
-  llvm::Optional LastCommand;
 
   /// Promise and future for the latests AST. Fulfilled during rebuild.
   /// We use std::shared_ptr here because MVSC fails to compile non-copyable
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -455,7 +455,6 @@
   this->ASTPromise = std::promise>();
   this->ASTFuture = this->ASTPromise.get_future();
 }
-this->LastCommand = Inputs.CompileCommand;
   } // unlock Mutex.
   // Notify about changes to RebuildCounter.
   RebuildCond.notify_all();
@@ -636,11 +635,6 @@
   return ASTFuture;
 }
 
-llvm::Optional CppFile::getLastCommand() const {
-  std::lock_guard Lock(Mutex);
-  return LastCommand;
-}
-
 CppFile::RebuildGuard::RebuildGuard(CppFile &File,
 unsigned RequestRebuildCounter)
 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
Index: clangd/ClangdServer.h
===
--- clangd/ClangdServer.h
+++ clangd/ClangdServer.h
@@ -331,13 +331,30 @@
   std::future
   scheduleReparseAndDiags(Context Ctx, PathRef File, VersionedDraft Contents,
   std::shared_ptr Resources,
-  Tagged> TaggedFS,
-  bool AllowCachedCompileFlags);
+  Tagged> TaggedFS);
 
   std::future
   scheduleCancelRebuild(Context Ctx, std::shared_ptr Resources);
 
-  GlobalCompilationDatabase &CDB;
+  // Stores compile commands produced by GlobalCompilationDatabase.
+  class CompileArgsCache {
+  public:
+CompileArgsCache(GlobalCompilationDatabase &CDB, Path ResourceDir);
+
+/// Gets compile command for \p File from cache or CDB if it's not in the
+/// cache.
+tooling::CompileCommand getCompileCommand(PathRef File);
+
+/// Removes a cache entry for \p File, if it's present in the cache.
+void invalidate(PathRef File);
+
+  private:
+GlobalCompilationDatabase &CDB;
+const Path ResourceDir;
+llvm::StringMap Cached;
+  };
+
+  CompileArgsCache CompileArgs;
   DiagnosticsConsumer &DiagConsumer;
   FileSystemProvider &FSProvider;
   DraftStore DraftMgr;
@@ -352,7 +369,6 @@
   // If present, a merged view of FileIdx and an external index. Read via Index.
   std::unique_ptr MergedIndex;
   CppFileCollection Units;
-  std::string ResourceDir;
   // If set, this represents the workspace path.
   llvm::Optional RootPath;
   std::shared_ptr PCHs;
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -149,7 +149,9 @@
bool StorePreamblesInMemory,
bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
llvm::Optional ResourceDir)
-: CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
+: CompileArgs(CDB,
+  ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
+  DiagConsumer(Diag

r323228 - Name two bool parameters. No behavior change.

2018-01-23 Thread Nico Weber via cfe-commits
Author: nico
Date: Tue Jan 23 09:29:41 2018
New Revision: 323228

URL: http://llvm.org/viewvc/llvm-project?rev=323228&view=rev
Log:
Name two bool parameters. No behavior change.

Modified:
cfe/trunk/lib/Format/FormatToken.h

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=323228&r1=323227&r2=323228&view=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Tue Jan 23 09:29:41 2018
@@ -441,7 +441,8 @@ struct FormatToken {
   }
 
   prec::Level getPrecedence() const {
-return getBinOpPrecedence(Tok.getKind(), true, true);
+return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
+  /*CPlusPlus11=*/true);
   }
 
   /// \brief Returns the previous token ignoring comments.


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


r323230 - test: simplify the matching logic a bit (NFC)

2018-01-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Jan 23 09:57:04 2018
New Revision: 323230

URL: http://llvm.org/viewvc/llvm-project?rev=323230&view=rev
Log:
test: simplify the matching logic a bit (NFC)

Use CHECK-SAME directives to simplify the test conditions a bit.  This
makes it easier to see what is being checked.  NFC.

Modified:
cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m

Modified: cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m?rev=323230&r1=323229&r2=323230&view=diff
==
--- cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m (original)
+++ cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m Tue Jan 23 
09:57:04 2018
@@ -23,4 +23,15 @@ int main() {
 // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_P0" = weak hidden global
 // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_P0" = weak hidden global
 
-// CHECK: llvm.compiler.used = appending global [10 x i8*] 
{{[^"]*}}OBJC_CLASS_NAME_{{[^"]*}}OBJC_METH_VAR_NAME_{{[^"]*}}OBJC_METH_VAR_TYPE_{{[^"]*}}"\01l_OBJC_$_CLASS_METHODS_A"{{[^"]*}}"\01l_OBJC_CLASS_PROTOCOLS_$_A"{{[^"]*}}OBJC_CLASS_NAME_.1{{[^"]*}}"\01l_OBJC_PROTOCOL_$_P0"{{[^"]*}}"\01l_OBJC_LABEL_PROTOCOL_$_P0"{{[^"]*}}"\01l_OBJC_PROTOCOL_REFERENCE_$_P0"{{[^"]*}}"OBJC_LABEL_CLASS_$"{{[^"]*}}
 section "llvm.metadata"
+// CHECK: llvm.compiler.used = appending global [10 x i8*]
+// CHECK-SAME: OBJC_CLASS_NAME_
+// CHECK-SAME: OBJC_METH_VAR_NAME_
+// CHECK-SAME: OBJC_METH_VAR_TYPE_
+// CHECK-SAME: "\01l_OBJC_$_CLASS_METHODS_A"
+// CHECK-SAME: "\01l_OBJC_CLASS_PROTOCOLS_$_A"
+// CHECK-SAME: OBJC_CLASS_NAME_.1
+// CHECK-SAME: "\01l_OBJC_PROTOCOL_$_P0"
+// CHECK-SAME: "\01l_OBJC_LABEL_PROTOCOL_$_P0"
+// CHECK-SAME: "\01l_OBJC_PROTOCOL_REFERENCE_$_P0"
+// CHECK-SAME: "OBJC_LABEL_CLASS_$"
+// CHECK-SAME: section "llvm.metadata"


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


[PATCH] D42242: Make libc++abi work with gcc's ARM unwind library

2018-01-23 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists updated this revision to Diff 131102.
mclow.lists added a comment.

Find *all* the places that we are using `exception_class` and wrap them in 
helper routines.


https://reviews.llvm.org/D42242

Files:
  src/cxa_default_handlers.cpp
  src/cxa_exception.cpp
  src/cxa_exception.hpp
  src/cxa_handlers.cpp
  src/cxa_personality.cpp

Index: src/cxa_personality.cpp
===
--- src/cxa_personality.cpp
+++ src/cxa_personality.cpp
@@ -492,7 +492,7 @@
 // Even for foreign exceptions, the exception object is *probably* at unwind_exception + 1
 //Regardless, this library is prohibited from touching a foreign exception
 void* adjustedPtr = unwind_exception + 1;
-if (unwind_exception->exception_class == kOurDependentExceptionClass)
+if (__getExceptionClass(unwind_exception) == kOurDependentExceptionClass)
 adjustedPtr = ((__cxa_dependent_exception*)adjustedPtr - 1)->primaryException;
 return adjustedPtr;
 }
@@ -1073,8 +1073,7 @@
 if (unwind_exception == 0 || context == 0)
 return _URC_FATAL_PHASE1_ERROR;
 
-bool native_exception = (unwind_exception->exception_class & get_vendor_and_language) ==
-(kOurExceptionClass & get_vendor_and_language);
+bool native_exception = __isOurExceptionClass(unwind_exception);
 
 #if !defined(LIBCXXABI_USE_LLVM_UNWINDER)
 // Copy the address of _Unwind_Control_Block to r12 so that
@@ -1178,9 +1177,7 @@
 if (unwind_exception == 0)
 call_terminate(false, unwind_exception);
 __cxa_begin_catch(unwind_exception);
-bool native_old_exception =
-(unwind_exception->exception_class & get_vendor_and_language) ==
-(kOurExceptionClass& get_vendor_and_language);
+bool native_old_exception = __isOurExceptionClass(unwind_exception);
 std::unexpected_handler u_handler;
 std::terminate_handler t_handler;
 __cxa_exception* old_exception_header = 0;
@@ -1242,9 +1239,7 @@
 if (new_exception_header == 0)
 // This shouldn't be able to happen!
 std::__terminate(t_handler);
-bool native_new_exception =
-(new_exception_header->unwindHeader.exception_class & get_vendor_and_language) ==
-(kOurExceptionClass & get_vendor_and_language);
+bool native_new_exception = __isOurExceptionClass(&new_exception_header->unwindHeader);
 void* adjustedPtr;
 if (native_new_exception && (new_exception_header != old_exception_header))
 {
@@ -1251,7 +1246,7 @@
 const __shim_type_info* excpType =
 static_cast(new_exception_header->exceptionType);
 adjustedPtr =
-new_exception_header->unwindHeader.exception_class == kOurDependentExceptionClass ?
+__getExceptionClass(&new_exception_header->unwindHeader) == kOurDependentExceptionClass ?
 ((__cxa_dependent_exception*)new_exception_header)->primaryException :
 new_exception_header + 1;
 if (!exception_spec_can_catch(ttypeIndex, classInfo, ttypeEncoding,
Index: src/cxa_handlers.cpp
===
--- src/cxa_handlers.cpp
+++ src/cxa_handlers.cpp
@@ -89,10 +89,7 @@
 {
 _Unwind_Exception* unwind_exception =
 reinterpret_cast<_Unwind_Exception*>(exception_header + 1) - 1;
-bool native_exception =
-(unwind_exception->exception_class & get_vendor_and_language) ==
-   (kOurExceptionClass & get_vendor_and_language);
-if (native_exception)
+if (__isOurExceptionClass(unwind_exception))
 __terminate(exception_header->terminateHandler);
 }
 }
Index: src/cxa_exception.hpp
===
--- src/cxa_exception.hpp
+++ src/cxa_exception.hpp
@@ -24,6 +24,10 @@
 static const uint64_t kOurDependentExceptionClass = 0x434C4E47432B2B01; // CLNGC++\1
 static const uint64_t get_vendor_and_language = 0xFF00; // mask for CLNGC++
 
+uint64_t __getExceptionClass  (const _Unwind_Exception*);
+void __setExceptionClass  (  _Unwind_Exception*, uint64_t);
+bool __isOurExceptionClass(const _Unwind_Exception*);
+
 struct _LIBCXXABI_HIDDEN __cxa_exception {
 #if defined(__LP64__) || defined(_LIBCXXABI_ARM_EHABI)
 // This is a new field to support C++ 0x exception_ptr.
Index: src/cxa_exception.cpp
===
--- src/cxa_exception.cpp
+++ src/cxa_exception.cpp
@@ -78,22 +78,37 @@
alignof(__cxa_exception));
 }
 
-static void setExceptionClass(_Unwind_Exception* unwind_exception) {
-unwind_exception->exception_class 

r323232 - [OPENMP] Remove more empty SourceLocations() from the code.

2018-01-23 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Jan 23 10:12:38 2018
New Revision: 323232

URL: http://llvm.org/viewvc/llvm-project?rev=323232&view=rev
Log:
[OPENMP] Remove more empty SourceLocations() from the code.

Removed more empty SourceLocations() from the OpenMP code and replaced
with the correct locations for better debug info emission.

Modified:
cfe/trunk/include/clang/AST/DeclOpenMP.h
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/flush_codegen.cpp
cfe/trunk/test/OpenMP/for_simd_codegen.cpp
cfe/trunk/test/OpenMP/parallel_for_simd_codegen.cpp
cfe/trunk/test/OpenMP/simd_codegen.cpp

Modified: cfe/trunk/include/clang/AST/DeclOpenMP.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclOpenMP.h?rev=323232&r1=323231&r2=323232&view=diff
==
--- cfe/trunk/include/clang/AST/DeclOpenMP.h (original)
+++ cfe/trunk/include/clang/AST/DeclOpenMP.h Tue Jan 23 10:12:38 2018
@@ -190,8 +190,8 @@ class OMPCapturedExprDecl final : public
 
   OMPCapturedExprDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
   QualType Type, SourceLocation StartLoc)
-  : VarDecl(OMPCapturedExpr, C, DC, StartLoc, SourceLocation(), Id, Type,
-nullptr, SC_None) {
+  : VarDecl(OMPCapturedExpr, C, DC, StartLoc, StartLoc, Id, Type, nullptr,
+SC_None) {
 setImplicit();
   }
 

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp?rev=323232&r1=323231&r2=323232&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp Tue Jan 23 10:12:38 2018
@@ -147,7 +147,7 @@ public:
 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
 CGF.GetAddrOfLocalVar(PartIDVar),
 PartIDVar->getType()->castAs());
-auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
+auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
 CGF.EmitBlock(DoneBB);
@@ -354,7 +354,7 @@ public:
   DeclRefExpr DRE(const_cast(VD),
   /*RefersToEnclosingVariableOrCapture=*/false,
   VD->getType().getNonReferenceType(), VK_LValue,
-  SourceLocation());
+  C.getLocation());
   PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
 return CGF.EmitLValue(&DRE).getAddress();
   });
@@ -787,17 +787,17 @@ static void emitInitWithReductionInitial
 RValue InitRVal;
 switch (CGF.getEvaluationKind(Ty)) {
 case TEK_Scalar:
-  InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
+  InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
   break;
 case TEK_Complex:
   InitRVal =
-  RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
+  RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
   break;
 case TEK_Aggregate:
   InitRVal = RValue::getAggregate(LV.getAddress());
   break;
 }
-OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
+OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
  /*IsInitializer=*/false);
@@ -4836,7 +4836,7 @@ void CGOpenMPRuntime::emitTaskLoopCall(C
   IfVal,
   LBLVal.getPointer(),
   UBLVal.getPointer(),
-  CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
+  CGF.EmitLoadOfScalar(StLVal, Loc),
   llvm::ConstantInt::getNullValue(
   CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
   llvm::ConstantInt::getSigned(
@@ -5399,9 +5399,8 @@ static llvm::Value *emitReduceInitFuncti
 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
 CGF, CGM.getContext().getSizeType(),
 generateUniqueName("reduction_size", Loc, N));
-Size =
-CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
- CGM.getContext().getSizeType(), SourceLocation());
+Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
+CGM.getContext().getSizeType(), Loc);
   }
   RCG.emitAggregateType(CGF, N, Size);
   LValue SharedLVal;
@@ -5469,9 +5468,8 @@ static llvm::Value *emitReduceCombFuncti
 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
 CGF, CGM.getContext().getSizeType(),
 generateUniqueName("reduction_size", Loc

r323231 - test/Driver: Add some --stdlib=platform, NFC.

2018-01-23 Thread Jonas Hahnfeld via cfe-commits
Author: hahnfeld
Date: Tue Jan 23 10:12:12 2018
New Revision: 323231

URL: http://llvm.org/viewvc/llvm-project?rev=323231&view=rev
Log:
test/Driver: Add some --stdlib=platform, NFC.

This fixes the failing test when building with CLANG_DEFAULT_CXX_STDLIB.

Modified:
cfe/trunk/test/Driver/solaris-header-search.cpp

Modified: cfe/trunk/test/Driver/solaris-header-search.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/solaris-header-search.cpp?rev=323231&r1=323230&r2=323231&view=diff
==
--- cfe/trunk/test/Driver/solaris-header-search.cpp (original)
+++ cfe/trunk/test/Driver/solaris-header-search.cpp Tue Jan 23 10:12:12 2018
@@ -2,7 +2,7 @@
 //
 // Sparc, 32bit
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
-// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --target=sparc-sun-solaris2.11 --stdlib=platform \
 // RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
 // RUN:   | FileCheck --check-prefix=CHECK_SOLARIS_SPARC %s
 // CHECK_SOLARIS_SPARC: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
@@ -12,7 +12,7 @@
 
 // Sparc, 64bit
 // RUN: %clang -no-canonical-prefixes -m64 %s -### -fsyntax-only 2>&1 \
-// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --target=sparc-sun-solaris2.11 --stdlib=platform \
 // RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
 // RUN:   | FileCheck --check-prefix=CHECK_SOLARIS_SPARC64 %s
 // CHECK_SOLARIS_SPARC64: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
@@ -22,7 +22,7 @@
 
 // Intel, 32bit
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
-// RUN: --target=i386-pc-solaris2.11 \
+// RUN: --target=i386-pc-solaris2.11 --stdlib=platform \
 // RUN: --sysroot=%S/Inputs/solaris_x86_tree \
 // RUN:   | FileCheck --check-prefix=CHECK_SOLARIS_X86 %s
 // CHECK_SOLARIS_X86: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
@@ -32,7 +32,7 @@
 
 // Intel, 64bit
 // RUN: %clang -no-canonical-prefixes -m64 %s -### -fsyntax-only 2>&1 \
-// RUN: --target=i386-pc-solaris2.11 \
+// RUN: --target=i386-pc-solaris2.11 --stdlib=platform \
 // RUN: --sysroot=%S/Inputs/solaris_x86_tree \
 // RUN:   | FileCheck --check-prefix=CHECK_SOLARIS_X64 %s
 // CHECK_SOLARIS_X64: "{{[^"]*}}clang{{[^"]*}}" "-cc1"


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


[PATCH] D42174: [clangd] Refactored threading in ClangdServer

2018-01-23 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 131105.
ilya-biryukov marked 4 inline comments as done.
ilya-biryukov added a comment.

- Renamed SimpleThreadPool to ThreadPool
- Removed PCHs from Scheduler's constructor
- Renamed waitFor(AST|Preamble)Action to blocking(AST|Preamble)Read
- Updates
- Remove getLastCommand from Scheduler's interface, pass Inputs to actions 
instead


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42174

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.h

Index: clangd/ClangdUnitStore.h
===
--- clangd/ClangdUnitStore.h
+++ clangd/ClangdUnitStore.h
@@ -27,26 +27,26 @@
 public:
   /// \p ASTCallback is called when a file is parsed synchronously. This should
   /// not be expensive since it blocks diagnostics.
-  explicit CppFileCollection(ASTParsedCallback ASTCallback)
-  : ASTCallback(std::move(ASTCallback)) {}
+  explicit CppFileCollection(bool StorePreamblesInMemory,
+ std::shared_ptr PCHs,
+ ASTParsedCallback ASTCallback)
+  : ASTCallback(std::move(ASTCallback)), PCHs(std::move(PCHs)),
+StorePreamblesInMemory(StorePreamblesInMemory) {}
 
-  std::shared_ptr
-  getOrCreateFile(PathRef File, bool StorePreamblesInMemory,
-  std::shared_ptr PCHs) {
+  std::shared_ptr getOrCreateFile(PathRef File) {
 std::lock_guard Lock(Mutex);
 auto It = OpenedFiles.find(File);
 if (It == OpenedFiles.end()) {
   It = OpenedFiles
.try_emplace(File, CppFile::Create(File, StorePreamblesInMemory,
-  std::move(PCHs), ASTCallback))
+  PCHs, ASTCallback))
.first;
 }
 return It->second;
   }
 
-  std::shared_ptr getFile(PathRef File) {
+  std::shared_ptr getFile(PathRef File) const {
 std::lock_guard Lock(Mutex);
-
 auto It = OpenedFiles.find(File);
 if (It == OpenedFiles.end())
   return nullptr;
@@ -58,9 +58,11 @@
   std::shared_ptr removeIfPresent(PathRef File);
 
 private:
-  std::mutex Mutex;
+  mutable std::mutex Mutex;
   llvm::StringMap> OpenedFiles;
   ASTParsedCallback ASTCallback;
+  std::shared_ptr PCHs;
+  bool StorePreamblesInMemory;
 };
 } // namespace clangd
 } // namespace clang
Index: clangd/ClangdServer.h
===
--- clangd/ClangdServer.h
+++ clangd/ClangdServer.h
@@ -98,21 +98,20 @@
 
 class ClangdServer;
 
-/// Returns a number of a default async threads to use for ClangdScheduler.
+/// Returns a number of a default async threads to use for Scheduler.
 /// Returned value is always >= 1 (i.e. will not cause requests to be processed
 /// synchronously).
 unsigned getDefaultAsyncThreadsCount();
 
-/// Handles running WorkerRequests of ClangdServer on a number of worker
-/// threads.
-class ClangdScheduler {
+/// A simple fixed-size thread pool implementation.
+class ThreadPool {
 public:
   /// If \p AsyncThreadsCount is 0, requests added using addToFront and addToEnd
   /// will be processed synchronously on the calling thread.
   // Otherwise, \p AsyncThreadsCount threads will be created to schedule the
   // requests.
-  ClangdScheduler(unsigned AsyncThreadsCount);
-  ~ClangdScheduler();
+  ThreadPool(unsigned AsyncThreadsCount);
+  ~ThreadPool();
 
   /// Add a new request to run function \p F with args \p As to the start of the
   /// queue. The request will be run on a separate thread.
@@ -149,20 +148,77 @@
 
 private:
   bool RunSynchronously;
-  std::mutex Mutex;
+  mutable std::mutex Mutex;
   /// We run some tasks on separate threads(parsing, CppFile cleanup).
   /// These threads looks into RequestQueue to find requests to handle and
   /// terminate when Done is set to true.
   std::vector Workers;
   /// Setting Done to true will make the worker threads terminate.
   bool Done = false;
-  /// A queue of requests. Elements of this vector are async computations (i.e.
-  /// results of calling std::async(std::launch::deferred, ...)).
+  /// A queue of requests.
   std::deque> RequestQueue;
   /// Condition variable to wake up worker threads.
   std::condition_variable RequestCV;
 };
 
+
+struct InputsAndAST {
+  const ParseInputs &Inputs;
+  ParsedAST &AST;
+};
+
+struct InputsAndPreamble {
+  const ParseInputs &Inputs;
+  const PreambleData* Preamble;
+};
+
+/// Handles running tasks for ClangdServer and managing the resources (e.g.,
+/// preambles and ASTs) for opened files.
+class Scheduler {
+public:
+  Scheduler(unsigned AsyncThreadsCount, bool StorePreamblesInMemory,
+ASTParsedCallback ASTCallback);
+
+  /// Schedule an update for \p File. Adds \p File to a list of tracked files if
+  /// \p File was not part of it before.
+  void scheduleUpdate(
+  Context Ctx, PathRef File, ParseInputs Inputs,
+  UniqueFunction>)>
+  OnUp

r323235 - [Docs] Re-generate command line documentation.

2018-01-23 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Tue Jan 23 10:40:15 2018
New Revision: 323235

URL: http://llvm.org/viewvc/llvm-project?rev=323235&view=rev
Log:
[Docs] Re-generate command line documentation.

Modified:
cfe/trunk/docs/ClangCommandLineReference.rst

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=323235&r1=323234&r2=323235&view=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Tue Jan 23 10:40:15 2018
@@ -116,6 +116,10 @@ Output path for the plist report
 .. option:: -bundle\_loader 
 .. program:: clang
 
+.. option:: -cfguard
+
+Emit tables required for Windows Control Flow Guard.
+
 .. option:: -client\_name
 
 .. option:: -compatibility\_version
@@ -1179,6 +1183,10 @@ Load the clang builtins module map file.
 
 .. option:: -fcaret-diagnostics, -fno-caret-diagnostics
 
+.. option:: -fcf-protection=, -fcf-protection (equivalent to 
-fcf-protection=full)
+
+Instrument control-flow architecture protection. Options: return, branch, 
full, none.
+
 .. option:: -fclasspath=, --CLASSPATH , --CLASSPATH=, 
--classpath , --classpath=
 
 .. option:: -fcolor-diagnostics, -fno-color-diagnostics
@@ -1756,6 +1764,10 @@ Force the usage of stack protectors for
 
 Use a strong heuristic to apply stack protectors to functions
 
+.. option:: -fstack-size-section, -fno-stack-size-section
+
+Emit section containing metadata on function stack sizes
+
 .. option:: -fstandalone-debug, -fno-limit-debug-info, -fno-standalone-debug
 
 Emit full debug info for all types used by the program
@@ -2412,10 +2424,16 @@ X86
 
 .. option:: -mprfchw, -mno-prfchw
 
+.. option:: -mrdpid, -mno-rdpid
+
 .. option:: -mrdrnd, -mno-rdrnd
 
 .. option:: -mrdseed, -mno-rdseed
 
+.. option:: -mretpoline, -mno-retpoline
+
+.. option:: -mretpoline-external-thunk, -mno-retpoline-external-thunk
+
 .. option:: -mrtm, -mno-rtm
 
 .. option:: -msgx, -mno-sgx


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


[PATCH] D42174: [clangd] Refactored threading in ClangdServer

2018-01-23 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdServer.cpp:222
+  }
+  // We currently do all the reads of the AST on a running thread to avoid
+  // inconsistent states coming from subsequent updates.

sammccall wrote:
> Having trouble with this one.
> is this the same as "We currently block the calling thread until the AST is 
> available, to avoid..."?
Yes. Used your wording, thanks.



Comment at: clangd/ClangdServer.h:169
+  Scheduler(unsigned AsyncThreadsCount, bool StorePreamblesInMemory,
+std::shared_ptr PCHs,
+ASTParsedCallback ASTCallback);

sammccall wrote:
> this is a performance optimization, right?
> I think the scheduler does enough of the compiling that giving it one of its 
> own isn't too wasteful.
It is probably redundant, yes. Removed it.



Comment at: clangd/ClangdServer.h:173
+  /// Get the CompileCommand passed at the last scheduleUpdate call for \p 
File.
+  llvm::Optional getLatestCommand(PathRef File) const;
+

sammccall wrote:
> This seems like a smell - the command is sometimes an input from callsites 
> that want builds, and sometimes an output to callsites that want builds. Also 
> this class is all about threading, scheduling, and versions, and this method 
> bypasses all of that.
> 
> (If this is a hack to keep code complete working while we refactor, that's 
> fine - but the docs should say that and we should know what next steps look 
> like!)
> 
> ISTM the issue here is coupling updates to the source with updates to the 
> compile command.
> Ultimately we should indeed be compiling a given version with a fixed CC, but 
> that doesn't seem like the clearest interface for callers.
> 
> One option is:
>   - Scheduler has a reference to the CDB (or a std::function wrapping it), 
> and needs to come up with commands itself
>   - it caches commands whenever it can, and has an "invalidateCommand(Path)" 
> to drop its cache. `with_file_lock { invalidateCommand(), scheduleUpdate() }` 
> is the equivalent to `forceRebuild`.
>  - it provides a `scheduleSourceRead` which is like scheduleASTRead but 
> provides source, compile command, and the latest preamble available without 
> blocking. This would be used for operations like codecomplete that can't use 
> scheduleASTRead.
I've opted for passing action inputs to the read methods, as discussed offline. 
The implementation turned out to be ugly, we now store a separate 
`StringMap` in `Scheduler` to keep track of the latest inputs and 
not put that into `CppFile`.



Comment at: clangd/ClangdServer.h:184
+  /// resources. \p Action will be called when resources are freed.
+  /// If an error occurs during processing, it is forwarded to the \p Action
+  /// callback.

sammccall wrote:
> The callback here is a bit confusing and YAGNI (both clangd and our known 
> embedders discard the returned future).
> It seems enough to return synchronously and know that subsequent reads that 
> ask for = or >= version are going to get nothing back.
I'm fine with removing the callback, but I'd like this change to focus on 
internals of `ClangdServer` without changing its interface, happy to remove the 
callback afterwards.
Added a FIXME for that.



Comment at: clangd/ClangdServer.h:200
+  /// callback.
+  void schedulePreambleRead(
+  PathRef File,

sammccall wrote:
> can we pass in a consistency policy here? even if we only support a subset of 
> {ast, preamble} x policy for now, a richer API would enable 
> experiments/tradeoffs later. e.g.
> 
>   enum class VersionConstraint {
> ANY, // returns the first data that's available, typically immediately
> EQUAL, // returns the data for the previous update
> GREATER_EQUAL, // Returns the data for the previous update, or some 
> subsequent update.
>   }
> 
> (I guess the semantics you've described for AST read are EQUAL, and ANY for 
> preamble read)
I would rather not extend the API beyond what it can do at the moment, but 
happy to explore this approach after threading gets rid of the legacy stuff 
that we have now.



Comment at: clangd/ClangdServer.h:206
+  CppFileCollection Units;
+  SimpleThreadPool Executor;
+};

sammccall wrote:
> these two names seem a bit confusing - might be easier as just CppFiles, 
> Threads?
> 
> The names seem to be ~synonyms for the types, which I don't think is better 
> than echoing the types. (Often there's a completely separate good name, but I 
> don't think so here)
- I'd go with `Files` instead of `CppFiles`. WDYT?
- `Executor` sounds better to me than `Threads`. Could you elaborate why you 
find it confusing?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42174



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

[PATCH] D42357: Under limitation of allocated buffer, inplace_merge() does NOT take usage of partial allocated buffer but applies native rotate directly.

2018-01-23 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists added inline comments.



Comment at: include/algorithm:2515
+{
+pointer __buff_end = __move(__first, __middle,  __buff);
+__move(__middle, __last, __first);

mclow.lists wrote:
> Probably a good idea to qualify these calls with `_VSTD::` to ensure that no 
> inadvertent ADL happens.
I think that you should run some tests with types that aren't `int`.

 You don't know what the state of the buffer is here; how much of it is actual 
objects, and how much of it is just raw memory.   For raw memory, `__move` is 
the wrong call, because it will attempt to "clean up" the objects that are 
already there.



Repository:
  rCXX libc++

https://reviews.llvm.org/D42357



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


r323236 - [OPENMP] Replace call of EmitLoadOfLValue() by EmitLoadOfScalar(), NFC.

2018-01-23 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Jan 23 10:44:14 2018
New Revision: 323236

URL: http://llvm.org/viewvc/llvm-project?rev=323236&view=rev
Log:
[OPENMP] Replace call of EmitLoadOfLValue() by EmitLoadOfScalar(), NFC.

Replace calls of EmitLoadOfLValue() by EmitLoadOfScalar() functions if
it is known that the value is scalar.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp?rev=323236&r1=323235&r2=323236&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp Tue Jan 23 10:44:14 2018
@@ -1499,7 +1499,7 @@ llvm::Value *CGOpenMPRuntime::getThreadI
   if (OMPRegionInfo->getThreadIDVariable()) {
 // Check if this an outlined function with thread id passed as 
argument.
 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
-ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
+ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
 // If value loaded in entry block, cache it and use it everywhere in
 // function.
 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
@@ -3979,7 +3979,7 @@ emitProxyTaskFunction(CodeGenModule &CGM
   auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
   auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
   auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
-  CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
+  CGF.EmitLoadOfScalar(SharedsLVal, Loc),
   CGF.ConvertTypeForMem(SharedsPtrTy));
 
   auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
@@ -4002,19 +4002,19 @@ emitProxyTaskFunction(CodeGenModule &CGM
   if (isOpenMPTaskLoopDirective(Kind)) {
 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
-auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
+auto *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
-auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
+auto *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
-auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
+auto *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
-auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
+auto *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
-auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
+auto *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
 CallArgs.push_back(LBParam);
 CallArgs.push_back(UBParam);
 CallArgs.push_back(StParam);
@@ -6714,10 +6714,8 @@ public:
 // We didn't find any match in our map information - generate a zero
 // size array section.
 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
-llvm::Value *Ptr =
-this->CGF
-.EmitLoadOfLValue(this->CGF.EmitLValue(IE), IE->getExprLoc())
-.getScalarVal();
+llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
+  IE->getExprLoc());
 BasePointers.push_back({Ptr, VD});
 Pointers.push_back(Ptr);
 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));

Modified: cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp?rev=323236&r1=323235&r2=323236&view=diff
==
--- cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp Tue Jan 23 10:44:14 2018
@@ -265,8 +265,7 @@ void CodeGenFunction::GenerateOpenMPCapt
 } else if (CurCap->capturesThis())
   CapturedVars.push_back(CXXThisValue);
 else if (CurCap->capturesVariableByCopy()) {
-  llvm::Value *CV =
-  EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
+  llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), 
CurCap->getLocation());
 
   // If the field is not a pointer, we need to save the actual value
   // and load it as a void pointer.
@@ -287,7 +286,7 @@ void CodeGenFunction::GenerateOpenMPCapt
 

[PATCH] D42276: [Driver] Add an -fexperimental-isel driver option to enable/disable GlobalISel

2018-01-23 Thread Quentin Colombet via Phabricator via cfe-commits
qcolombet added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:4699
+else
+  CmdArgs.push_back("-global-isel=0");
+  }

aemerson wrote:
> qcolombet wrote:
> > qcolombet wrote:
> > > I think that it would be useful to also set -global-isel-abort=2, so that 
> > > users can report problem early.
> > > 
> > > What do you think?
> > > 
> > > 
> > Should we have some kind of "target validation"?
> > What I'd like to avoid is people trying the new allocator on unsupported 
> > target (as in the GISel base classes are not present) that would just crash 
> > the compiler.
> > 
> > Alternatively, we could fix the backend to fallback gracefully/abort 
> > properly in those situation.
> > Right now I believe we would get a segfault on RegisterBankInfo or 
> > something along those lines.
> > I think that it would be useful to also set -global-isel-abort=2, so that 
> > users can report problem early.
> > 
> > What do you think?
> 
> Yes that makes sense, although should we ignore it for ARM64 O0 since we will 
> officially support it?
> 
> > 
> > Should we have some kind of "target validation"?
> > What I'd like to avoid is people trying the new allocator on unsupported 
> > target (as in the GISel base classes are not present) that would just crash 
> > the compiler.
> 
> Perhaps a warning like "GlobalISel support is incomplete for [target]"? I 
> don't know the GISel status for other targets.
> 
> 
> Yes that makes sense, although should we ignore it for ARM64 O0 since we will 
> officially support it?

Sounds sensible. We can advertise the remark option if people want to know what 
is going on.


Repository:
  rC Clang

https://reviews.llvm.org/D42276



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


[libcxx] r323237 - libcxx: Rename vasprintf function to __libcpp_vasprintf.

2018-01-23 Thread Peter Collingbourne via cfe-commits
Author: pcc
Date: Tue Jan 23 10:53:33 2018
New Revision: 323237

URL: http://llvm.org/viewvc/llvm-project?rev=323237&view=rev
Log:
libcxx: Rename vasprintf function to __libcpp_vasprintf.

The language standard does not define a function with this name,
so it is part of the user's namespace. This change fixes a duplicate
symbol error that occurs when a user attempts to define a function
with this name.

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

Modified:
libcxx/trunk/include/stdio.h
libcxx/trunk/src/support/win32/locale_win32.cpp
libcxx/trunk/src/support/win32/support.cpp

Modified: libcxx/trunk/include/stdio.h
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/stdio.h?rev=323237&r1=323236&r2=323237&view=diff
==
--- libcxx/trunk/include/stdio.h (original)
+++ libcxx/trunk/include/stdio.h Tue Jan 23 10:53:33 2018
@@ -109,13 +109,6 @@ void perror(const char* s);
 
 #ifdef __cplusplus
 
-// snprintf
-#if defined(_LIBCPP_MSVCRT_LIKE)
-extern "C" {
-int vasprintf(char **sptr, const char *__restrict fmt, va_list ap);
-}
-#endif
-
 #undef getc
 #undef putc
 #undef clearerr

Modified: libcxx/trunk/src/support/win32/locale_win32.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/support/win32/locale_win32.cpp?rev=323237&r1=323236&r2=323237&view=diff
==
--- libcxx/trunk/src/support/win32/locale_win32.cpp (original)
+++ libcxx/trunk/src/support/win32/locale_win32.cpp Tue Jan 23 10:53:33 2018
@@ -13,6 +13,8 @@
 #include 
 #include 
 
+int __libcpp_vasprintf(char **sptr, const char *__restrict fmt, va_list ap);
+
 using std::__libcpp_locale_guard;
 
 // FIXME: base currently unused. Needs manual work to construct the new locale
@@ -105,7 +107,7 @@ int asprintf_l( char **ret, locale_t loc
 int vasprintf_l( char **ret, locale_t loc, const char *format, va_list ap )
 {
 __libcpp_locale_guard __current(loc);
-return vasprintf( ret, format, ap );
+return __libcpp_vasprintf( ret, format, ap );
 }
 
 #if !defined(_LIBCPP_MSVCRT)

Modified: libcxx/trunk/src/support/win32/support.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/support/win32/support.cpp?rev=323237&r1=323236&r2=323237&view=diff
==
--- libcxx/trunk/src/support/win32/support.cpp (original)
+++ libcxx/trunk/src/support/win32/support.cpp Tue Jan 23 10:53:33 2018
@@ -19,7 +19,7 @@
 // Like sprintf, but when return value >= 0 it returns
 // a pointer to a malloc'd string in *sptr.
 // If return >= 0, use free to delete *sptr.
-int vasprintf( char **sptr, const char *__restrict format, va_list ap )
+int __libcpp_vasprintf( char **sptr, const char *__restrict format, va_list ap 
)
 {
 *sptr = NULL;
 // Query the count required.


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


[PATCH] D42174: [clangd] Refactored threading in ClangdServer

2018-01-23 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdServer.h:164
 
+/// Handles running tasks for ClangdServer and managing the resources (e.g.,
+/// preambles and ASTs) for opened files.

sammccall wrote:
> This is a nice abstraction, so much better than dealing with Cppfile! A 
> couple of observations:
> 
> 1) all methods refer to a single file, neither the contracts nor the 
> implementation have any interactions between files. An API that reflects this 
> seems more natural. e.g. it naturally provides operations like "are we 
> tracking this file", and makes it natural to be able to e.g. lock at the 
> per-file level. e.g.
> 
>   class WorkingSet {
>  shared_ptr get(Path);
>  shared_ptr getOrCreate(Path)
>}
>class TranslationUnit {
>  void update(ParseInputs);
>  void read(Callback);
>}
> 
> This seems like it would make it easier to explain what the semantics of 
> scheduleRemove are, too.
> 
> 2) The callbacks from individual methods seem more powerful than needed, and 
> encourage deeper coupling. Basically, the inputs (changes) and outputs 
> (diagnostics, reads) don't seem to want to interact with the same code. This 
> suggests decoupling them: the changes are a sequence of input events, 
> diagnostics are a sequence of output events, reads look much as they do now.
> 
> One benefit here is that the versioning relationship between inputs and 
> outputs no longer show up in the function signatures (by coupling an input to 
> a matching output). Expressing them as data makes it easier to tweak them.
> 
> 3) It's not spelled out how this interacts with drafts: whether 
> text<->version is maintained here or externally, and what the contracts 
> around versions are. There are no options offered, so I would guess that 
> scheduleUpdate delivers new-version-or-nothing, and scheduleASTRead 
> delivers... current-or-newer? current-or-nothing?
> 
> I think it would *probably* be clearer to have versions minted by the 
> external DraftStore, that way we can decouple "we know about the contents of 
> this file" from "we're building this file". e.g. we probably want wildly 
> different policies for discarding resources of old versions, when "resources" 
> = source code vs "resources" = ASTs and preambles.
> 
> 4) Scheduler (or anything it decomposes into) is important and isolated 
> enough that it deserves its own header.
1. Given the nature of the LSP, the users of the interface will probably always 
call only a single function of `TranslationUnit`, so we won't win much in terms 
of the code clarity.
```
scheduleUpdate(File, Inputs) --> get(File).update(Inputs)
```
That adds some complexity to the interface, though. I'd opt for not doing that 
in the initial version.

2. One place where I find these callbacks useful are tests where we could wait 
for latest `addDocument` to complete. A more pressing concern is that the 
interface of `ClangdServer` does not allow to remove the callbacks 
(`addDocument` returns a future) and I would really love to keep the public 
interface of `ClangdServer` the same for the first iteration.

3. I would err on the side of saying that `scheduleASTRead` delivers current 
version. This gives correct results for the current callers of the interface. 
If we do current-or-newer I'd start with adding the versions to the interface, 
so that the callers of the API would have enough context to know whether the 
results correspond to the latest version or not. I'd really love to keep 
version out of the initial patch, happy to chat about them for follow-up 
patches.

4.  Totally agree. I planned to move it into a separate header after the 
changes land. Happy to do that with a follow-up patch.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42174



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


r323239 - [CUDA] CUDA has no device-side library builtins.

2018-01-23 Thread Artem Belevich via cfe-commits
Author: tra
Date: Tue Jan 23 11:08:18 2018
New Revision: 323239

URL: http://llvm.org/viewvc/llvm-project?rev=323239&view=rev
Log:
[CUDA] CUDA has no device-side library builtins.

We should (almost) never consider a device-side declaration to match a
library builtin functio.  Otherwise clang may ignore the implementation
provided by the CUDA headers and emit clang's idea of the builtin.

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

Added:
cfe/trunk/test/CodeGenCUDA/library-builtin.cu
Modified:
cfe/trunk/lib/AST/Decl.cpp

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=323239&r1=323238&r2=323239&view=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Tue Jan 23 11:08:18 2018
@@ -2901,6 +2901,13 @@ unsigned FunctionDecl::getBuiltinID() co
   Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
 return 0;
 
+  // CUDA does not have device-side standard library. printf and malloc are the
+  // only special cases that are supported by device-side runtime.
+  if (Context.getLangOpts().CUDA && hasAttr() &&
+  !hasAttr() &&
+  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
+return 0;
+
   return BuiltinID;
 }
 

Added: cfe/trunk/test/CodeGenCUDA/library-builtin.cu
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCUDA/library-builtin.cu?rev=323239&view=auto
==
--- cfe/trunk/test/CodeGenCUDA/library-builtin.cu (added)
+++ cfe/trunk/test/CodeGenCUDA/library-builtin.cu Tue Jan 23 11:08:18 2018
@@ -0,0 +1,22 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | \
+// RUN:  FileCheck --check-prefixes=HOST,BOTH %s
+// RUN: %clang_cc1 -fcuda-is-device -triple nvptx64-nvidia-cuda \
+// RUN:   -emit-llvm -o - %s | FileCheck %s --check-prefixes=DEVICE,BOTH
+
+// BOTH-LABEL: define float @logf(float
+
+// logf() should be calling itself recursively as we don't have any standard
+// library on device side.
+// DEVICE: call float @logf(float
+extern "C" __attribute__((device)) float logf(float __x) { return logf(__x); }
+
+// NOTE: this case is to illustrate the expected differences in behavior 
between
+// the host and device. In general we do not mess with host-side standard
+// library.
+//
+// Host is assumed to have standard library, so logf() calls LLVM intrinsic.
+// HOST: call float @llvm.log.f32(float
+extern "C" float logf(float __x) { return logf(__x); }


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


[PATCH] D42319: [CUDA] CUDA has no device-side library builtins.

2018-01-23 Thread Artem Belevich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323239: [CUDA] CUDA has no device-side library builtins. 
(authored by tra, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42319?vs=130697&id=131112#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42319

Files:
  cfe/trunk/lib/AST/Decl.cpp
  cfe/trunk/test/CodeGenCUDA/library-builtin.cu


Index: cfe/trunk/test/CodeGenCUDA/library-builtin.cu
===
--- cfe/trunk/test/CodeGenCUDA/library-builtin.cu
+++ cfe/trunk/test/CodeGenCUDA/library-builtin.cu
@@ -0,0 +1,22 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | \
+// RUN:  FileCheck --check-prefixes=HOST,BOTH %s
+// RUN: %clang_cc1 -fcuda-is-device -triple nvptx64-nvidia-cuda \
+// RUN:   -emit-llvm -o - %s | FileCheck %s --check-prefixes=DEVICE,BOTH
+
+// BOTH-LABEL: define float @logf(float
+
+// logf() should be calling itself recursively as we don't have any standard
+// library on device side.
+// DEVICE: call float @logf(float
+extern "C" __attribute__((device)) float logf(float __x) { return logf(__x); }
+
+// NOTE: this case is to illustrate the expected differences in behavior 
between
+// the host and device. In general we do not mess with host-side standard
+// library.
+//
+// Host is assumed to have standard library, so logf() calls LLVM intrinsic.
+// HOST: call float @llvm.log.f32(float
+extern "C" float logf(float __x) { return logf(__x); }
Index: cfe/trunk/lib/AST/Decl.cpp
===
--- cfe/trunk/lib/AST/Decl.cpp
+++ cfe/trunk/lib/AST/Decl.cpp
@@ -2901,6 +2901,13 @@
   Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
 return 0;
 
+  // CUDA does not have device-side standard library. printf and malloc are the
+  // only special cases that are supported by device-side runtime.
+  if (Context.getLangOpts().CUDA && hasAttr() &&
+  !hasAttr() &&
+  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
+return 0;
+
   return BuiltinID;
 }
 


Index: cfe/trunk/test/CodeGenCUDA/library-builtin.cu
===
--- cfe/trunk/test/CodeGenCUDA/library-builtin.cu
+++ cfe/trunk/test/CodeGenCUDA/library-builtin.cu
@@ -0,0 +1,22 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | \
+// RUN:  FileCheck --check-prefixes=HOST,BOTH %s
+// RUN: %clang_cc1 -fcuda-is-device -triple nvptx64-nvidia-cuda \
+// RUN:   -emit-llvm -o - %s | FileCheck %s --check-prefixes=DEVICE,BOTH
+
+// BOTH-LABEL: define float @logf(float
+
+// logf() should be calling itself recursively as we don't have any standard
+// library on device side.
+// DEVICE: call float @logf(float
+extern "C" __attribute__((device)) float logf(float __x) { return logf(__x); }
+
+// NOTE: this case is to illustrate the expected differences in behavior between
+// the host and device. In general we do not mess with host-side standard
+// library.
+//
+// Host is assumed to have standard library, so logf() calls LLVM intrinsic.
+// HOST: call float @llvm.log.f32(float
+extern "C" float logf(float __x) { return logf(__x); }
Index: cfe/trunk/lib/AST/Decl.cpp
===
--- cfe/trunk/lib/AST/Decl.cpp
+++ cfe/trunk/lib/AST/Decl.cpp
@@ -2901,6 +2901,13 @@
   Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
 return 0;
 
+  // CUDA does not have device-side standard library. printf and malloc are the
+  // only special cases that are supported by device-side runtime.
+  if (Context.getLangOpts().CUDA && hasAttr() &&
+  !hasAttr() &&
+  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
+return 0;
+
   return BuiltinID;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323241 - AST: adjust ObjC MS mangling to work with typedefs

2018-01-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Jan 23 11:17:25 2018
New Revision: 323241

URL: http://llvm.org/viewvc/llvm-project?rev=323241&view=rev
Log:
AST: adjust ObjC MS mangling to work with typedefs

Rather than hardcode the pointerness of the `id` and `class` types,
handle them generically.  This allows for the template type
specialization of `remove_pointer` which would look through the `id`
type and deal with the `objc_object` structure without the pointer.

Modified:
cfe/trunk/lib/AST/MicrosoftMangle.cpp
cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm

Modified: cfe/trunk/lib/AST/MicrosoftMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/MicrosoftMangle.cpp?rev=323241&r1=323240&r2=323241&view=diff
==
--- cfe/trunk/lib/AST/MicrosoftMangle.cpp (original)
+++ cfe/trunk/lib/AST/MicrosoftMangle.cpp Tue Jan 23 11:17:25 2018
@@ -1833,11 +1833,9 @@ void MicrosoftCXXNameMangler::mangleType
 llvm_unreachable("placeholder types shouldn't get to name mangling");
 
   case BuiltinType::ObjCId:
-Out << "PA";
 mangleArtificalTagType(TTK_Struct, "objc_object");
 break;
   case BuiltinType::ObjCClass:
-Out << "PA";
 mangleArtificalTagType(TTK_Struct, "objc_class");
 break;
   case BuiltinType::ObjCSel:
@@ -2337,9 +2335,6 @@ void MicrosoftCXXNameMangler::mangleType
 
 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
  Qualifiers Quals, SourceRange Range) {
-  if (T->isObjCIdType() || T->isObjCClassType())
-return mangleType(T->getPointeeType(), Range, QMM_Drop);
-
   QualType PointeeType = T->getPointeeType();
   manglePointerCVQualifiers(Quals);
   manglePointerExtQualifiers(Quals, PointeeType);

Modified: cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm?rev=323241&r1=323240&r2=323241&view=diff
==
--- cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm (original)
+++ cfe/trunk/test/CodeGenObjCXX/msabi-objc-types.mm Tue Jan 23 11:17:25 2018
@@ -33,7 +33,7 @@ void g(id &) {}
 // CHECK-LABEL: "\01?g@@YAXAAPAUobjc_object@@@Z"
 
 void g(const id &) {}
-// CHECK-LABEL: "\01?g@@YAXABPAUobjc_object@@@Z"
+// CHECK-LABEL: "\01?g@@YAXABQAUobjc_object@@@Z"
 
 void g(id &&) {}
 // CHECK-LABEL: "\01?g@@YAX$$QAPAUobjc_object@@@Z"
@@ -45,7 +45,7 @@ void h(Class &) {}
 // CHECK-LABEL: "\01?h@@YAXAAPAUobjc_class@@@Z"
 
 void h(const Class &) {}
-// CHECK-LABEL: "\01?h@@YAXABPAUobjc_class@@@Z"
+// CHECK-LABEL: "\01?h@@YAXABQAUobjc_class@@@Z"
 
 void h(Class &&) {}
 // CHECK-LABEL: "\01?h@@YAX$$QAPAUobjc_class@@@Z"
@@ -62,6 +62,12 @@ I &k() { return *kI; }
 const I &l() { return *kI; }
 // CHECK-LABEL: "\01?l@@YAABUI@@XZ"
 
+void m(const id) {}
+// CHECK-LABEL: "\01?m@@YAXQAUobjc_object@@@Z"
+
+void m(const I *) {}
+// CHECK-LABEL: "\01?m@@YAXPBUI@@@Z"
+
 struct __declspec(dllexport) s {
   struct s &operator=(const struct s &) = delete;
 
@@ -93,16 +99,16 @@ struct __declspec(dllexport) s {
   // CHECK-LABEL: "\01?m@s@@QAAX$$QAPAUobjc_object@@@Z"
 
   void m(const id &) {}
-  // CHECK-LABEL: "\01?m@s@@QAAXABPAUobjc_object@@@Z"
+  // CHECK-LABEL: "\01?m@s@@QAAXABQAUobjc_object@@@Z"
 
   void m(const id &&) {}
-  // CHECK-LABEL: "\01?m@s@@QAAX$$QBPAUobjc_object@@@Z"
+  // CHECK-LABEL: "\01?m@s@@QAAX$$QBQAUobjc_object@@@Z"
 
   void m(Class *) {}
   // CHECK-LABEL: "\01?m@s@@QAAXPAPAUobjc_class@@@Z"
 
   void m(const Class *) {}
-  // CHECK-LABEL: "\01?m@s@@QAAXPBPAUobjc_class@@@Z"
+  // CHECK-LABEL: "\01?m@s@@QAAXPBQAUobjc_class@@@Z"
 
   void m(Class) {}
   // CHECK-LABEL: "\01?m@s@@QAAXPAUobjc_class@@@Z"
@@ -111,12 +117,31 @@ struct __declspec(dllexport) s {
   // CHECK-LABEL: "\01?m@s@@QAAXAAPAUobjc_class@@@Z"
 
   void m(const Class &) {}
-  // CHECK-LABEL: "\01?m@s@@QAAXABPAUobjc_class@@@Z"
+  // CHECK-LABEL: "\01?m@s@@QAAXABQAUobjc_class@@@Z"
 
   void m(Class &&) {}
   // CHECK-LABEL: "\01?m@s@@QAAX$$QAPAUobjc_class@@@Z"
 
   void m(const Class &&) {}
-  // CHECK-LABEL: "\01?m@s@@QAAX$$QBPAUobjc_class@@@Z"
+  // CHECK-LABEL: "\01?m@s@@QAAX$$QBQAUobjc_class@@@Z"
+};
+
+template 
+struct remove_pointer { typedef T type; };
+
+template 
+struct remove_pointer {
+  typedef T type;
 };
 
+template 
+struct t {
+  t() {}
+};
+
+template struct t;
+// CHECK-LABEL: "\01??0?$t@PAUobjc_objectQAA@XZ"
+
+template struct t::type>;
+// CHECK-LABEL: "\01??0?$t@Uobjc_objectQAA@XZ"
+


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


r323244 - [html] [NFC] Use raw strings to dump the style table.

2018-01-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jan 23 11:28:43 2018
New Revision: 323244

URL: http://llvm.org/viewvc/llvm-project?rev=323244&view=rev
Log:
[html] [NFC] Use raw strings to dump the style table.

Modified:
cfe/trunk/lib/Rewrite/HTMLRewrite.cpp

Modified: cfe/trunk/lib/Rewrite/HTMLRewrite.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Rewrite/HTMLRewrite.cpp?rev=323244&r1=323243&r2=323244&view=diff
==
--- cfe/trunk/lib/Rewrite/HTMLRewrite.cpp (original)
+++ cfe/trunk/lib/Rewrite/HTMLRewrite.cpp Tue Jan 23 11:28:43 2018
@@ -288,82 +288,108 @@ void html::AddHeaderFooterInternalBuilti
   if (!title.empty())
 os << "" << html::EscapeText(title) << "\n";
 
-  os << "\n"
-  " body { color:#00; background-color:#ff }\n"
-  " body { font-family:Helvetica, sans-serif; font-size:10pt }\n"
-  " h1 { font-size:14pt }\n"
-  " .FileName { margin-top: 5px; margin-bottom: 5px; display: inline; }\n"
-  " .FileNav { margin-left: 5px; margin-right: 5px; display: inline; }\n"
-  " .FileNav a { text-decoration:none; font-size: larger; }\n"
-  " .divider { margin-top: 30px; margin-bottom: 30px; height: 15px; }\n"
-  " .divider { background-color: gray; }\n"
-  " .code { border-collapse:collapse; width:100%; }\n"
-  " .code { font-family: \"Monospace\", monospace; font-size:10pt }\n"
-  " .code { line-height: 1.2em }\n"
-  " .comment { color: green; font-style: oblique }\n"
-  " .keyword { color: blue }\n"
-  " .string_literal { color: red }\n"
-  " .directive { color: darkmagenta }\n"
-  // Macro expansions.
-  " .expansion { display: none; }\n"
-  " .macro:hover .expansion { display: block; border: 2px solid #FF; "
-  "padding: 2px; background-color:#FFF0F0; font-weight: normal; "
-  "  -webkit-border-radius:5px;  -webkit-box-shadow:1px 1px 7px #000; "
-  "  border-radius:5px;  box-shadow:1px 1px 7px #000; "
-  "position: absolute; top: -1em; left:10em; z-index: 1 } \n"
-  " #tooltiphint { position: fixed; width: 50em; margin-left: -25em;"
- "left: 50%; padding: 10px; border: 1px solid #b0b0b0;"
- "border-radius: 2px; box-shadow: 1px 1px 7px black; "
- "background-color: #c0c0c0; z-index: 2; }\n"
-  " .macro { color: darkmagenta; background-color:LemonChiffon;"
- // Macros are position: relative to provide base for expansions.
- " position: relative }\n"
-  " .num { width:2.5em; padding-right:2ex; background-color:#ee }\n"
-  " .num { text-align:right; font-size:8pt }\n"
-  " .num { color:#44 }\n"
-  " .line { padding-left: 1ex; border-left: 3px solid #ccc }\n"
-  " .line { white-space: pre }\n"
-  " .msg { -webkit-box-shadow:1px 1px 7px #000 }\n"
-  " .msg { box-shadow:1px 1px 7px #000 }\n"
-  " .msg { -webkit-border-radius:5px }\n"
-  " .msg { border-radius:5px }\n"
-  " .msg { font-family:Helvetica, sans-serif; font-size:8pt }\n"
-  " .msg { float:left }\n"
-  " .msg { padding:0.25em 1ex 0.25em 1ex }\n"
-  " .msg { margin-top:10px; margin-bottom:10px }\n"
-  " .msg { font-weight:bold }\n"
-  " .msg { max-width:60em; word-wrap: break-word; white-space: pre-wrap 
}\n"
-  " .msgT { padding:0x; spacing:0x }\n"
-  " .msgEvent { background-color:#fff8b4; color:#00 }\n"
-  " .msgControl { background-color:#bb; color:#00 }\n"
-  " .msgNote { background-color:#ddeeff; color:#00 }\n"
-  " .mrange { background-color:#dfddf3 }\n"
-  " .mrange { border-bottom:1px solid #6F9DBE }\n"
-  " .PathIndex { font-weight: bold; padding:0px 5px; "
-"margin-right:5px; }\n"
-  " .PathIndex { -webkit-border-radius:8px }\n"
-  " .PathIndex { border-radius:8px }\n"
-  " .PathIndexEvent { background-color:#bfba87 }\n"
-  " .PathIndexControl { background-color:#8c8c8c }\n"
-  " .PathNav a { text-decoration:none; font-size: larger }\n"
-  " .CodeInsertionHint { font-weight: bold; background-color: #10dd10 }\n"
-  " .CodeRemovalHint { background-color:#de1010 }\n"
-  " .CodeRemovalHint { border-bottom:1px solid #6F9DBE }\n"
-  " .selected{ background-color:orange !important; }\n"
-  " table.simpletable {\n"
-  "   padding: 5px;\n"
-  "   font-size:12pt;\n"
-  "   margin:20px;\n"
-  "   border-collapse: collapse; border-spacing: 0px;\n"
-  " }\n"
-  " td.rowname {\n"
-  "   text-align: right;\n"
-  "   vertical-align: top;\n"
-  "   font-weight: bold;\n"
-  "   color:#44;\n"
-  "   padding-right:2ex;\n"
-  " }\n"
-  "\n\n";
+  os << R"<<<(
+
+body { color:#00; background-color:#ff }
+body { font-family:Helvetica, sans-serif; font-size:10pt }
+h1 { font-size:14pt }
+.FileName { margin-top: 5px; margin-bottom: 5px; display: inline; }
+.Fi

r323245 - [analyzer] Show full analyzer invocation for reproducibility in HTML reports

2018-01-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jan 23 11:28:52 2018
New Revision: 323245

URL: http://llvm.org/viewvc/llvm-project?rev=323245&view=rev
Log:
[analyzer] Show full analyzer invocation for reproducibility in HTML reports

Analyzing problems which appear in scan-build results can be very
difficult, as after the launch no exact invocation is stored, and it's
super-hard to launch the debugger.
With this patch, the exact analyzer invocation appears in the footer,
and can be copied to debug/check reproducibility/etc.

rdar://35980230

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/Rewrite/HTMLRewrite.cpp
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h?rev=323245&r1=323244&r2=323245&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h Tue Jan 23 
11:28:52 2018
@@ -139,6 +139,10 @@ public:
   AnalysisPurgeMode AnalysisPurgeOpt;
   
   std::string AnalyzeSpecificFunction;
+
+  /// Store full compiler invocation for reproducible instructions in the
+  /// generated report.
+  std::string FullCompilerInvocation;
   
   /// \brief The maximum number of times the analyzer visits a block.
   unsigned maxBlockVisitOnPath;

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=323245&r1=323244&r2=323245&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Tue Jan 23 11:28:52 2018
@@ -305,6 +305,14 @@ static bool ParseAnalyzerArgs(AnalyzerOp
 }
   }
 
+  llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
+  for (unsigned i=0; ihttp://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Rewrite/HTMLRewrite.cpp?rev=323245&r1=323244&r2=323245&view=diff
==
--- cfe/trunk/lib/Rewrite/HTMLRewrite.cpp (original)
+++ cfe/trunk/lib/Rewrite/HTMLRewrite.cpp Tue Jan 23 11:28:52 2018
@@ -387,6 +387,26 @@ td.rowname {
   color:#44;
   padding-right:2ex;
 }
+
+/* Hidden text. */
+input.spoilerhider + label {
+  cursor: pointer;
+  text-decoration: underline;
+  display: block;
+}
+input.spoilerhider {
+ display: none;
+}
+input.spoilerhider ~ .spoiler {
+  overflow: hidden;
+  margin: 10px auto 0;
+  height: 0;
+  opacity: 0;
+}
+input.spoilerhider:checked + label + .spoiler{
+  height: auto;
+  opacity: 1;
+}
 
 
 )<<<";

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=323245&r1=323244&r2=323245&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Tue Jan 23 11:28:52 
2018
@@ -406,6 +406,12 @@ void HTMLDiagnostics::FinalizeHTML(const
 Annotated Source Code
 Press '?'
to see keyboard shortcuts
+
+Show analyzer invocation
+clang -cc1 )<<<";
+os << html::EscapeText(AnalyzerOpts.FullCompilerInvocation);
+os << R"<<<(
+
 
   Keyboard shortcuts: 
   
@@ -416,7 +422,6 @@ void HTMLDiagnostics::FinalizeHTML(const
   Close
 
 )<<<";
-
 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
   }
 


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


[PATCH] D42170: Fixit for 'typedef' instead of 'typename' typo

2018-01-23 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: Parse/ParseTemplate.cpp:492
+  // Is there just a typo in the input code? ('typedef' instead of 'typename')
+  if (Tok.is(tok::kw_typedef)) {
+Diag(Tok.getLocation(), diag::err_expected_template_parameter);

jkorous-apple wrote:
> vsapsai wrote:
> > How does it work when you have `typedef` for the first template parameter?
> It works all right but I am puzzled by your question now :-)
> 
> 
> ```
> /Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp:3:11:
>  error: expected template parameter
> template  struct Foo {
>   ^
> /Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp:3:11:
>  note: Did you mean to use 'typename'?
> template  struct Foo {
>   ^~~
>   typename
> fix-it:"/Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp":{3:11-3:18}:"typename"
> /Users/jankorous/src/oss/llvm/llvm/tools/clang/test/Parser/typedef-instead-of-typename-typo.hpp:4:3:
>  error: unknown type name 'a'
>   a
>   ^
> 
> ```
> 
> I am probably not following you here. Do you have any specific reason on your 
> mind? Anything I should think about or check in the source code?
I was suspicious that
```lang=c++
  if (isStartOfTemplateTypeParameter())
return ParseTypeParameter(Depth, Position);
```
earlier in the function won't let your code run for the first template 
parameter. But `isStartOfTemplateTypeParameter` has
```lang=c++
  if (Tok.isNot(tok::kw_typename))
return false;
```
so everything works fine.



Comment at: Parser/typedef-instead-of-typename-typo.hpp:5
+  a
+}; // CHECK: expected-error{{expected template parameter}} \
+// CHECK: expected-note{{Did you mean to use 'typename'?}} \

jkorous-apple wrote:
> vsapsai wrote:
> > It is a little bit confusing to what lines the messages would be attributed 
> > to. Need to check locally because not sure I interpret all those 
> > backslashes the same way lit does.
> > 
> > Also idea for the test. To check that the fix-it was applied properly you 
> > can add a member like `B b;` and it shouldn't trigger any errors.
> I am totally open to suggestions how to write better tests using FileCheck. 
> As far as I understand it I have to keep the expected-* macro on the same 
> line as the code. Or is there any better way?
> 
> Do I understand it right that you suggest to create another test in which to 
> try applying fixit and check that compilation was successful? Do you mean to 
> create compile_commands.json temporarily and use clang-check -fixit?
> 
> 
To answer your question. You can keep the expected-* macro on the same line and 
attach subsequent expectations with backslash. Another option is doing 
something like `expected-note@-1 {{...}}`. That `-1` is a relative line number.

Back to the test case. I believe you need to separate expected-* checks from 
fixit output check. The former uses `-verify` and the latter `| FileCheck %s`. 
I think test/FixIt/fixit-vexing-parse.cpp is a good example. And remember that 
you can split long lines, `template  struct Foo` doesn't 
have to be on the same line.

For suggested test I didn't mean anything fancy. Just something like adding a 
line `B b;` Because currently for
```lang=c++
template  
struct Foo {
B b;
};
```
the output is
```
recovery.cc:1:31: error: unknown type name 'B'
template 
  ^
recovery.cc:3:5: error: unknown type name 'B'
B b;
^
2 errors generated.
```
And with your change we won't have the second error.


https://reviews.llvm.org/D42170



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


r323247 - CodeGen: use `llvm.used` for ObjC protocols

2018-01-23 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Jan 23 11:35:51 2018
New Revision: 323247

URL: http://llvm.org/viewvc/llvm-project?rev=323247&view=rev
Log:
CodeGen: use `llvm.used` for ObjC protocols

These symbols are supposed to be preserved even by the linker.  Use the
`llvm.used` to ensure that the symbols are not removed by DCE in the
linker.  This should be a no-op change on MachO since the symbols are
annotated as `no_dead_strip`.

Modified:
cfe/trunk/lib/CodeGen/CGObjCMac.cpp
cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m

Modified: cfe/trunk/lib/CodeGen/CGObjCMac.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGObjCMac.cpp?rev=323247&r1=323246&r2=323247&view=diff
==
--- cfe/trunk/lib/CodeGen/CGObjCMac.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGObjCMac.cpp Tue Jan 23 11:35:51 2018
@@ -6399,7 +6399,7 @@ llvm::Value *CGObjCNonFragileABIMac::Gen
   PTGV->setAlignment(Align.getQuantity());
   if (!CGM.getTriple().isOSBinFormatMachO())
 PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolName));
-  CGM.addCompilerUsedGlobal(PTGV);
+  CGM.addUsedGlobal(PTGV);
   return CGF.Builder.CreateAlignedLoad(PTGV, Align);
 }
 
@@ -6843,7 +6843,7 @@ llvm::Constant *CGObjCNonFragileABIMac::
 Protocols[PD->getIdentifier()] = Entry;
   }
   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
-  CGM.addCompilerUsedGlobal(Entry);
+  CGM.addUsedGlobal(Entry);
 
   // Use this protocol meta-data to build protocol list table in section
   // __DATA, __objc_protolist
@@ -6862,7 +6862,7 @@ llvm::Constant *CGObjCNonFragileABIMac::
   PTGV->setSection(GetSectionName("__objc_protolist",
   "coalesced,no_dead_strip"));
   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
-  CGM.addCompilerUsedGlobal(PTGV);
+  CGM.addUsedGlobal(PTGV);
   return Entry;
 }
 

Modified: cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m?rev=323247&r1=323246&r2=323247&view=diff
==
--- cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m (original)
+++ cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m Tue Jan 23 
11:35:51 2018
@@ -23,15 +23,17 @@ int main() {
 // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_P0" = weak hidden global
 // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_P0" = weak hidden global
 
-// CHECK: llvm.compiler.used = appending global [10 x i8*]
+// CHECK: llvm.used = appending global [3 x i8*]
+// CHECK-SAME: "\01l_OBJC_PROTOCOL_$_P0"
+// CHECK-SAME: "\01l_OBJC_LABEL_PROTOCOL_$_P0"
+// CHECK-SAME: "\01l_OBJC_PROTOCOL_REFERENCE_$_P0"
+
+// CHECK: llvm.compiler.used = appending global [7 x i8*]
 // CHECK-SAME: OBJC_CLASS_NAME_
 // CHECK-SAME: OBJC_METH_VAR_NAME_
 // CHECK-SAME: OBJC_METH_VAR_TYPE_
 // CHECK-SAME: "\01l_OBJC_$_CLASS_METHODS_A"
 // CHECK-SAME: "\01l_OBJC_CLASS_PROTOCOLS_$_A"
 // CHECK-SAME: OBJC_CLASS_NAME_.1
-// CHECK-SAME: "\01l_OBJC_PROTOCOL_$_P0"
-// CHECK-SAME: "\01l_OBJC_LABEL_PROTOCOL_$_P0"
-// CHECK-SAME: "\01l_OBJC_PROTOCOL_REFERENCE_$_P0"
 // CHECK-SAME: "OBJC_LABEL_CLASS_$"
 // CHECK-SAME: section "llvm.metadata"


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


r323251 - [analyzer] Mark lines as relevant even if they weren't executed but have a label attached

2018-01-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jan 23 12:01:31 2018
New Revision: 323251

URL: http://llvm.org/viewvc/llvm-project?rev=323251&view=rev
Log:
[analyzer] Mark lines as relevant even if they weren't executed but have a 
label attached

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

Added:
cfe/trunk/test/Analysis/html_diagnostics/relevant_lines/notexecutedlines.c
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=323251&r1=323250&r2=323251&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Tue Jan 23 12:01:31 
2018
@@ -28,6 +28,8 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
+#include 
 #include 
 
 using namespace clang;
@@ -96,11 +98,6 @@ public:
   std::string generateKeyboardNavigationJavascript();
 
 private:
-  /// \return JavaScript for an option to only show relevant lines.
-  std::string showRelevantLinesJavascript(const PathDiagnostic &D);
-
-  /// \return Executed lines from \p D in JSON format.
-  std::string serializeExecutedLines(const PathDiagnostic &D);
 
   /// \return Javascript for displaying shortcuts help;
   std::string showHelpJavascript();
@@ -333,6 +330,115 @@ std::string HTMLDiagnostics::GenerateHTM
   return os.str();
 }
 
+/// Write executed lines from \p D in JSON format into \p os.
+static void serializeExecutedLines(
+const PathDiagnostic &D,
+const PathPieces &path,
+llvm::raw_string_ostream &os) {
+
+  // Copy executed lines from path diagnostics.
+  std::map> ExecutedLines;
+  for (auto I = D.executedLines_begin(),
+E = D.executedLines_end(); I != E; ++I) {
+std::set &LinesInFile = ExecutedLines[I->first];
+for (unsigned LineNo : I->second) {
+  LinesInFile.insert(LineNo);
+}
+  }
+
+  // We need to include all lines for which any kind of diagnostics appears.
+  for (const auto &P : path) {
+FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
+FileID FID = Loc.getFileID();
+unsigned LineNo = Loc.getLineNumber();
+ExecutedLines[FID.getHashValue()].insert(LineNo);
+  }
+
+  os << "var relevant_lines = {";
+  for (auto I = ExecutedLines.begin(),
+E = ExecutedLines.end(); I != E; ++I) {
+if (I != ExecutedLines.begin())
+  os << ", ";
+
+os << "\"" << I->first << "\": {";
+for (unsigned LineNo : I->second) {
+  if (LineNo != *(I->second.begin()))
+os << ", ";
+
+  os << "\"" << LineNo << "\": 1";
+}
+os << "}";
+  }
+
+  os << "};";
+}
+
+/// \return JavaScript for an option to only show relevant lines.
+static std::string showRelevantLinesJavascript(
+  const PathDiagnostic &D, const PathPieces &path) {
+  std::string s;
+  llvm::raw_string_ostream os(s);
+  os << "\n";
+  serializeExecutedLines(D, path, os);
+  os << R"<<<(
+
+var filterCounterexample = function (hide) {
+  var tables = document.getElementsByClassName("code");
+  for (var t=0; t

[PATCH] D42320: [analyzer] Mark lines as relevant even if they weren't executed but have a label attached

2018-01-23 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323251: [analyzer] Mark lines as relevant even if they 
weren't executed but have a… (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D42320

Files:
  lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  test/Analysis/html_diagnostics/relevant_lines/notexecutedlines.c

Index: test/Analysis/html_diagnostics/relevant_lines/notexecutedlines.c
===
--- test/Analysis/html_diagnostics/relevant_lines/notexecutedlines.c
+++ test/Analysis/html_diagnostics/relevant_lines/notexecutedlines.c
@@ -0,0 +1,12 @@
+int f() {
+  int zzz = 200;
+  zzz += 100;
+  return 0;
+}
+
+// Show line with the warning even if it wasn't executed (e.g. warning given
+// by path-insensitive analysis).
+// RUN: rm -rf %t.output
+// RUN: %clang_analyze_cc1 -analyze -analyzer-checker=core,deadcode -analyzer-output html -o %t.output %s
+// RUN: cat %t.output/* | FileCheck %s --match-full-lines
+// CHECK: var relevant_lines = {"1": {"3": 1}};
Index: lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
===
--- lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
+++ lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
@@ -28,6 +28,8 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
+#include 
 #include 
 
 using namespace clang;
@@ -96,11 +98,6 @@
   std::string generateKeyboardNavigationJavascript();
 
 private:
-  /// \return JavaScript for an option to only show relevant lines.
-  std::string showRelevantLinesJavascript(const PathDiagnostic &D);
-
-  /// \return Executed lines from \p D in JSON format.
-  std::string serializeExecutedLines(const PathDiagnostic &D);
 
   /// \return Javascript for displaying shortcuts help;
   std::string showHelpJavascript();
@@ -333,6 +330,115 @@
   return os.str();
 }
 
+/// Write executed lines from \p D in JSON format into \p os.
+static void serializeExecutedLines(
+const PathDiagnostic &D,
+const PathPieces &path,
+llvm::raw_string_ostream &os) {
+
+  // Copy executed lines from path diagnostics.
+  std::map> ExecutedLines;
+  for (auto I = D.executedLines_begin(),
+E = D.executedLines_end(); I != E; ++I) {
+std::set &LinesInFile = ExecutedLines[I->first];
+for (unsigned LineNo : I->second) {
+  LinesInFile.insert(LineNo);
+}
+  }
+
+  // We need to include all lines for which any kind of diagnostics appears.
+  for (const auto &P : path) {
+FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
+FileID FID = Loc.getFileID();
+unsigned LineNo = Loc.getLineNumber();
+ExecutedLines[FID.getHashValue()].insert(LineNo);
+  }
+
+  os << "var relevant_lines = {";
+  for (auto I = ExecutedLines.begin(),
+E = ExecutedLines.end(); I != E; ++I) {
+if (I != ExecutedLines.begin())
+  os << ", ";
+
+os << "\"" << I->first << "\": {";
+for (unsigned LineNo : I->second) {
+  if (LineNo != *(I->second.begin()))
+os << ", ";
+
+  os << "\"" << LineNo << "\": 1";
+}
+os << "}";
+  }
+
+  os << "};";
+}
+
+/// \return JavaScript for an option to only show relevant lines.
+static std::string showRelevantLinesJavascript(
+  const PathDiagnostic &D, const PathPieces &path) {
+  std::string s;
+  llvm::raw_string_ostream os(s);
+  os << "\n";
+  serializeExecutedLines(D, path, os);
+  os << R"<<<(
+
+var filterCounterexample = function (hide) {
+  var tables = document.getElementsByClassName("code");
+  for (var t=0; t

r323253 - [WebAssembly] Factor out settings common to wasm32 and wasm64. NFC.

2018-01-23 Thread Dan Gohman via cfe-commits
Author: djg
Date: Tue Jan 23 12:22:12 2018
New Revision: 323253

URL: http://llvm.org/viewvc/llvm-project?rev=323253&view=rev
Log:
[WebAssembly] Factor out settings common to wasm32 and wasm64. NFC.

MaxAtomicPromoteWidth and MaxAtomicInlineWidth are 64 on both
wasm32 and wasm64, so they can be set in shared code.

Modified:
cfe/trunk/lib/Basic/Targets/WebAssembly.h

Modified: cfe/trunk/lib/Basic/Targets/WebAssembly.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/WebAssembly.h?rev=323253&r1=323252&r2=323253&view=diff
==
--- cfe/trunk/lib/Basic/Targets/WebAssembly.h (original)
+++ cfe/trunk/lib/Basic/Targets/WebAssembly.h Tue Jan 23 12:22:12 2018
@@ -45,6 +45,7 @@ public:
 SigAtomicType = SignedLong;
 LongDoubleWidth = LongDoubleAlign = 128;
 LongDoubleFormat = &llvm::APFloat::IEEEquad();
+MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
 SizeType = UnsignedInt;
 PtrDiffType = SignedInt;
 IntPtrType = SignedInt;
@@ -118,7 +119,6 @@ public:
   explicit WebAssembly32TargetInfo(const llvm::Triple &T,
const TargetOptions &Opts)
   : WebAssemblyTargetInfo(T, Opts) {
-MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
 resetDataLayout("e-m:e-p:32:32-i64:64-n32:64-S128");
   }
 
@@ -135,7 +135,6 @@ public:
   : WebAssemblyTargetInfo(T, Opts) {
 LongAlign = LongWidth = 64;
 PointerAlign = PointerWidth = 64;
-MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
 SizeType = UnsignedLong;
 PtrDiffType = SignedLong;
 IntPtrType = SignedLong;


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


  1   2   >