[clang-tools-extra] 2e75986 - bugprone-argument-comment: ignore mismatches from system headers

2021-08-03 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2021-08-03T19:56:27Z
New Revision: 2e75986a21e543ac9f169a067542eec590339ac0

URL: 
https://github.com/llvm/llvm-project/commit/2e75986a21e543ac9f169a067542eec590339ac0
DIFF: 
https://github.com/llvm/llvm-project/commit/2e75986a21e543ac9f169a067542eec590339ac0.diff

LOG: bugprone-argument-comment: ignore mismatches from system headers

As of 2a3498e24f97d, we ignore parameter name mismatches for functions
in the `std::` namespace, since those aren't standardized. It seems
reasonable to extend this to all functions which are declared in system
headers, since this lint can be a bit noisy otherwise
(https://bugs.chromium.org/p/chromium/issues/detail?id=1191507).

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h

Modified: 
clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
index e50ebdba3b34..c36fb60b6d3d 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
@@ -20,10 +20,12 @@ namespace clang {
 namespace tidy {
 namespace bugprone {
 namespace {
-AST_MATCHER(Decl, isFromStdNamespace) {
+AST_MATCHER(Decl, isFromStdNamespaceOrSystemHeader) {
   if (const auto *D = Node.getDeclContext()->getEnclosingNamespaceContext())
-return D->isStdNamespace();
-  return false;
+if (D->isStdNamespace())
+  return true;
+  return Node.getASTContext().getSourceManager().isInSystemHeader(
+  Node.getLocation());
 }
 } // namespace
 
@@ -66,13 +68,13 @@ void ArgumentCommentCheck::registerMatchers(MatchFinder 
*Finder) {
// not specified by the standard, and standard library
// implementations in practice have to use reserved names to
// avoid conflicts with same-named macros.
-   unless(hasDeclaration(isFromStdNamespace(
-  .bind("expr"),
-  this);
-  Finder->addMatcher(
-  cxxConstructExpr(unless(hasDeclaration(isFromStdNamespace(
+   unless(hasDeclaration(isFromStdNamespaceOrSystemHeader(
   .bind("expr"),
   this);
+  Finder->addMatcher(cxxConstructExpr(unless(hasDeclaration(
+  isFromStdNamespaceOrSystemHeader(
+ .bind("expr"),
+ this);
 }
 
 static std::vector>

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h
 
b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h
new file mode 100644
index ..1e065b1edeb6
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/header-with-decl.h
@@ -0,0 +1 @@
+void my_header_function(int arg);

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h
 
b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h
new file mode 100644
index ..4e3529a6f1ab
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/Inputs/bugprone-argument-comment/system-header-with-decl.h
@@ -0,0 +1,3 @@
+#pragma clang system_header
+
+void my_system_header_function(int arg);

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp
index 8a6fe097a55d..cb4eac84c691 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-argument-comment %t
+// RUN: %check_clang_tidy %s bugprone-argument-comment %t -- -- -I 
%S/Inputs/bugprone-argument-comment
 
 // FIXME: clang-tidy should provide a -verify mode to make writing these checks
 // easier and more accurate.
@@ -134,3 +134,20 @@ void test(int a, int b) {
   std::swap(a, /*num=*/b);
 }
 } // namespace ignore_std_functions
+
+namespace regular_header {
+#include "header-with-decl.h"
+void test() {
+  my_header_function(/*not_arg=*/1);
+// CHECK-NOTES: [[@LINE-1]]:22: warning: argument name 'not_arg' in comment 
does not match parameter name 'arg'
+// CHECK-NOTES: header-with-decl.h:1:29: note: 'arg' declared here
+// CHECK-FIXES: my_header_function(/*not_arg=*/1);
+}
+} // namespace regular_header
+
+namespace system_header {
+#include 

[clang] e12e02d - [clang] Evaluate strlen of strcpy argument for -Wfortify-source.

2021-07-28 Thread George Burgess IV via cfe-commits

Author: Michael Benfield
Date: 2021-07-28T20:52:57Z
New Revision: e12e02df09a967f644cf28136a7361bce7a5bb91

URL: 
https://github.com/llvm/llvm-project/commit/e12e02df09a967f644cf28136a7361bce7a5bb91
DIFF: 
https://github.com/llvm/llvm-project/commit/e12e02df09a967f644cf28136a7361bce7a5bb91.diff

LOG: [clang] Evaluate strlen of strcpy argument for -Wfortify-source.

Also introduce Expr::tryEvaluateStrLen.

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

Added: 


Modified: 
clang/include/clang/AST/Expr.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/AST/ExprConstant.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/Analysis/security-syntax-checks.m
clang/test/Sema/warn-fortify-source.c

Removed: 




diff  --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 06164411cc2d4..991abef733637 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -740,6 +740,12 @@ class Expr : public ValueStmt {
   bool tryEvaluateObjectSize(uint64_t , ASTContext ,
  unsigned Type) const;
 
+  /// If the current Expr is a pointer, this will try to statically
+  /// determine the strlen of the string pointed to.
+  /// Returns true if all of the above holds and we were able to figure out the
+  /// strlen, false otherwise.
+  bool tryEvaluateStrLen(uint64_t , ASTContext ) const;
+
   /// Enumeration used to describe the kind of Null pointer constant
   /// returned from \c isNullPointerConstant().
   enum NullPointerConstantKind {

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 00b443b45f132..a777f08de8909 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -816,6 +816,11 @@ def warn_fortify_source_size_mismatch : Warning<
   "'%0' size argument is too large; destination buffer has size %1,"
   " but size argument is %2">, InGroup;
 
+def warn_fortify_strlen_overflow: Warning<
+  "'%0' will always overflow; destination buffer has size %1,"
+  " but the source string has length %2 (including NUL byte)">,
+  InGroup;
+
 def warn_fortify_source_format_overflow : Warning<
   "'%0' will always overflow; destination buffer has size %1,"
   " but format string expands to at least %2">,

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 01c0168d61a40..f49a144879b3e 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -1826,6 +1826,8 @@ static bool EvaluateComplex(const Expr *E, ComplexValue 
, EvalInfo );
 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue ,
EvalInfo );
 static bool EvaluateAsRValue(EvalInfo , const Expr *E, APValue );
+static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t ,
+  EvalInfo );
 
 /// Evaluate an integer or fixed point expression into an APResult.
 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint ,
@@ -11836,46 +11838,10 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const 
CallExpr *E,
   case Builtin::BI__builtin_wcslen: {
 // As an extension, we support __builtin_strlen() as a constant expression,
 // and support folding strlen() to a constant.
-LValue String;
-if (!EvaluatePointer(E->getArg(0), String, Info))
-  return false;
-
-QualType CharTy = E->getArg(0)->getType()->getPointeeType();
-
-// Fast path: if it's a string literal, search the string value.
-if (const StringLiteral *S = dyn_cast_or_null(
-String.getLValueBase().dyn_cast())) {
-  // The string literal may have embedded null characters. Find the first
-  // one and truncate there.
-  StringRef Str = S->getBytes();
-  int64_t Off = String.Offset.getQuantity();
-  if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
-  S->getCharByteWidth() == 1 &&
-  // FIXME: Add fast-path for wchar_t too.
-  Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
-Str = Str.substr(Off);
-
-StringRef::size_type Pos = Str.find(0);
-if (Pos != StringRef::npos)
-  Str = Str.substr(0, Pos);
-
-return Success(Str.size(), E);
-  }
-
-  // Fall through to slow path to issue appropriate diagnostic.
-}
-
-// Slow path: scan the bytes of the string looking for the terminating 0.
-for (uint64_t Strlen = 0; /**/; ++Strlen) {
-  APValue Char;
-  if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
-  !Char.isInt())
-return false;
-  if (!Char.getInt())
-return Success(Strlen, E);
-  if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
-return false;
-}
+uint64_t StrLen;
+if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, 

[clang] 20f7b5f - [Clang] Test case for -Wunused-but-set-variable, warn for volatile.

2021-06-14 Thread George Burgess IV via cfe-commits

Author: Michael Benfield
Date: 2021-06-14T10:25:59-07:00
New Revision: 20f7b5f3f9c8ebbbe7bf6648c824b815385d4bf7

URL: 
https://github.com/llvm/llvm-project/commit/20f7b5f3f9c8ebbbe7bf6648c824b815385d4bf7
DIFF: 
https://github.com/llvm/llvm-project/commit/20f7b5f3f9c8ebbbe7bf6648c824b815385d4bf7.diff

LOG: [Clang] Test case for -Wunused-but-set-variable, warn for volatile.

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

Added: 


Modified: 
clang/test/Sema/warn-unused-but-set-variables.c

Removed: 




diff  --git a/clang/test/Sema/warn-unused-but-set-variables.c 
b/clang/test/Sema/warn-unused-but-set-variables.c
index 93595a251df0..a8d05243321f 100644
--- a/clang/test/Sema/warn-unused-but-set-variables.c
+++ b/clang/test/Sema/warn-unused-but-set-variables.c
@@ -23,6 +23,10 @@ int f0() {
   int a;
   w = (a = 0);
 
+  // Following gcc, warn for a volatile variable.
+  volatile int b; // expected-warning{{variable 'b' set but not used}}
+  b = 0;
+
   int x;
   x = 0;
   return x;



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


[clang] cf49cae - [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable

2021-06-01 Thread George Burgess IV via cfe-commits

Author: Michael Benfield
Date: 2021-06-01T15:38:48-07:00
New Revision: cf49cae278b4e972cd2547d72f9ee7d9d69a3af4

URL: 
https://github.com/llvm/llvm-project/commit/cf49cae278b4e972cd2547d72f9ee7d9d69a3af4
DIFF: 
https://github.com/llvm/llvm-project/commit/cf49cae278b4e972cd2547d72f9ee7d9d69a3af4.diff

LOG: [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable

These are intended to mimic warnings available in gcc.

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

Added: 
clang/test/Sema/warn-unused-but-set-parameters.c
clang/test/Sema/warn-unused-but-set-variables.c
clang/test/SemaCXX/warn-unused-but-set-parameters-cpp.cpp
clang/test/SemaCXX/warn-unused-but-set-variables-cpp.cpp

Modified: 
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p12.cpp
clang/test/CodeGen/2007-10-30-Volatile.c
clang/test/CodeGen/X86/x86_32-xsave.c
clang/test/CodeGen/X86/x86_64-xsave.c
clang/test/CodeGen/builtins-arm.c
clang/test/CodeGen/builtins-riscv.c
clang/test/FixIt/fixit.cpp
clang/test/Misc/warning-wall.c
clang/test/Sema/shift.c
clang/test/Sema/vector-gcc-compat.c
clang/test/Sema/vector-gcc-compat.cpp
clang/test/SemaCXX/goto.cpp
clang/test/SemaCXX/shift.cpp
clang/test/SemaCXX/sizeless-1.cpp
clang/test/SemaObjC/foreach.m

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 8544607673c3e..b4be0fcfb454f 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -725,6 +725,7 @@ def UnusedMemberFunction : 
DiagGroup<"unused-member-function",
 def UnusedLabel : DiagGroup<"unused-label">;
 def UnusedLambdaCapture : DiagGroup<"unused-lambda-capture">;
 def UnusedParameter : DiagGroup<"unused-parameter">;
+def UnusedButSetParameter : DiagGroup<"unused-but-set-parameter">;
 def UnusedResult : DiagGroup<"unused-result">;
 def PotentiallyEvaluatedExpression : 
DiagGroup<"potentially-evaluated-expression">;
 def UnevaluatedExpression : DiagGroup<"unevaluated-expression",
@@ -734,6 +735,7 @@ def UnusedValue : DiagGroup<"unused-value", 
[UnusedComparison, UnusedResult,
 def UnusedConstVariable : DiagGroup<"unused-const-variable">;
 def UnusedVariable : DiagGroup<"unused-variable",
[UnusedConstVariable]>;
+def UnusedButSetVariable : DiagGroup<"unused-but-set-variable">;
 def UnusedLocalTypedef : DiagGroup<"unused-local-typedef">;
 def UnusedPropertyIvar :  DiagGroup<"unused-property-ivar">;
 def UnusedGetterReturnValue : DiagGroup<"unused-getter-return-value">;
@@ -875,7 +877,7 @@ def Unused : DiagGroup<"unused",
 // UnusedMemberFunction, (clean-up llvm before 
enabling)
 UnusedPrivateField, UnusedLambdaCapture,
 UnusedLocalTypedef, UnusedValue, UnusedVariable,
-UnusedPropertyIvar]>,
+UnusedButSetVariable, UnusedPropertyIvar]>,
 DiagCategory<"Unused Entity Issue">;
 
 // Format settings.
@@ -927,6 +929,7 @@ def Extra : DiagGroup<"extra", [
 MissingMethodReturnType,
 SignCompare,
 UnusedParameter,
+UnusedButSetParameter,
 NullPointerArithmetic,
 EmptyInitStatement,
 StringConcatation,

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 80130c2584fe5..cc23fd789d31c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -311,8 +311,12 @@ def note_riscv_repeated_interrupt_attribute : Note<
   "repeated RISC-V 'interrupt' attribute is here">;
 def warn_unused_parameter : Warning<"unused parameter %0">,
   InGroup, DefaultIgnore;
+def warn_unused_but_set_parameter : Warning<"parameter %0 set but not used">,
+  InGroup, DefaultIgnore;
 def warn_unused_variable : Warning<"unused variable %0">,
   InGroup, DefaultIgnore;
+def warn_unused_but_set_variable : Warning<"variable %0 set but not used">,
+  InGroup, DefaultIgnore;
 def warn_unused_local_typedef : Warning<
   "unused %select{typedef|type alias}0 %1">,
   InGroup, DefaultIgnore;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 65469418936cb..347a909d99574 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1518,6 +1518,11 @@ class Sema final {
 
   bool WarnedStackExhausted = false;
 
+  /// Increment when we find a reference; decrement when we find an ignored
+  /// assignment.  Ultimately the value is 0 if every reference is an ignored
+  /// 

[clang] b270fd5 - Revert "[clang] Change builtin object size when subobject is invalid"

2021-01-20 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2021-01-20T11:03:34-08:00
New Revision: b270fd59f0a86fe737853abc43e76b9d29a67eea

URL: 
https://github.com/llvm/llvm-project/commit/b270fd59f0a86fe737853abc43e76b9d29a67eea
DIFF: 
https://github.com/llvm/llvm-project/commit/b270fd59f0a86fe737853abc43e76b9d29a67eea.diff

LOG: Revert "[clang] Change builtin object size when subobject is invalid"

This reverts commit 275f30df8ad6de75e1f29e4b33eaeb67686caf0d.

As noted on the code review (https://reviews.llvm.org/D92892), this
change causes us to reject valid code in a few cases. Reverting so we
have more time to figure out what the right fix{es are, is} here.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/CodeGen/object-size.c

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index b153e22259f7..56181bbe1166 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11408,9 +11408,9 @@ static bool tryEvaluateBuiltinObjectSize(const Expr *E, 
unsigned Type,
   return false;
   }
 
-  // If we point outside of the object, there are no accessible bytes.
-  if (LVal.getLValueOffset().isNegative() ||
-  ((Type & 1) && !LVal.Designator.isValidSubobject())) {
+  // If we point to before the start of the object, there are no accessible
+  // bytes.
+  if (LVal.getLValueOffset().isNegative()) {
 Size = 0;
 return true;
   }

diff  --git a/clang/test/CodeGen/object-size.c 
b/clang/test/CodeGen/object-size.c
index dbf286138454..ff54b11a0f04 100644
--- a/clang/test/CodeGen/object-size.c
+++ b/clang/test/CodeGen/object-size.c
@@ -310,7 +310,7 @@ void test24() {
 void test25() {
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN((void*)0x1000, 0);
-  // CHECK: store i32 0
+  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN((void*)0x1000, 1);
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 true, i1 true, i1
   gi = OBJECT_SIZE_BUILTIN((void*)0x1000, 2);
@@ -321,7 +321,7 @@ void test25() {
 
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN((void*)0 + 0x1000, 0);
-  // CHECK: store i32 0
+  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN((void*)0 + 0x1000, 1);
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 true, i1 true, i1
   gi = OBJECT_SIZE_BUILTIN((void*)0 + 0x1000, 2);
@@ -337,7 +337,7 @@ void test26() {
 
   // CHECK: store i32 316
   gi = OBJECT_SIZE_BUILTIN([1].v[11], 0);
-  // CHECK: store i32 0
+  // CHECK: store i32 312
   gi = OBJECT_SIZE_BUILTIN([1].v[12], 1);
   // CHECK: store i32 308
   gi = OBJECT_SIZE_BUILTIN([1].v[13], 2);
@@ -433,7 +433,7 @@ void test29(struct DynStructVar *dv, struct DynStruct0 *d0,
 
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN(d0->snd, 0);
-  // CHECK: store i32 0
+  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN(d0->snd, 1);
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 true, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN(d0->snd, 2);
@@ -518,7 +518,7 @@ void test31() {
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN([9].snd[0], 1);
 
-  // CHECK: store i32 0
+  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN([9].snd[0], 1);
 
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1



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


[clang] 275f30d - [clang] Change builtin object size when subobject is invalid

2021-01-07 Thread George Burgess IV via cfe-commits

Author: Jeffrey T Mott
Date: 2021-01-07T12:34:07-08:00
New Revision: 275f30df8ad6de75e1f29e4b33eaeb67686caf0d

URL: 
https://github.com/llvm/llvm-project/commit/275f30df8ad6de75e1f29e4b33eaeb67686caf0d
DIFF: 
https://github.com/llvm/llvm-project/commit/275f30df8ad6de75e1f29e4b33eaeb67686caf0d.diff

LOG: [clang] Change builtin object size when subobject is invalid

Motivating example:

```
  struct { int v[10]; } t[10];

  __builtin_object_size(
  [0].v[11], // access past end of subobject
  1// request remaining bytes of closest surrounding
   // subobject
  );
```

In GCC, this returns 0. https://godbolt.org/z/7TeGs7

In current clang, however, this returns 356, the number of bytes
remaining in the whole variable, as if the `type` was 0 instead of 1.
https://godbolt.org/z/6Kffox

This patch checks for the specific case where we're requesting a
subobject's size (type 1) but the subobject is invalid.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/CodeGen/object-size.c

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 56181bbe1166..b153e22259f7 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11408,9 +11408,9 @@ static bool tryEvaluateBuiltinObjectSize(const Expr *E, 
unsigned Type,
   return false;
   }
 
-  // If we point to before the start of the object, there are no accessible
-  // bytes.
-  if (LVal.getLValueOffset().isNegative()) {
+  // If we point outside of the object, there are no accessible bytes.
+  if (LVal.getLValueOffset().isNegative() ||
+  ((Type & 1) && !LVal.Designator.isValidSubobject())) {
 Size = 0;
 return true;
   }

diff  --git a/clang/test/CodeGen/object-size.c 
b/clang/test/CodeGen/object-size.c
index ff54b11a0f04..dbf286138454 100644
--- a/clang/test/CodeGen/object-size.c
+++ b/clang/test/CodeGen/object-size.c
@@ -310,7 +310,7 @@ void test24() {
 void test25() {
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN((void*)0x1000, 0);
-  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
+  // CHECK: store i32 0
   gi = OBJECT_SIZE_BUILTIN((void*)0x1000, 1);
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 true, i1 true, i1
   gi = OBJECT_SIZE_BUILTIN((void*)0x1000, 2);
@@ -321,7 +321,7 @@ void test25() {
 
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN((void*)0 + 0x1000, 0);
-  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false, i1 true, 
i1
+  // CHECK: store i32 0
   gi = OBJECT_SIZE_BUILTIN((void*)0 + 0x1000, 1);
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 true, i1 true, i1
   gi = OBJECT_SIZE_BUILTIN((void*)0 + 0x1000, 2);
@@ -337,7 +337,7 @@ void test26() {
 
   // CHECK: store i32 316
   gi = OBJECT_SIZE_BUILTIN([1].v[11], 0);
-  // CHECK: store i32 312
+  // CHECK: store i32 0
   gi = OBJECT_SIZE_BUILTIN([1].v[12], 1);
   // CHECK: store i32 308
   gi = OBJECT_SIZE_BUILTIN([1].v[13], 2);
@@ -433,7 +433,7 @@ void test29(struct DynStructVar *dv, struct DynStruct0 *d0,
 
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN(d0->snd, 0);
-  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
+  // CHECK: store i32 0
   gi = OBJECT_SIZE_BUILTIN(d0->snd, 1);
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 true, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN(d0->snd, 2);
@@ -518,7 +518,7 @@ void test31() {
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
   gi = OBJECT_SIZE_BUILTIN([9].snd[0], 1);
 
-  // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1
+  // CHECK: store i32 0
   gi = OBJECT_SIZE_BUILTIN([9].snd[0], 1);
 
   // CHECK: call i64 @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true, 
i1



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


[clang] ba18bc4 - [Sema] adds -Wfree-nonheap-object member var checks

2020-11-02 Thread George Burgess IV via cfe-commits

Author: Christopher Di Bella
Date: 2020-11-02T11:03:28-08:00
New Revision: ba18bc4925d8cbd4a9354629617cbcafbbd48941

URL: 
https://github.com/llvm/llvm-project/commit/ba18bc4925d8cbd4a9354629617cbcafbbd48941
DIFF: 
https://github.com/llvm/llvm-project/commit/ba18bc4925d8cbd4a9354629617cbcafbbd48941.diff

LOG: [Sema] adds -Wfree-nonheap-object member var checks

Checks to make sure that stdlib's (std::)free is being appropriately
used for member variables.

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

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/warn-free-nonheap-object.c
clang/test/Sema/warn-free-nonheap-object.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3d5e2d70d8ca..bad9b14c1fa2 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -10107,19 +10107,9 @@ void Sema::CheckStrncatArguments(const CallExpr *CE,
 }
 
 namespace {
-void CheckFreeArgumentsAddressof(Sema , const std::string ,
- const UnaryOperator *UnaryExpr) {
-  if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
-return;
-
-  const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr());
-  if (Lvalue == nullptr)
-return;
-
-  const auto *Var = dyn_cast(Lvalue->getDecl());
-  if (Var == nullptr)
-return;
-
+void CheckFreeArgumentsOnLvalue(Sema , const std::string ,
+const UnaryOperator *UnaryExpr,
+const VarDecl *Var) {
   StorageClass Class = Var->getStorageClass();
   if (Class == StorageClass::SC_Extern ||
   Class == StorageClass::SC_PrivateExtern ||
@@ -10130,6 +10120,27 @@ void CheckFreeArgumentsAddressof(Sema , const 
std::string ,
   << CalleeName << Var;
 }
 
+void CheckFreeArgumentsOnLvalue(Sema , const std::string ,
+const UnaryOperator *UnaryExpr, const Decl *D) 
{
+  if (const auto *Field = dyn_cast(D))
+S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
+<< CalleeName << Field;
+}
+
+void CheckFreeArgumentsAddressof(Sema , const std::string ,
+ const UnaryOperator *UnaryExpr) {
+  if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
+return;
+
+  if (const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr()))
+if (const auto *Var = dyn_cast(Lvalue->getDecl()))
+  return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
+
+  if (const auto *Lvalue = dyn_cast(UnaryExpr->getSubExpr()))
+return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
+  Lvalue->getMemberDecl());
+}
+
 void CheckFreeArgumentsStackArray(Sema , const std::string ,
   const DeclRefExpr *Lvalue) {
   if (!Lvalue->getType()->isArrayType())

diff  --git a/clang/test/Sema/warn-free-nonheap-object.c 
b/clang/test/Sema/warn-free-nonheap-object.c
index e149e8349571..1618a559b431 100644
--- a/clang/test/Sema/warn-free-nonheap-object.c
+++ b/clang/test/Sema/warn-free-nonheap-object.c
@@ -4,6 +4,11 @@ typedef __SIZE_TYPE__ size_t;
 void *malloc(size_t);
 void free(void *);
 
+struct S {
+  int I;
+  char *P;
+};
+
 int GI;
 void test() {
   {
@@ -31,4 +36,9 @@ void test() {
 free(A);  // expected-warning {{attempt to call free on non-heap object 
'A'}}
 free(); // expected-warning {{attempt to call free on non-heap object 
'A'}}
   }
+  {
+struct S s;
+free(); // expected-warning {{attempt to call free on non-heap object 
'I'}}
+free(s.P);
+  }
 }

diff  --git a/clang/test/Sema/warn-free-nonheap-object.cpp 
b/clang/test/Sema/warn-free-nonheap-object.cpp
index 0578d9e9cd66..9347709a23ca 100644
--- a/clang/test/Sema/warn-free-nonheap-object.cpp
+++ b/clang/test/Sema/warn-free-nonheap-object.cpp
@@ -13,10 +13,25 @@ int GI;
 struct S {
   operator char *() { return ptr; }
 
+  void CFree() {
+::free(); // expected-warning {{attempt to call free on non-heap 
object 'ptr'}}
+::free();   // expected-warning {{attempt to call free on non-heap 
object 'I'}}
+::free(ptr);
+  }
+
+  void CXXFree() {
+std::free(); // expected-warning {{attempt to call std::free on 
non-heap object 'ptr'}}
+std::free();   // expected-warning {{attempt to call std::free on 
non-heap object 'I'}}
+std::free(ptr);
+  }
+
 private:
   char *ptr = (char *)std::malloc(10);
+  static int I;
 };
 
+int S::I = 0;
+
 void test1() {
   {
 free(); // expected-warning {{attempt to call free on non-heap object 
'GI'}}
@@ -51,6 +66,10 @@ void test1() {
 free(s);
 free(); // expected-warning {{attempt to call free on non-heap object 
's'}}
   }
+  {
+S s;
+s.CFree();
+  }
 }
 
 void test2() {
@@ -87,4 +106,8 @@ void test2() {
 std::free(s);
 std::free(); // expected-warning {{attempt to call std::free on non-heap 

[clang] 425a83a - [Sema] adds basic -Wfree-nonheap-object functionality

2020-10-28 Thread George Burgess IV via cfe-commits

Author: Christopher Di Bella
Date: 2020-10-28T16:18:23-07:00
New Revision: 425a83a5f069eb1a692145d2c92e6d3bfe564a62

URL: 
https://github.com/llvm/llvm-project/commit/425a83a5f069eb1a692145d2c92e6d3bfe564a62
DIFF: 
https://github.com/llvm/llvm-project/commit/425a83a5f069eb1a692145d2c92e6d3bfe564a62.diff

LOG: [Sema] adds basic -Wfree-nonheap-object functionality

Checks to make sure that stdlib's (std::)free is being appropriately
used. Presently checks for the following misuses:

- free(_object)
- free(stack_array)

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

Added: 
clang/test/Sema/warn-free-nonheap-object.c
clang/test/Sema/warn-free-nonheap-object.cpp

Modified: 
clang/include/clang/Basic/Builtins.def
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/Decl.cpp
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index b2876ed6cbed..45ea7d9a3551 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -913,6 +913,7 @@ LIBBUILTIN(exit, "vi","fr","stdlib.h", 
ALL_LANGUAGES)
 LIBBUILTIN(_Exit, "vi",   "fr","stdlib.h", ALL_LANGUAGES)
 LIBBUILTIN(malloc, "v*z", "f", "stdlib.h", ALL_LANGUAGES)
 LIBBUILTIN(realloc, "v*v*z",  "f", "stdlib.h", ALL_LANGUAGES)
+LIBBUILTIN(free,"vv*","f", "stdlib.h", ALL_LANGUAGES)
 LIBBUILTIN(strtod, "dcC*c**", "f", "stdlib.h", ALL_LANGUAGES)
 LIBBUILTIN(strtof, "fcC*c**", "f", "stdlib.h", ALL_LANGUAGES)
 LIBBUILTIN(strtold, "LdcC*c**",   "f", "stdlib.h", ALL_LANGUAGES)

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index e1d20fbcb433..97cacbe32e5a 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7539,6 +7539,11 @@ def err_incomplete_object_call : Error<
 def warn_condition_is_assignment : Warning<"using the result of an "
   "assignment as a condition without parentheses">,
   InGroup;
+def warn_free_nonheap_object
+  : Warning<"attempt to call %0 on non-heap object %1">,
+InGroup>,
+DefaultIgnore; // FIXME: add to -Wall after sufficient testing
+
 // Completely identical except off by default.
 def warn_condition_is_idiomatic_assignment : Warning<"using the result "
   "of an assignment as a condition without parentheses">,

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 3c3190680acf..61ee743a7ab9 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -12400,6 +12400,8 @@ class Sema final {
   void CheckStrncatArguments(const CallExpr *Call,
  IdentifierInfo *FnName);
 
+  void CheckFreeArguments(const CallExpr *E);
+
   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
   SourceLocation ReturnLoc,
   bool isObjCMethod = false,

diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 80bc22b61b70..b4f92d77dd5d 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -3959,6 +3959,9 @@ unsigned FunctionDecl::getMemoryFunctionKind() const {
   case Builtin::BIbzero:
 return Builtin::BIbzero;
 
+  case Builtin::BIfree:
+return Builtin::BIfree;
+
   default:
 if (isExternC()) {
   if (FnInfo->isStr("memset"))
@@ -3987,6 +3990,9 @@ unsigned FunctionDecl::getMemoryFunctionKind() const {
 return Builtin::BIstrlen;
   else if (FnInfo->isStr("bzero"))
 return Builtin::BIbzero;
+} else if (isInStdNamespace()) {
+  if (FnInfo->isStr("free"))
+return Builtin::BIfree;
 }
 break;
   }

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e87adf8ff302..3d5e2d70d8ca 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4496,16 +4496,24 @@ bool Sema::CheckFunctionCall(FunctionDecl *FDecl, 
CallExpr *TheCall,
 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
 
   unsigned CMId = FDecl->getMemoryFunctionKind();
-  if (CMId == 0)
-return false;
 
   // Handle memory setting and copying functions.
-  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
+  switch (CMId) {
+  case 0:
+return false;
+  case Builtin::BIstrlcpy: // fallthrough
+  case Builtin::BIstrlcat:
 CheckStrlcpycatArguments(TheCall, FnInfo);
-  else if (CMId == Builtin::BIstrncat)
+break;
+  case Builtin::BIstrncat:
 CheckStrncatArguments(TheCall, FnInfo);
-  else
+break;
+  case Builtin::BIfree:
+CheckFreeArguments(TheCall);
+break;
+  default:
 CheckMemaccessArguments(TheCall, CMId, FnInfo);
+  }
 
   return false;
 }
@@ -10098,6 +10106,57 

[clang-tools-extra] 9d40fb8 - Allow to specify macro names for android-comparison-in-temp-failure-retry

2020-10-01 Thread George Burgess IV via cfe-commits

Author: Florian Mayer
Date: 2020-10-01T10:09:26-07:00
New Revision: 9d40fb808fd0fbd33eb3b50c20d7f402de5db91e

URL: 
https://github.com/llvm/llvm-project/commit/9d40fb808fd0fbd33eb3b50c20d7f402de5db91e
DIFF: 
https://github.com/llvm/llvm-project/commit/9d40fb808fd0fbd33eb3b50c20d7f402de5db91e.diff

LOG: Allow to specify macro names for android-comparison-in-temp-failure-retry

Some projects do not use the TEMP_FAILURE_RETRY macro but define their
own one, as not to depend on glibc / Bionic details. By allowing the
user to override the list of macros, these projects can also benefit
from this check.

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/android-comparison-in-temp-failure-retry-custom-macro.c

Modified: 
clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.h

clang-tools-extra/docs/clang-tidy/checks/android-comparison-in-temp-failure-retry.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp 
b/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
index 188d44da51d81..c7b9896c64f81 100644
--- a/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
+++ b/clang-tools-extra/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
@@ -18,32 +18,17 @@ namespace clang {
 namespace tidy {
 namespace android {
 
-namespace {
-AST_MATCHER(BinaryOperator, isRHSATempFailureRetryArg) {
-  if (!Node.getBeginLoc().isMacroID())
-return false;
-
-  const SourceManager  = Finder->getASTContext().getSourceManager();
-  if 
(!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getBeginLoc()))
-return false;
-
-  const LangOptions  = Finder->getASTContext().getLangOpts();
-  SourceLocation LocStart = Node.getBeginLoc();
-  while (LocStart.isMacroID()) {
-SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart);
-Token Tok;
-if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts,
-/*IgnoreWhiteSpace=*/true)) {
-  if (Tok.getKind() == tok::raw_identifier &&
-  Tok.getRawIdentifier() == "TEMP_FAILURE_RETRY")
-return true;
-}
+ComparisonInTempFailureRetryCheck::ComparisonInTempFailureRetryCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  RawRetryList(Options.get("RetryMacros", "TEMP_FAILURE_RETRY")) {
+  StringRef(RawRetryList).split(RetryMacros, ",", -1, false);
+}
 
-LocStart = Invocation;
-  }
-  return false;
+void ComparisonInTempFailureRetryCheck::storeOptions(
+ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "RetryMacros", RawRetryList);
 }
-} // namespace
 
 void ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) {
   // Both glibc's and Bionic's TEMP_FAILURE_RETRY macros structurally look 
like:
@@ -63,15 +48,43 @@ void 
ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   binaryOperator(hasOperatorName("="),
  hasRHS(ignoringParenCasts(
- 
binaryOperator(isComparisonOperator()).bind("binop"))),
- isRHSATempFailureRetryArg()),
+ 
binaryOperator(isComparisonOperator()).bind("inner"
+  .bind("outer"),
   this);
 }
 
 void ComparisonInTempFailureRetryCheck::check(
 const MatchFinder::MatchResult ) {
-  const auto  = *Result.Nodes.getNodeAs("binop");
-  diag(BinOp.getOperatorLoc(), "top-level comparison in TEMP_FAILURE_RETRY");
+  StringRef RetryMacroName;
+  const auto  = *Result.Nodes.getNodeAs("outer");
+  if (!Node.getBeginLoc().isMacroID())
+return;
+
+  const SourceManager  = *Result.SourceManager;
+  if 
(!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getBeginLoc()))
+return;
+
+  const LangOptions  = Result.Context->getLangOpts();
+  SourceLocation LocStart = Node.getBeginLoc();
+  while (LocStart.isMacroID()) {
+SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart);
+Token Tok;
+if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts,
+/*IgnoreWhiteSpace=*/true)) {
+  if (Tok.getKind() == tok::raw_identifier &&
+  llvm::is_contained(RetryMacros, Tok.getRawIdentifier())) {
+RetryMacroName = Tok.getRawIdentifier();
+break;
+  }
+}
+
+LocStart = Invocation;
+  }
+  if (RetryMacroName.empty())
+return;
+
+  const auto  = *Result.Nodes.getNodeAs("inner");
+  diag(Inner.getOperatorLoc(), "top-level comparison in %0") << RetryMacroName;
 
   // FIXME: FixIts would be nice, but potentially nontrivial when nested macros
   // happen, e.g. `TEMP_FAILURE_RETRY(IS_ZERO(foo()))`

diff  --git 

[clang] 9490808 - [CodeGen] fix inline builtin-related breakage from D78162

2020-04-16 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2020-04-16T11:54:10-07:00
New Revision: 94908088a831141cfbdd15fc5837dccf30cfeeb6

URL: 
https://github.com/llvm/llvm-project/commit/94908088a831141cfbdd15fc5837dccf30cfeeb6
DIFF: 
https://github.com/llvm/llvm-project/commit/94908088a831141cfbdd15fc5837dccf30cfeeb6.diff

LOG: [CodeGen] fix inline builtin-related breakage from D78162

In cases where we have multiple decls of an inline builtin, we may need
to go hunting for the one with a definition when setting function
attributes.

An additional test-case was provided on
https://github.com/ClangBuiltLinux/linux/issues/979

Added: 
clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 1243ce50ec8d..ce28d741225e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1909,9 +1909,15 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 
llvm::Function *F,
  F->setSection(SA->getName());
 
   // If we plan on emitting this inline builtin, we can't treat it as a 
builtin.
-  if (FD->isInlineBuiltinDeclaration() && shouldEmitFunction(FD)) {
-F->addAttribute(llvm::AttributeList::FunctionIndex,
-llvm::Attribute::NoBuiltin);
+  if (FD->isInlineBuiltinDeclaration()) {
+const FunctionDecl *FDBody;
+bool HasBody = FD->hasBody(FDBody);
+(void)HasBody;
+assert(HasBody && "Inline builtin declarations should always have an "
+  "available body!");
+if (shouldEmitFunction(FDBody))
+  F->addAttribute(llvm::AttributeList::FunctionIndex,
+  llvm::Attribute::NoBuiltin);
   }
 
   if (FD->isReplaceableGlobalAllocationFunction()) {

diff  --git a/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp 
b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp
new file mode 100644
index ..d27aa9c53413
--- /dev/null
+++ b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple i686-linux-gnu -std=c++11 -S -emit-llvm -o - %s | 
FileCheck %s
+//
+// Regression test for the issue reported at
+// https://reviews.llvm.org/D78162#1986104
+
+typedef unsigned long size_t;
+
+extern "C" __inline__ __attribute__((__gnu_inline__)) void *memcpy(void *a, 
const void *b, unsigned c) {
+  return __builtin_memcpy(a, b, c);
+}
+void *memcpy(void *, const void *, unsigned);
+
+// CHECK-LABEL: define void @_Z1av
+void a() { (void)memcpy; }
+
+// CHECK-NOT: nobuiltin



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


[clang] 2dd17ff - [CodeGen] only add nobuiltin to inline builtins if we'll emit them

2020-04-15 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2020-04-15T11:05:22-07:00
New Revision: 2dd17ff08165e6118e70f00e22b2c36d2d4e0a9a

URL: 
https://github.com/llvm/llvm-project/commit/2dd17ff08165e6118e70f00e22b2c36d2d4e0a9a
DIFF: 
https://github.com/llvm/llvm-project/commit/2dd17ff08165e6118e70f00e22b2c36d2d4e0a9a.diff

LOG: [CodeGen] only add nobuiltin to inline builtins if we'll emit them

There are some inline builtin definitions that we can't emit
(isTriviallyRecursive & callers go into why). Marking these
nobuiltin is only useful if we actually emit the body, so don't mark
these as such unless we _do_ plan on emitting that.

This suboptimality was encountered in Linux (see some discussion on
D71082, and https://github.com/ClangBuiltLinux/linux/issues/979).

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

Added: 
clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 39aa5c1c512f..73a3212bcd47 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1908,7 +1908,8 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 
llvm::Function *F,
   else if (const auto *SA = FD->getAttr())
  F->setSection(SA->getName());
 
-  if (FD->isInlineBuiltinDeclaration()) {
+  // If we plan on emitting this inline builtin, we can't treat it as a 
builtin.
+  if (FD->isInlineBuiltinDeclaration() && shouldEmitFunction(FD)) {
 F->addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoBuiltin);
   }

diff  --git a/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c 
b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c
new file mode 100644
index ..b4c1376c5bb3
--- /dev/null
+++ b/clang/test/CodeGen/memcpy-no-nobuiltin-if-not-emitted.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -S -emit-llvm -o - %s | 
FileCheck %s
+//
+// Verifies that clang doesn't mark an inline builtin definition as `nobuiltin`
+// if the builtin isn't emittable.
+
+typedef unsigned long size_t;
+
+// always_inline is used so clang will emit this body. Otherwise, we need >=
+// -O1.
+#define AVAILABLE_EXTERNALLY extern inline __attribute__((always_inline)) \
+__attribute__((gnu_inline))
+
+AVAILABLE_EXTERNALLY void *memcpy(void *a, const void *b, size_t c) {
+  return __builtin_memcpy(a, b, c);
+}
+
+// CHECK-LABEL: define void @foo
+void foo(void *a, const void *b, size_t c) {
+  // Clang will always _emit_ this as memcpy. LLVM turns it into @llvm.memcpy
+  // later on if optimizations are enabled.
+  // CHECK: call i8* @memcpy
+  memcpy(a, b, c);
+}
+
+// CHECK-NOT: nobuiltin



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


[clang] 91c8c74 - [CodeGen] clarify a comment; NFC

2020-04-14 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2020-04-14T14:33:01-07:00
New Revision: 91c8c74180ced4b82da02f2544f3978f72003d37

URL: 
https://github.com/llvm/llvm-project/commit/91c8c74180ced4b82da02f2544f3978f72003d37
DIFF: 
https://github.com/llvm/llvm-project/commit/91c8c74180ced4b82da02f2544f3978f72003d37.diff

LOG: [CodeGen] clarify a comment; NFC

Prompted by discussion on https://reviews.llvm.org/D78148.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 0f56dcb3e26c..39aa5c1c512f 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2796,8 +2796,8 @@ bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
 
   // PR9614. Avoid cases where the source code is lying to us. An available
   // externally function should have an equivalent function somewhere else,
-  // but a function that calls itself is clearly not equivalent to the real
-  // implementation.
+  // but a function that calls itself through asm label/`__builtin_` trickery 
is
+  // clearly not equivalent to the real implementation.
   // This happens in glibc's btowc and in some configure checks.
   return !isTriviallyRecursive(F);
 }



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


[clang] 380a645 - [ASTMatchers] work around a miscompile; "NFC"

2019-11-22 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2019-11-22T20:11:16-08:00
New Revision: 380a6452b2e98d9c34828503edf8032f6b4c82d3

URL: 
https://github.com/llvm/llvm-project/commit/380a6452b2e98d9c34828503edf8032f6b4c82d3
DIFF: 
https://github.com/llvm/llvm-project/commit/380a6452b2e98d9c34828503edf8032f6b4c82d3.diff

LOG: [ASTMatchers] work around a miscompile; "NFC"

I chatted with Reid offline, and we agreed that having a workaround here
would be appropriate until PR43879 is resolved.

The given transformation Works On My Machine(TM), and should hopefully
hold more broadly, but my fingers are crossed nonetheless. :)

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index c51fd630e64b..8a103f3d89a3 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -904,8 +904,9 @@ bool MatchASTVisitor::objcClassIsDerivedFrom(
 if (Base.matches(*ClassDecl, this, Builder))
   return true;
 
+// Not `return false` as a temporary workaround for PR43879.
 if (Directly)
-  return false;
+  break;
   }
 
   return false;



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


[clang-tools-extra] 9f13a03 - clang-tidy: don't use an absolute path in a test

2019-11-22 Thread George Burgess IV via cfe-commits

Author: George Burgess IV
Date: 2019-11-22T18:13:18-08:00
New Revision: 9f13a032b6d7f720caf6511d0c9b1b6b7d2bbc67

URL: 
https://github.com/llvm/llvm-project/commit/9f13a032b6d7f720caf6511d0c9b1b6b7d2bbc67
DIFF: 
https://github.com/llvm/llvm-project/commit/9f13a032b6d7f720caf6511d0c9b1b6b7d2bbc67.diff

LOG: clang-tidy: don't use an absolute path in a test

`run_clang_tidy` takes a regular expression to match against
compile_commands.json entries. If we pass "%t/test.cpp" and "%t" expands
to anything that includes chars that a regex treats specially, like '+',
this test starts failing.

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp 
b/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp
index 31c4d681ebc9..0d0e41e022ae 100644
--- a/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/run-clang-tidy.cpp
@@ -9,7 +9,7 @@
 // RUN: echo "value:   '0'" >> %t/.clang-tidy
 // RUN: cp "%s" "%t/test.cpp"
 // RUN: cd "%t"
-// RUN: not %run_clang_tidy "%t/test.cpp"
+// RUN: not %run_clang_tidy "test.cpp"
 
 int main()
 {



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


r367947 - [Sema] attempt to appease buildbots after r367940

2019-08-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Aug  5 16:19:15 2019
New Revision: 367947

URL: http://llvm.org/viewvc/llvm-project?rev=367947=rev
Log:
[Sema] attempt to appease buildbots after r367940

A buildbot got angry about this new test, with error messages like:

warn-nullchar-nullptr.c Line 16: use of undeclared identifier 'u'

It looks like this `u'c'` syntax was introduced in C11; I'm guessing
some bots may default to something before that. Let's see if explicitly
specifying the standard version makes it happy...

Modified:
cfe/trunk/test/Sema/warn-nullchar-nullptr.c

Modified: cfe/trunk/test/Sema/warn-nullchar-nullptr.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-nullchar-nullptr.c?rev=367947=367946=367947=diff
==
--- cfe/trunk/test/Sema/warn-nullchar-nullptr.c (original)
+++ cfe/trunk/test/Sema/warn-nullchar-nullptr.c Mon Aug  5 16:19:15 2019
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s -std=c11
 
 int test1(int *a) {
   return a == '\0'; // expected-warning {{comparing a pointer to a null 
character constant; did you mean to compare to (void *)0?}}


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


r367940 - [Sema] Add -Wpointer-compare

2019-08-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Aug  5 15:15:40 2019
New Revision: 367940

URL: http://llvm.org/viewvc/llvm-project?rev=367940=rev
Log:
[Sema] Add -Wpointer-compare

This patch adds a warning that diagnoses comparisons of pointers to
'\0'. This is often indicative of a bug (e.g. the user might've
forgotten to dereference the pointer).

Patch by Elaina Guan!

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

Added:
cfe/trunk/test/Sema/warn-nullchar-nullptr.c
Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=367940=367939=367940=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Mon Aug  5 15:15:40 
2019
@@ -3296,6 +3296,10 @@ def warn_impcast_bool_to_null_pointer :
 def warn_non_literal_null_pointer : Warning<
 "expression which evaluates to zero treated as a null pointer constant of "
 "type %0">, InGroup;
+def warn_pointer_compare : Warning<
+"comparing a pointer to a null character constant; did you mean "
+"to compare to %select{NULL|(void *)0}0?">,
+InGroup>;
 def warn_impcast_null_pointer_to_integer : Warning<
 "implicit conversion of %select{NULL|nullptr}0 constant to %1">,
 InGroup;

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=367940=367939=367940=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Mon Aug  5 15:15:40 2019
@@ -10022,6 +10022,7 @@ public:
   QualType CheckShiftOperands( // C99 6.5.7
 ExprResult , ExprResult , SourceLocation Loc,
 BinaryOperatorKind Opc, bool IsCompAssign = false);
+  void CheckPtrComparisonWithNullChar(ExprResult , ExprResult );
   QualType CheckCompareOperands( // C99 6.5.8/9
   ExprResult , ExprResult , SourceLocation Loc,
   BinaryOperatorKind Opc);

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=367940=367939=367940=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Mon Aug  5 15:15:40 2019
@@ -10443,6 +10443,32 @@ static QualType checkArithmeticOrEnumera
   return S.Context.getLogicalOperationType();
 }
 
+void Sema::CheckPtrComparisonWithNullChar(ExprResult , ExprResult ) {
+  if (!NullE.get()->getType()->isAnyPointerType())
+return;
+  int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
+  if (!E.get()->getType()->isAnyPointerType() &&
+  E.get()->isNullPointerConstant(Context,
+ Expr::NPC_ValueDependentIsNotNull) ==
+Expr::NPCK_ZeroExpression) {
+if (const auto *CL = dyn_cast(E.get())) {
+  if (CL->getValue() == 0)
+Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
+<< NullValue
+<< FixItHint::CreateReplacement(E.get()->getExprLoc(),
+NullValue ? "NULL" : "(void *)0");
+} else if (const auto *CE = dyn_cast(E.get())) {
+TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
+QualType T = 
Context.getCanonicalType(TI->getType()).getUnqualifiedType();
+if (T == Context.CharTy)
+  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
+  << NullValue
+  << FixItHint::CreateReplacement(E.get()->getExprLoc(),
+  NullValue ? "NULL" : "(void 
*)0");
+  }
+  }
+}
+
 // C99 6.5.8, C++ [expr.rel]
 QualType Sema::CheckCompareOperands(ExprResult , ExprResult ,
 SourceLocation Loc,
@@ -10476,6 +10502,10 @@ QualType Sema::CheckCompareOperands(Expr
   }
 
   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
+  if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
+CheckPtrComparisonWithNullChar(LHS, RHS);
+CheckPtrComparisonWithNullChar(RHS, LHS);
+  }
 
   // Handle vector comparisons separately.
   if (LHS.get()->getType()->isVectorType() ||

Added: cfe/trunk/test/Sema/warn-nullchar-nullptr.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-nullchar-nullptr.c?rev=367940=auto
==
--- cfe/trunk/test/Sema/warn-nullchar-nullptr.c (added)
+++ cfe/trunk/test/Sema/warn-nullchar-nullptr.c Mon Aug  5 15:15:40 2019
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s
+
+int test1(int *a) {
+  return a == '\0'; // 

r367067 - [Sema] add -Walloca to flag uses of `alloca`

2019-07-25 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Jul 25 15:23:40 2019
New Revision: 367067

URL: http://llvm.org/viewvc/llvm-project?rev=367067=rev
Log:
[Sema] add -Walloca to flag uses of `alloca`

This CL adds an optional warning to diagnose uses of the
`__builtin_alloca` family of functions. The use of these functions is
discouraged by many, so it seems like a good idea to allow clang to warn
about it.

Patch by Elaina Guan!

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

Added:
cfe/trunk/test/Sema/warn-alloca.c
Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaChecking.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=367067=367066=367067=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Jul 25 15:23:40 
2019
@@ -2779,6 +2779,11 @@ def err_no_accessor_for_property : Error
 def err_cannot_find_suitable_accessor : Error<
   "cannot find suitable %select{getter|setter}0 for property %1">;
 
+def warn_alloca : Warning<
+  "use of function %0 is discouraged; there is no way to check for failure but 
"
+  "failure may still occur, resulting in a possibly exploitable security 
vulnerability">,
+  InGroup>, DefaultIgnore;
+
 def warn_alloca_align_alignof : Warning<
   "second argument to __builtin_alloca_with_align is supposed to be in bits">,
   InGroup>;

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=367067=367066=367067=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Thu Jul 25 15:23:40 2019
@@ -1179,6 +1179,10 @@ Sema::CheckBuiltinFunctionCall(FunctionD
   case Builtin::BI__builtin_alloca_with_align:
 if (SemaBuiltinAllocaWithAlign(TheCall))
   return ExprError();
+LLVM_FALLTHROUGH;
+  case Builtin::BI__builtin_alloca:
+Diag(TheCall->getBeginLoc(), diag::warn_alloca)
+<< TheCall->getDirectCallee();
 break;
   case Builtin::BI__assume:
   case Builtin::BI__builtin_assume:

Added: cfe/trunk/test/Sema/warn-alloca.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-alloca.c?rev=367067=auto
==
--- cfe/trunk/test/Sema/warn-alloca.c (added)
+++ cfe/trunk/test/Sema/warn-alloca.c Thu Jul 25 15:23:40 2019
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -DSILENCE -fsyntax-only -verify -Wall %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Walloca %s
+
+#ifdef SILENCE
+  // expected-no-diagnostics
+#endif
+
+void test1(int a) {
+  __builtin_alloca(a);
+#ifndef SILENCE
+  // expected-warning@-2 {{use of function '__builtin_alloca' is discouraged; 
there is no way to check for failure but failure may still occur, resulting in 
a possibly exploitable security vulnerability}}
+#endif
+}
+
+void test2(int a) {
+  __builtin_alloca_with_align(a, 32);
+#ifndef SILENCE
+  // expected-warning@-2 {{use of function '__builtin_alloca_with_align' is 
discouraged; there is no way to check for failure but failure may still occur, 
resulting in a possibly exploitable security vulnerability}}
+#endif
+}


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


r366276 - Fix a typo in target features

2019-07-16 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Jul 16 15:32:17 2019
New Revision: 366276

URL: http://llvm.org/viewvc/llvm-project?rev=366276=rev
Log:
Fix a typo in target features

There was a slight typo in r364352 that ended up causing our backend to
complain on some x86 Android builds. This CL fixes that.

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp
cfe/trunk/test/Driver/clang-translation.c

Modified: cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp?rev=366276=366275=366276=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Arch/X86.cpp Tue Jul 16 15:32:17 2019
@@ -135,7 +135,7 @@ void x86::getX86TargetFeatures(const Dri
 if (ArchType == llvm::Triple::x86_64) {
   Features.push_back("+sse4.2");
   Features.push_back("+popcnt");
-  Features.push_back("+mcx16");
+  Features.push_back("+cx16");
 } else
   Features.push_back("+ssse3");
   }

Modified: cfe/trunk/test/Driver/clang-translation.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/clang-translation.c?rev=366276=366275=366276=diff
==
--- cfe/trunk/test/Driver/clang-translation.c (original)
+++ cfe/trunk/test/Driver/clang-translation.c Tue Jul 16 15:32:17 2019
@@ -318,7 +318,7 @@
 // ANDROID-X86_64: "-target-cpu" "x86-64"
 // ANDROID-X86_64: "-target-feature" "+sse4.2"
 // ANDROID-X86_64: "-target-feature" "+popcnt"
-// ANDROID-X86_64: "-target-feature" "+mcx16"
+// ANDROID-X86_64: "-target-feature" "+cx16"
 
 // RUN: %clang -target mips-linux-gnu -### -S %s 2>&1 | \
 // RUN: FileCheck -check-prefix=MIPS %s


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


r364104 - clang-format a block; NFC

2019-06-21 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Jun 21 13:49:47 2019
New Revision: 364104

URL: http://llvm.org/viewvc/llvm-project?rev=364104=rev
Log:
clang-format a block; NFC

The indentation of the return here was off, and confusing as a result.
Cleaned up a bit extra while I was in the area.

Modified:
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=364104=364103=364104=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Fri Jun 21 13:49:47 2019
@@ -5794,28 +5794,29 @@ ExprResult Sema::BuildResolvedCallExpr(E
   // CheckBuiltinFunctionCall below just after creation of the call expression.
   const FunctionType *FuncT = nullptr;
   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
-   retry:
+  retry:
 if (const PointerType *PT = Fn->getType()->getAs()) {
   // C99 6.5.2.2p1 - "The expression that denotes the called function shall
   // have type pointer to function".
   FuncT = PT->getPointeeType()->getAs();
   if (!FuncT)
 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
-   << Fn->getType() << Fn->getSourceRange());
+ << Fn->getType() << Fn->getSourceRange());
 } else if (const BlockPointerType *BPT =
- Fn->getType()->getAs()) {
+   Fn->getType()->getAs()) {
   FuncT = BPT->getPointeeType()->castAs();
 } else {
   // Handle calls to expressions of unknown-any type.
   if (Fn->getType() == Context.UnknownAnyTy) {
 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
-if (rewrite.isInvalid()) return ExprError();
+if (rewrite.isInvalid())
+  return ExprError();
 Fn = rewrite.get();
 goto retry;
   }
 
-return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
-  << Fn->getType() << Fn->getSourceRange());
+  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
+   << Fn->getType() << Fn->getSourceRange());
 }
   }
 


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


r363346 - [Targets] Move soft-float-abi filtering to `initFeatureMap`

2019-06-13 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Jun 13 17:35:17 2019
New Revision: 363346

URL: http://llvm.org/viewvc/llvm-project?rev=363346=rev
Log:
[Targets] Move soft-float-abi filtering to `initFeatureMap`

ARM has a special target feature called soft-float-abi. This feature is
special, since we get it passed to us explicitly in the frontend, but
filter it out before it can land in any target feature strings in LLVM
IR.

__attribute__((target(""))) doesn't quite filter these features out
properly, so today, we get warnings about soft-float-abi being an
unknown feature from the backend.

This CL has us filter soft-float-abi out at a slightly different point,
so we don't end up passing these invalid features to the backend.

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

Added:
cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c
Modified:
cfe/trunk/lib/Basic/Targets/ARM.cpp
cfe/trunk/lib/Basic/Targets/ARM.h

Modified: cfe/trunk/lib/Basic/Targets/ARM.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/ARM.cpp?rev=363346=363345=363346=diff
==
--- cfe/trunk/lib/Basic/Targets/ARM.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/ARM.cpp Thu Jun 13 17:35:17 2019
@@ -323,6 +323,8 @@ ARMTargetInfo::ARMTargetInfo(const llvm:
 this->MCountName = Opts.EABIVersion == llvm::EABI::GNU
? "\01__gnu_mcount_nc"
: "\01mcount";
+
+  SoftFloatABI = llvm::is_contained(Opts.FeaturesAsWritten, "+soft-float-abi");
 }
 
 StringRef ARMTargetInfo::getABI() const { return ABI; }
@@ -385,12 +387,21 @@ bool ARMTargetInfo::initFeatureMap(
 
   // Convert user-provided arm and thumb GNU target attributes to
   // [-|+]thumb-mode target features respectively.
-  std::vector UpdatedFeaturesVec(FeaturesVec);
-  for (auto  : UpdatedFeaturesVec) {
-if (Feature.compare("+arm") == 0)
-  Feature = "-thumb-mode";
-else if (Feature.compare("+thumb") == 0)
-  Feature = "+thumb-mode";
+  std::vector UpdatedFeaturesVec;
+  for (const auto  : FeaturesVec) {
+// Skip soft-float-abi; it's something we only use to initialize a bit of
+// class state, and is otherwise unrecognized.
+if (Feature == "+soft-float-abi")
+  continue;
+
+StringRef FixedFeature;
+if (Feature == "+arm")
+  FixedFeature = "-thumb-mode";
+else if (Feature == "+thumb")
+  FixedFeature = "+thumb-mode";
+else
+  FixedFeature = Feature;
+UpdatedFeaturesVec.push_back(FixedFeature.str());
   }
 
   return TargetInfo::initFeatureMap(Features, Diags, CPU, UpdatedFeaturesVec);
@@ -405,7 +416,8 @@ bool ARMTargetInfo::handleTargetFeatures
   Crypto = 0;
   DSP = 0;
   Unaligned = 1;
-  SoftFloat = SoftFloatABI = false;
+  SoftFloat = false;
+  // Note that SoftFloatABI is initialized in our constructor.
   HWDiv = 0;
   DotProd = 0;
   HasFloat16 = true;
@@ -415,8 +427,6 @@ bool ARMTargetInfo::handleTargetFeatures
   for (const auto  : Features) {
 if (Feature == "+soft-float") {
   SoftFloat = true;
-} else if (Feature == "+soft-float-abi") {
-  SoftFloatABI = true;
 } else if (Feature == "+vfp2sp" || Feature == "+vfp2d16sp" ||
Feature == "+vfp2" || Feature == "+vfp2d16") {
   FPU |= VFP2FPU;
@@ -510,11 +520,6 @@ bool ARMTargetInfo::handleTargetFeatures
   else if (FPMath == FP_VFP)
 Features.push_back("-neonfp");
 
-  // Remove front-end specific options which the backend handles differently.
-  auto Feature = llvm::find(Features, "+soft-float-abi");
-  if (Feature != Features.end())
-Features.erase(Feature);
-
   return true;
 }
 

Modified: cfe/trunk/lib/Basic/Targets/ARM.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/ARM.h?rev=363346=363345=363346=diff
==
--- cfe/trunk/lib/Basic/Targets/ARM.h (original)
+++ cfe/trunk/lib/Basic/Targets/ARM.h Thu Jun 13 17:35:17 2019
@@ -124,6 +124,12 @@ public:
  StringRef CPU,
  const std::vector ) const override;
 
+  bool isValidFeatureName(StringRef Feature) const override {
+// We pass soft-float-abi in as a -target-feature, but the backend figures
+// this out through other means.
+return Feature != "soft-float-abi";
+  }
+
   bool handleTargetFeatures(std::vector ,
 DiagnosticsEngine ) override;
 

Added: cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c?rev=363346=auto
==
--- cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c (added)
+++ cfe/trunk/test/CodeGen/arm-soft-float-abi-filtering.c Thu Jun 13 17:35:17 
2019
@@ -0,0 +1,9 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -emit-llvm -o - -triple arm-none-linux-gnueabi 

[clang-tools-extra] r362673 - android: add a close-on-exec check on pipe()

2019-06-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Jun  5 22:21:45 2019
New Revision: 362673

URL: http://llvm.org/viewvc/llvm-project?rev=362673=rev
Log:
android: add a close-on-exec check on pipe()

On Android, pipe() is better to be replaced by pipe2() with O_CLOEXEC
flag to avoid file descriptor leakage.

Patch by Jian Cai!

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

Added:
clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp
clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/android-cloexec-pipe.rst
clang-tools-extra/trunk/test/clang-tidy/android-cloexec-pipe.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=362673=362672=362673=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Wed Jun  5 
22:21:45 2019
@@ -20,6 +20,7 @@
 #include "CloexecInotifyInitCheck.h"
 #include "CloexecMemfdCreateCheck.h"
 #include "CloexecOpenCheck.h"
+#include "CloexecPipeCheck.h"
 #include "CloexecPipe2Check.h"
 #include "CloexecSocketCheck.h"
 #include "ComparisonInTempFailureRetryCheck.h"
@@ -50,6 +51,7 @@ public:
 CheckFactories.registerCheck(
 "android-cloexec-memfd-create");
 CheckFactories.registerCheck("android-cloexec-open");
+CheckFactories.registerCheck("android-cloexec-pipe");
 CheckFactories.registerCheck("android-cloexec-pipe2");
 CheckFactories.registerCheck("android-cloexec-socket");
 CheckFactories.registerCheck(

Modified: clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt?rev=362673=362672=362673=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt Wed Jun  5 
22:21:45 2019
@@ -14,6 +14,7 @@ add_clang_library(clangTidyAndroidModule
   CloexecInotifyInitCheck.cpp
   CloexecMemfdCreateCheck.cpp
   CloexecOpenCheck.cpp
+  CloexecPipeCheck.cpp
   CloexecPipe2Check.cpp
   CloexecSocketCheck.cpp
   ComparisonInTempFailureRetryCheck.cpp

Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp?rev=362673=auto
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.cpp Wed Jun  5 
22:21:45 2019
@@ -0,0 +1,37 @@
+//===--- CloexecPipeCheck.cpp - 
clang-tidy-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CloexecPipeCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+void CloexecPipeCheck::registerMatchers(MatchFinder *Finder) {
+  registerMatchersImpl(Finder,
+   functionDecl(returns(isInteger()), hasName("pipe"),
+hasParameter(0, 
hasType(pointsTo(isInteger());
+}
+
+void CloexecPipeCheck::check(const MatchFinder::MatchResult ) {
+  std::string ReplacementText =
+  (Twine("pipe2(") + getSpellingArg(Result, 0) + ", O_CLOEXEC)").str();
+
+  replaceFunc(
+  Result,
+  "prefer pipe2() with O_CLOEXEC to avoid leaking file descriptors to 
child processes",
+  ReplacementText);
+}
+
+} // namespace android
+} // namespace tidy
+} // namespace clang

Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h?rev=362673=auto
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h (added)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipeCheck.h Wed Jun  5 
22:21:45 2019
@@ -0,0 +1,34 @@
+//===--- CloexecPipeCheck.h - clang-tidy-*- C++ 
-*-===//
+//
+// Part of the LLVM Project, 

[clang-tools-extra] r362672 - android: add a close-on-exec check on pipe2()

2019-06-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Jun  5 22:21:39 2019
New Revision: 362672

URL: http://llvm.org/viewvc/llvm-project?rev=362672=rev
Log:
android: add a close-on-exec check on pipe2()

On Android, pipe2() is better to set O_CLOEXEC flag to avoid file
descriptor leakage.

Patch by Jian Cai!

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

Added:
clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp
clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h
clang-tools-extra/trunk/docs/clang-tidy/checks/android-cloexec-pipe2.rst
clang-tools-extra/trunk/test/clang-tidy/android-cloexec-pipe2.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=362672=362671=362672=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Wed Jun  5 
22:21:39 2019
@@ -20,6 +20,7 @@
 #include "CloexecInotifyInitCheck.h"
 #include "CloexecMemfdCreateCheck.h"
 #include "CloexecOpenCheck.h"
+#include "CloexecPipe2Check.h"
 #include "CloexecSocketCheck.h"
 #include "ComparisonInTempFailureRetryCheck.h"
 
@@ -49,6 +50,7 @@ public:
 CheckFactories.registerCheck(
 "android-cloexec-memfd-create");
 CheckFactories.registerCheck("android-cloexec-open");
+CheckFactories.registerCheck("android-cloexec-pipe2");
 CheckFactories.registerCheck("android-cloexec-socket");
 CheckFactories.registerCheck(
 "android-comparison-in-temp-failure-retry");

Modified: clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt?rev=362672=362671=362672=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt Wed Jun  5 
22:21:39 2019
@@ -14,6 +14,7 @@ add_clang_library(clangTidyAndroidModule
   CloexecInotifyInitCheck.cpp
   CloexecMemfdCreateCheck.cpp
   CloexecOpenCheck.cpp
+  CloexecPipe2Check.cpp
   CloexecSocketCheck.cpp
   ComparisonInTempFailureRetryCheck.cpp
 

Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp?rev=362672=auto
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.cpp Wed Jun  5 
22:21:39 2019
@@ -0,0 +1,33 @@
+//===--- CloexecPipe2Check.cpp - 
clang-tidy===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CloexecPipe2Check.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+void CloexecPipe2Check::registerMatchers(MatchFinder *Finder) {
+  registerMatchersImpl(Finder,
+   functionDecl(returns(isInteger()), hasName("pipe2"),
+hasParameter(0, 
hasType(pointsTo(isInteger(,
+hasParameter(1, hasType(isInteger();
+}
+
+void CloexecPipe2Check::check(const MatchFinder::MatchResult ) {
+  insertMacroFlag(Result, /*MacroFlag=*/"O_CLOEXEC", /*ArgPos=*/1);
+}
+
+} // namespace android
+} // namespace tidy
+} // namespace clang

Added: clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h?rev=362672=auto
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h (added)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecPipe2Check.h Wed Jun  5 
22:21:39 2019
@@ -0,0 +1,34 @@
+//===--- CloexecPipe2Check.h - clang-tidy*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: 

[clang-tools-extra] r361457 - Remove unnecessary const NFC

2019-05-22 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed May 22 19:52:39 2019
New Revision: 361457

URL: http://llvm.org/viewvc/llvm-project?rev=361457=rev
Log:
Remove unnecessary const NFC

It's uncommon to rely on temporary lifetime extension when having a
regular, non-`const&` value behaves identically. Since `Twine::str`
and `buildFixMsgForStringFlag` both return regular `std::string`s,
there's seemingly no point in having `const&` here.

Modified:
clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp
clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp
clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp?rev=361457=361456=361457=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecAcceptCheck.cpp Wed May 
22 19:52:39 2019
@@ -29,7 +29,7 @@ void CloexecAcceptCheck::registerMatcher
 }
 
 void CloexecAcceptCheck::check(const MatchFinder::MatchResult ) {
-  const std::string  =
+  std::string ReplacementText =
   (Twine("accept4(") + getSpellingArg(Result, 0) + ", " +
getSpellingArg(Result, 1) + ", " + getSpellingArg(Result, 2) +
", SOCK_CLOEXEC)")

Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp?rev=361457=361456=361457=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecCheck.cpp Wed May 22 
19:52:39 2019
@@ -90,7 +90,7 @@ void CloexecCheck::insertStringFlag(
   if (!ModeStr || (ModeStr->getString().find(Mode) != StringRef::npos))
 return;
 
-  const std::string  = buildFixMsgForStringFlag(
+  std::string ReplacementText = buildFixMsgForStringFlag(
   ModeArg, *Result.SourceManager, Result.Context->getLangOpts(), Mode);
 
   diag(ModeArg->getBeginLoc(), "use %0 mode '%1' to set O_CLOEXEC")

Modified: clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp?rev=361457=361456=361457=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/CloexecDupCheck.cpp Wed May 22 
19:52:39 2019
@@ -23,7 +23,7 @@ void CloexecDupCheck::registerMatchers(M
 }
 
 void CloexecDupCheck::check(const MatchFinder::MatchResult ) {
-  const std::string  =
+  std::string ReplacementText =
   (Twine("fcntl(") + getSpellingArg(Result, 0) + ", F_DUPFD_CLOEXEC)")
   .str();
 


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


r357290 - Various fixes and additions to creduce-clang-crash.py

2019-03-29 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Mar 29 10:50:43 2019
New Revision: 357290

URL: http://llvm.org/viewvc/llvm-project?rev=357290=rev
Log:
Various fixes and additions to creduce-clang-crash.py

Some more additions to the script - mainly reducing the clang args after
the creduce run by removing them one by one and seeing if the crash
reproduces. Other things:

- remove the --crash flag when "fatal error" occurs
- fixed to read stack trace functions from the top
- run creduce on a copy of the original file

Patch by Amy Huang!

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

Modified:
cfe/trunk/utils/creduce-clang-crash.py

Modified: cfe/trunk/utils/creduce-clang-crash.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=357290=357289=357290=diff
==
--- cfe/trunk/utils/creduce-clang-crash.py (original)
+++ cfe/trunk/utils/creduce-clang-crash.py Fri Mar 29 10:50:43 2019
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@ import shutil
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,339 @@ def check_cmd(cmd_name, cmd_dir, cmd_pat
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+def quote_cmd(cmd):
+  return ' '.join(pipes.quote(arg) for arg in cmd)
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = 

r356636 - creduce-clang-crash.py: preprocess file + reduce commandline

2019-03-20 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar 20 18:01:53 2019
New Revision: 356636

URL: http://llvm.org/viewvc/llvm-project?rev=356636=rev
Log:
creduce-clang-crash.py: preprocess file + reduce commandline

This CL causes our creduce-clang-crash.py util to:

- try to preprocess the file before reducing
- try to remove some command line arguments
- now require a llvm bin directory, since the generated crash script
  doesn't have an absolute path for clang

It also marks it as executable, since I forgot to do that in the last
commit. :)

Patch by Amy Huang!

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

Modified:
cfe/trunk/utils/creduce-clang-crash.py

Modified: cfe/trunk/utils/creduce-clang-crash.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=356636=356635=356636=diff
==
--- cfe/trunk/utils/creduce-clang-crash.py (original)
+++ cfe/trunk/utils/creduce-clang-crash.py Wed Mar 20 18:01:53 2019
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,108 +9,232 @@ import stat
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
+  for arg in cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+new_clang = check_cmd('clang', llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
 
-  # Get crash output
-  p = subprocess.Popen(build_script,
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  return all(msg in crash_output for msg in expected_output)
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
-
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
+
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output,
+   file_to_reduce):
+  filename = os.path.basename(file_to_reduce)
+  if filename not in crash_cmd:
+sys.exit("ERROR: expected %s to be in the crash command" % filename)
+
+  # Replace all instances of file_to_reduce with a command line variable
+  output = ['#!/bin/bash',
+'if [ -z "$1" ] ; then',
+'  f=%s' % (pipes.quote(filename)),
+'else',
+'  f="$1"',
+'fi']
+  cmd = ['$f' if s == filename else s for s in crash_cmd]
+
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+ 

r355944 - Add a creduce script for clang crashes

2019-03-12 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Mar 12 10:48:53 2019
New Revision: 355944

URL: http://llvm.org/viewvc/llvm-project?rev=355944=rev
Log:
Add a creduce script for clang crashes

This CL adds a script that calls C-Reduce on an input file and given the
clang crash script, which is used to generate an interestingness test
for C-Reduce.

Patch by Amy Huang!

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

Added:
cfe/trunk/utils/creduce-clang-crash.py

Added: cfe/trunk/utils/creduce-clang-crash.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=355944=auto
==
--- cfe/trunk/utils/creduce-clang-crash.py (added)
+++ cfe/trunk/utils/creduce-clang-crash.py Tue Mar 12 10:48:53 2019
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+"""Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Requires C-Reduce and not (part of LLVM utils) to be installed.
+"""
+
+from argparse import ArgumentParser
+import os
+import re
+import stat
+import sys
+import subprocess
+import pipes
+from distutils.spawn import find_executable
+
+def create_test(build_script, llvm_not):
+  """
+  Create an interestingness test from the crash output.
+  Return as a string.
+  """
+  # Get clang call from build script
+  # Assumes the call is the last line of the script
+  with open(build_script) as f:
+cmd = f.readlines()[-1].rstrip('\n\r')
+
+  # Get crash output
+  p = subprocess.Popen(build_script,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
+
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
+  cmd))
+
+  # Add messages from crash output to the test
+  # If there is an Assertion failure, use that; otherwise use the
+  # last five stack trace functions
+  assertion_re = r'Assertion `([^\']+)\' failed'
+  assertion_match = re.search(assertion_re, crash_output)
+  if assertion_match:
+msg = assertion_match.group(1)
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+  else:
+stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
+matches = re.findall(stacktrace_re, crash_output)
+del matches[:-5]
+output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+
+  return output
+
+def main():
+  parser = ArgumentParser(description=__doc__)
+  parser.add_argument('build_script', type=str, nargs=1,
+  help='Name of the script that generates the crash.')
+  parser.add_argument('file_to_reduce', type=str, nargs=1,
+  help='Name of the file to be reduced.')
+  parser.add_argument('-o', '--output', dest='output', type=str,
+  help='Name of the output file for the reduction. 
Optional.')
+  parser.add_argument('--llvm-not', dest='llvm_not', type=str,
+  help="The path to the llvm-not executable. "
+  "Required if 'not' is not in PATH environment.");
+  parser.add_argument('--creduce', dest='creduce', type=str,
+  help="The path to the C-Reduce executable. "
+  "Required if 'creduce' is not in PATH environment.");
+  args = parser.parse_args()
+
+  build_script = os.path.abspath(args.build_script[0])
+  file_to_reduce = os.path.abspath(args.file_to_reduce[0])
+  llvm_not = (find_executable(args.llvm_not) if args.llvm_not else
+  find_executable('not'))
+  creduce = (find_executable(args.creduce) if args.creduce else
+ find_executable('creduce'))
+
+  if not os.path.isfile(build_script):
+print(("ERROR: input file '%s' does not exist") % build_script)
+return 1
+
+  if not os.path.isfile(file_to_reduce):
+print(("ERROR: input file '%s' does not exist") % file_to_reduce)
+return 1
+
+  if not llvm_not:
+parser.print_help()
+return 1
+
+  if not creduce:
+parser.print_help()
+return 1
+
+  # Write interestingness test to file
+  test_contents = create_test(build_script, llvm_not)
+  testname, _ = os.path.splitext(file_to_reduce)
+  testfile = testname + '.test.sh'
+  with open(testfile, 'w') as f:
+f.write('\n'.join(test_contents))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+  # Confirm that the interestingness test passes
+  try:
+with open(os.devnull, 'w') as devnull:
+  subprocess.check_call(testfile, stdout=devnull)
+  except subprocess.CalledProcessError:
+print("For some reason the interestingness test does not return zero")
+return 1
+
+  # FIXME: try running clang preprocessor first
+
+  try:
+p = subprocess.Popen([creduce, testfile, file_to_reduce])
+p.communicate()
+  except KeyboardInterrupt:
+# Hack to kill C-Reduce because it jumps into its own pgid
+print('\n\nctrl-c detected, killed creduce')
+p.kill()
+
+if __name__ == 

r338962 - Use Optional instead of unique_ptr; NFC

2018-08-04 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Sat Aug  4 18:37:07 2018
New Revision: 338962

URL: http://llvm.org/viewvc/llvm-project?rev=338962=rev
Log:
Use Optional instead of unique_ptr; NFC

Looks like the only reason we use a unique_ptr here is so that we can
conditionally construct a LogicalErrorHandler. It's a small type, and
Optional can do the same thing with 100% fewer heap allocations.

Modified:
cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp

Modified: cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp?rev=338962=338961=338962=diff
==
--- cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp (original)
+++ cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp Sat Aug  4 18:37:07 2018
@@ -2068,11 +2068,11 @@ AnalysisBasedWarnings::IssueWarnings(sem
   }
 
   // Install the logical handler for -Wtautological-overlap-compare
-  std::unique_ptr LEH;
+  llvm::Optional LEH;
   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
D->getLocStart())) {
-LEH.reset(new LogicalErrorHandler(S));
-AC.getCFGBuildOptions().Observer = LEH.get();
+LEH.emplace(S);
+AC.getCFGBuildOptions().Observer = &*LEH;
   }
 
   // Emit delayed diagnostics.


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


r337796 - Fix unused variable warnings; NFC

2018-07-23 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Jul 23 19:10:53 2018
New Revision: 337796

URL: http://llvm.org/viewvc/llvm-project?rev=337796=rev
Log:
Fix unused variable warnings; NFC

Looks like MTE was previously used for its SourceLoc, but we're now
using a seperate SourceLocation here.

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=337796=337795=337796=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Jul 23 19:10:53 2018
@@ -6774,7 +6774,7 @@ void Sema::checkInitializerLifetime(cons
 }
 
 case LK_MemInitializer: {
-  if (auto *MTE = dyn_cast(L)) {
+  if (isa(L)) {
 // Under C++ DR1696, if a mem-initializer (or a default member
 // initializer used by the absence of one) would lifetime-extend a
 // temporary, the program is ill-formed.
@@ -6833,7 +6833,7 @@ void Sema::checkInitializerLifetime(cons
 }
 
 case LK_New:
-  if (auto *MTE = dyn_cast(L)) {
+  if (isa(L)) {
 Diag(DiagLoc, RK == RK_ReferenceBinding
   ? diag::warn_new_dangling_reference
   : diag::warn_new_dangling_initializer_list)


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


r335927 - [Parse] Make -Wgcc-compat complain about for loop inits in C89

2018-06-28 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Jun 28 14:36:00 2018
New Revision: 335927

URL: http://llvm.org/viewvc/llvm-project?rev=335927=rev
Log:
[Parse] Make -Wgcc-compat complain about for loop inits in C89

While clang allows declarations in for loop init statements in c89 and
gnu89, gcc does not. So, we should probably warn if users care about gcc
compatibility.

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

Added:
cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c
Modified:
cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
cfe/trunk/lib/Parse/ParseStmt.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td?rev=335927=335926=335927=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td Thu Jun 28 14:36:00 
2018
@@ -173,6 +173,9 @@ def warn_attribute_on_function_definitio
 def warn_gcc_attribute_location : Warning<
   "GCC does not allow an attribute in this position on a function 
declaration">, 
   InGroup;
+def warn_gcc_variable_decl_in_for_loop : Warning<
+  "GCC does not allow variable declarations in for loop initializers before "
+  "C99">, InGroup;
 def warn_attribute_no_decl : Warning<
   "attribute %0 ignored, because it is not attached to a declaration">, 
   InGroup;

Modified: cfe/trunk/lib/Parse/ParseStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseStmt.cpp?rev=335927=335926=335927=diff
==
--- cfe/trunk/lib/Parse/ParseStmt.cpp (original)
+++ cfe/trunk/lib/Parse/ParseStmt.cpp Thu Jun 28 14:36:00 2018
@@ -1624,8 +1624,10 @@ StmtResult Parser::ParseForStatement(Sou
 ParenBraceBracketBalancer BalancerRAIIObj(*this);
 
 // Parse declaration, which eats the ';'.
-if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
+if (!C99orCXXorObjC) {   // Use of C99-style for loops in C90 mode?
   Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
+  Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
+}
 
 // In C++0x, "for (T NS:a" might not be a typo for ::
 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;

Added: cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c?rev=335927=auto
==
--- cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c (added)
+++ cfe/trunk/test/Parser/gcc-for-loop-init-compatibility.c Thu Jun 28 14:36:00 
2018
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -std=c89 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=gnu89 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify %s -DC99
+
+#ifdef C99
+// expected-no-diagnostics
+#endif
+
+void foo() {
+#ifndef C99
+  // expected-warning@+2{{GCC does not allow variable declarations in for loop 
initializers before C99}}
+#endif
+  for (int i = 0; i < 10; i++)
+;
+}


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


Re: r333333 - Test commit; please ignore.

2018-05-25 Thread George Burgess IV via cfe-commits
Thanks. :)

On Fri, May 25, 2018, 7:56 PM Richard Smith <rich...@metafoo.co.uk> wrote:

> Congratulations?
>
> On Fri, 25 May 2018, 19:33 George Burgess IV via cfe-commits, <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: gbiv
>> Date: Fri May 25 19:29:14 2018
>> New Revision: 33
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=33=rev
>> Log:
>> Test commit; please ignore.
>>
>> Modified:
>> cfe/trunk/lib/Sema/SemaAttr.cpp
>>
>> Modified: cfe/trunk/lib/Sema/SemaAttr.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=33=32=33=diff
>>
>> ==
>> --- cfe/trunk/lib/Sema/SemaAttr.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri May 25 19:29:14 2018
>> @@ -330,7 +330,7 @@ void Sema::PragmaStack::Act(S
>>  Stack.erase(std::prev(I.base()), Stack.end());
>>}
>>  } else if (!Stack.empty()) {
>> -  // We don't have a label, just pop the last entry.
>> +  // We do not have a label, just pop the last entry.
>>CurrentValue = Stack.back().Value;
>>CurrentPragmaLocation = Stack.back().PragmaLocation;
>>Stack.pop_back();
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r333333 - Test commit; please ignore.

2018-05-25 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri May 25 19:29:14 2018
New Revision: 33

URL: http://llvm.org/viewvc/llvm-project?rev=33=rev
Log:
Test commit; please ignore.

Modified:
cfe/trunk/lib/Sema/SemaAttr.cpp

Modified: cfe/trunk/lib/Sema/SemaAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=33=32=33=diff
==
--- cfe/trunk/lib/Sema/SemaAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri May 25 19:29:14 2018
@@ -330,7 +330,7 @@ void Sema::PragmaStack::Act(S
 Stack.erase(std::prev(I.base()), Stack.end());
   }
 } else if (!Stack.empty()) {
-  // We don't have a label, just pop the last entry.
+  // We do not have a label, just pop the last entry.
   CurrentValue = Stack.back().Value;
   CurrentPragmaLocation = Stack.back().PragmaLocation;
   Stack.pop_back();


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


r333324 - Fix typo + reflow comment; NFC

2018-05-25 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri May 25 16:40:59 2018
New Revision: 24

URL: http://llvm.org/viewvc/llvm-project?rev=24=rev
Log:
Fix typo + reflow comment; NFC

Reflow brings said comment below 80 cols

Modified:
cfe/trunk/include/clang/AST/ASTContext.h

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=24=23=24=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Fri May 25 16:40:59 2018
@@ -1123,7 +1123,7 @@ public:
   /// Return the uniqued reference to the type for an Objective-C
   /// gc-qualified type.
   ///
-  /// The retulting type has a union of the qualifiers from T and the gc
+  /// The resulting type has a union of the qualifiers from T and the gc
   /// attribute.
   QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
 
@@ -1250,9 +1250,9 @@ public:
   /// Returns true iff we need copy/dispose helpers for the given type.
   bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
 
-  /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout 
is set
-  /// to false in this case. If HasByrefExtendedLayout returns true, byref 
variable
-  /// has extended lifetime.
+  /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
+  /// is set to false in this case. If HasByrefExtendedLayout returns true,
+  /// byref variable has extended lifetime.
   bool getByrefLifetime(QualType Ty,
 Qualifiers::ObjCLifetime ,
 bool ) const;


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


[clang-tools-extra] r329759 - [clang-tidy] Add a `android-comparison-in-temp-failure-retry` check

2018-04-10 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Apr 10 14:22:22 2018
New Revision: 329759

URL: http://llvm.org/viewvc/llvm-project?rev=329759=rev
Log:
[clang-tidy] Add a `android-comparison-in-temp-failure-retry` check

This check attempts to catch buggy uses of the `TEMP_FAILURE_RETRY`
macro, which is provided by both Bionic and glibc.

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

Added:

clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp

clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/android-comparison-in-temp-failure-retry.rst

clang-tools-extra/trunk/test/clang-tidy/android-comparison-in-temp-failure-retry.c
Modified:
clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=329759=329758=329759=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Tue Apr 10 
14:22:22 2018
@@ -22,6 +22,7 @@
 #include "CloexecMemfdCreateCheck.h"
 #include "CloexecOpenCheck.h"
 #include "CloexecSocketCheck.h"
+#include "ComparisonInTempFailureRetryCheck.h"
 
 using namespace clang::ast_matchers;
 
@@ -50,6 +51,8 @@ public:
 "android-cloexec-memfd-create");
 CheckFactories.registerCheck("android-cloexec-open");
 CheckFactories.registerCheck("android-cloexec-socket");
+CheckFactories.registerCheck(
+"android-comparison-in-temp-failure-retry");
   }
 };
 

Modified: clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt?rev=329759=329758=329759=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/android/CMakeLists.txt Tue Apr 10 
14:22:22 2018
@@ -15,6 +15,7 @@ add_clang_library(clangTidyAndroidModule
   CloexecMemfdCreateCheck.cpp
   CloexecOpenCheck.cpp
   CloexecSocketCheck.cpp
+  ComparisonInTempFailureRetryCheck.cpp
 
   LINK_LIBS
   clangAST

Added: 
clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp?rev=329759=auto
==
--- 
clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
 (added)
+++ 
clang-tools-extra/trunk/clang-tidy/android/ComparisonInTempFailureRetryCheck.cpp
 Tue Apr 10 14:22:22 2018
@@ -0,0 +1,84 @@
+//===--- ComparisonInTempFailureRetryCheck.cpp - 
clang-tidy===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "../utils/Matchers.h"
+#include "ComparisonInTempFailureRetryCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+namespace {
+AST_MATCHER(BinaryOperator, isRHSATempFailureRetryArg) {
+  if (!Node.getLocStart().isMacroID())
+return false;
+
+  const SourceManager  = Finder->getASTContext().getSourceManager();
+  if 
(!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getLocStart()))
+return false;
+
+  const LangOptions  = Finder->getASTContext().getLangOpts();
+  SourceLocation LocStart = Node.getLocStart();
+  while (LocStart.isMacroID()) {
+SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart);
+Token Tok;
+if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts,
+/*IgnoreWhiteSpace=*/true)) {
+  if (Tok.getKind() == tok::raw_identifier &&
+  Tok.getRawIdentifier() == "TEMP_FAILURE_RETRY")
+return true;
+}
+
+LocStart = Invocation;
+  }
+  return false;
+}
+} // namespace
+
+void ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) {
+  // Both glibc's and Bionic's TEMP_FAILURE_RETRY macros structurally look 
like:
+  //
+  // #define TEMP_FAILURE_RETRY(x) ({ \
+  //typeof(x) y; \
+  //do y = (x); \
+  //while (y == -1 && errno == EINTR); \
+  //y; \
+  // })
+  //
+  

r329652 - [AST] Attempt to fix buildbot warnings + appease MSVC; NFCI

2018-04-09 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Apr  9 18:11:26 2018
New Revision: 329652

URL: http://llvm.org/viewvc/llvm-project?rev=329652=rev
Log:
[AST] Attempt to fix buildbot warnings + appease MSVC; NFCI

GCC 4.8.4 on a bot was warning about `ArgPassingKind` not fitting in
`ArgPassingRestrictions`, which appears to be incorrect, since
`ArgPassingKind` only has three potential values:

"warning: 'clang::RecordDecl::ArgPassingRestrictions' is too small to
hold all values of 'enum clang::RecordDecl::ArgPassingKind'"

Additionally, I remember hearing (though my knowledge may be outdated)
that MSVC won't merge adjacent bitfields if their types are different.

Try to fix both issues by turning these into `uint8_t`s.

Modified:
cfe/trunk/include/clang/AST/Decl.h

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=329652=329651=329652=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Mon Apr  9 18:11:26 2018
@@ -3599,10 +3599,13 @@ private:
   /// Indicates whether this struct is destroyed in the callee. This flag is
   /// meaningless when Microsoft ABI is used since parameters are always
   /// destroyed in the callee.
-  bool ParamDestroyedInCallee : 1;
+  ///
+  /// Please note that MSVC won't merge adjacent bitfields if they don't have
+  /// the same type.
+  uint8_t ParamDestroyedInCallee : 1;
 
   /// Represents the way this type is passed to a function.
-  ArgPassingKind ArgPassingRestrictions : 2;
+  uint8_t ArgPassingRestrictions : 2;
 
 protected:
   RecordDecl(Kind DK, TagKind TK, const ASTContext , DeclContext *DC,
@@ -3691,15 +3694,15 @@ public:
   /// it must have at least one trivial, non-deleted copy or move constructor.
   /// FIXME: This should be set as part of completeDefinition.
   bool canPassInRegisters() const {
-return ArgPassingRestrictions == APK_CanPassInRegs;
+return getArgPassingRestrictions() == APK_CanPassInRegs;
   }
 
   ArgPassingKind getArgPassingRestrictions() const {
-return ArgPassingRestrictions;
+return static_cast(ArgPassingRestrictions);
   }
 
   void setArgPassingRestrictions(ArgPassingKind Kind) {
-ArgPassingRestrictions = Kind;
+ArgPassingRestrictions = static_cast(Kind);
   }
 
   bool isParamDestroyedInCallee() const {


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


[clang-tools-extra] r329428 - [clang-tidy] Sort includes; NFC

2018-04-06 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Apr  6 10:22:36 2018
New Revision: 329428

URL: http://llvm.org/viewvc/llvm-project?rev=329428=rev
Log:
[clang-tidy] Sort includes; NFC

Modified:
clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp

Modified: clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp?rev=329428=329427=329428=diff
==
--- clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/android/AndroidTidyModule.cpp Fri Apr  6 
10:22:36 2018
@@ -13,9 +13,9 @@
 #include "CloexecAccept4Check.h"
 #include "CloexecAcceptCheck.h"
 #include "CloexecCreatCheck.h"
+#include "CloexecDupCheck.h"
 #include "CloexecEpollCreate1Check.h"
 #include "CloexecEpollCreateCheck.h"
-#include "CloexecDupCheck.h"
 #include "CloexecFopenCheck.h"
 #include "CloexecInotifyInit1Check.h"
 #include "CloexecInotifyInitCheck.h"


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


r327945 - Properly construct `inline` members without initializers

2018-03-19 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Mar 19 20:27:44 2018
New Revision: 327945

URL: http://llvm.org/viewvc/llvm-project?rev=327945=rev
Log:
Properly construct `inline` members without initializers

Digging through commit logs, it appears the checks in this block predate
`inline` class variables. With them, we fail to emit dynamic
initializers for members that don't have an explicit initializer, and we
won't go out of our way to instantiate the class denoted by
`Var->getType()`.

Fixes PR35599.

Modified:
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp

Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp?rev=327945=327944=327945=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Mon Mar 19 20:27:44 2018
@@ -4202,7 +4202,9 @@ void Sema::InstantiateVariableInitialize
   Var->setInvalidDecl();
 }
   } else {
-if (Var->isStaticDataMember()) {
+// `inline` variables are a definition and declaration all in one; we won't
+// pick up an initializer from anywhere else.
+if (Var->isStaticDataMember() && !Var->isInline()) {
   if (!Var->isOutOfLine())
 return;
 

Modified: cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp?rev=327945=327944=327945=diff
==
--- cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/cxx1z-inline-variables.cpp Mon Mar 19 20:27:44 
2018
@@ -111,3 +111,29 @@ int e = d;
 // CHECK-NOT: __cxa_guard_acquire(i64* @_ZGV1b)
 // CHECK: call i32 @_Z1fv
 // CHECK-NOT: __cxa_guard_release(i64* @_ZGV1b)
+
+namespace PR35599 {
+struct Marker1 {};
+struct Marker2 {};
+
+template 
+struct Foo {
+  struct Bar { Bar(); };
+  inline static Bar bar;
+};
+
+void run() {
+  // All we want here are ODR uses. Anything that requires that the type is
+  // complete is uninteresting.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-value"
+  Foo::bar;
+#pragma clang diagnostic pop
+  static_cast(Foo::bar);
+}
+
+// CHECK-LABEL: define {{.*}}global_var_init{{.*}}comdat
+// CHECK: call void @_ZN7PR355993FooINS_7Marker1EE3BarC1Ev
+// CHECK-LABEL: define {{.*}}global_var_init{{.*}}comdat
+// CHECK: call void @_ZN7PR355993FooINS_7Marker2EE3BarC1Ev
+}


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


r327229 - [CodeGen] Eagerly emit lifetime.end markers for calls

2018-03-10 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Sat Mar 10 15:06:31 2018
New Revision: 327229

URL: http://llvm.org/viewvc/llvm-project?rev=327229=rev
Log:
[CodeGen] Eagerly emit lifetime.end markers for calls

In C, we'll wait until the end of the scope to clean up aggregate
temporaries used for returns from calls. This means in cases like:

{
  // Assuming that `Bar` is large enough to warrant indirect returns
  struct Bar b = {};
  b = foo();
  b = foo();
  b = foo();
  b = foo();
}

...We'll allocate space for 5 Bars on the stack (`b`, and 4
temporaries). This becomes painful in things like large switch
statements.

If cleaning up sooner is trivial, we should do it.

Added:
cfe/trunk/test/CodeGen/aggregate-assign-call.c
Modified:
cfe/trunk/lib/CodeGen/CGExprAgg.cpp

Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprAgg.cpp?rev=327229=327228=327229=diff
==
--- cfe/trunk/lib/CodeGen/CGExprAgg.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprAgg.cpp Sat Mar 10 15:06:31 2018
@@ -23,6 +23,7 @@
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/IntrinsicInst.h"
 using namespace clang;
 using namespace CodeGen;
 
@@ -48,7 +49,7 @@ class AggExprEmitter : public StmtVisito
 
   // Calls `Fn` with a valid return value slot, potentially creating a 
temporary
   // to do so. If a temporary is created, an appropriate copy into `Dest` will
-  // be emitted.
+  // be emitted, as will lifetime markers.
   //
   // The given function should take a ReturnValueSlot, and return an RValue 
that
   // points to said slot.
@@ -250,16 +251,28 @@ void AggExprEmitter::withReturnValueSlot
  (RequiresDestruction && !Dest.getAddress().isValid());
 
   Address RetAddr = Address::invalid();
+
+  EHScopeStack::stable_iterator LifetimeEndBlock;
+  llvm::Value *LifetimeSizePtr = nullptr;
+  llvm::IntrinsicInst *LifetimeStartInst = nullptr;
   if (!UseTemp) {
 RetAddr = Dest.getAddress();
   } else {
 RetAddr = CGF.CreateMemTemp(RetTy);
 uint64_t Size =
 CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
-if (llvm::Value *LifetimeSizePtr =
-CGF.EmitLifetimeStart(Size, RetAddr.getPointer()))
+LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAddr.getPointer());
+if (LifetimeSizePtr) {
+  LifetimeStartInst =
+  cast(std::prev(Builder.GetInsertPoint()));
+  assert(LifetimeStartInst->getIntrinsicID() ==
+ llvm::Intrinsic::lifetime_start &&
+ "Last insertion wasn't a lifetime.start?");
+
   CGF.pushFullExprCleanup(
   NormalEHLifetimeMarker, RetAddr, LifetimeSizePtr);
+  LifetimeEndBlock = CGF.EHStack.stable_begin();
+}
   }
 
   RValue Src =
@@ -268,9 +281,18 @@ void AggExprEmitter::withReturnValueSlot
   if (RequiresDestruction)
 CGF.pushDestroy(RetTy.isDestructedType(), Src.getAggregateAddress(), 
RetTy);
 
-  if (UseTemp) {
-assert(Dest.getPointer() != Src.getAggregatePointer());
-EmitFinalDestCopy(E->getType(), Src);
+  if (!UseTemp)
+return;
+
+  assert(Dest.getPointer() != Src.getAggregatePointer());
+  EmitFinalDestCopy(E->getType(), Src);
+
+  if (!RequiresDestruction && LifetimeStartInst) {
+// If there's no dtor to run, the copy was the last use of our temporary.
+// Since we're not guaranteed to be in an ExprWithCleanups, clean up
+// eagerly.
+CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
+CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAddr.getPointer());
   }
 }
 

Added: cfe/trunk/test/CodeGen/aggregate-assign-call.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/aggregate-assign-call.c?rev=327229=auto
==
--- cfe/trunk/test/CodeGen/aggregate-assign-call.c (added)
+++ cfe/trunk/test/CodeGen/aggregate-assign-call.c Sat Mar 10 15:06:31 2018
@@ -0,0 +1,101 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O1 -S -emit-llvm -o - %s 
| FileCheck %s --check-prefix=O1
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O0 -S -emit-llvm -o - %s 
| FileCheck %s --check-prefix=O0
+//
+// Ensure that we place appropriate lifetime markers around indirectly returned
+// temporaries, and that the lifetime.ends appear in a timely manner.
+//
+// -O1 is used so lifetime markers actually get emitted.
+
+struct S {
+  int ns[40];
+};
+
+struct S foo(void);
+
+// CHECK-LABEL: define dso_local void @bar
+struct S bar() {
+  // O0-NOT: @llvm.lifetime.start
+  // O0-NOT: @llvm.lifetime.end
+
+  struct S r;
+  // O1: call void @llvm.lifetime.start.p0i8({{[^,]*}}, i8* nonnull 
%[[R_TMP:[^)]+]])
+
+  // O1: call void @llvm.lifetime.start.p0i8({{[^,]*}}, i8* nonnull 
%[[TMP1:[^)]+]])
+  // O1: call void @foo
+  r = foo();
+  // O1: call void @llvm.lifetime.end.p0i8({{[^,]*}}, i8* 

r327192 - [CodeGen] Try to not call a dtor after lifetime.end

2018-03-09 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Mar  9 17:11:17 2018
New Revision: 327192

URL: http://llvm.org/viewvc/llvm-project?rev=327192=rev
Log:
[CodeGen] Try to not call a dtor after lifetime.end

If CodeGenFunction::EmitCall is:
- asked to emit a call with an indirectly returned value,
- given an invalid return value slot, and
- told the return value of the function it's calling is unused

then it'll make its own temporary, and add lifetime markers so that the
temporary's lifetime ends immediately after the call.

The early lifetime.end becomes problematic when we need to run a
destructor on the result of the function.

Instead of unconditionally saying that results of all calls are used
here (which would be correct, but would also cause us to never emit
lifetime markers for these temporaries), we just build our own temporary
to pass in when a dtor has to be run.

Modified:
cfe/trunk/lib/CodeGen/CGExprAgg.cpp
cfe/trunk/test/CodeGenObjC/arc.m

Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprAgg.cpp?rev=327192=327191=327192=diff
==
--- cfe/trunk/lib/CodeGen/CGExprAgg.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprAgg.cpp Fri Mar  9 17:11:17 2018
@@ -37,23 +37,6 @@ class AggExprEmitter : public StmtVisito
   AggValueSlot Dest;
   bool IsResultUnused;
 
-  /// We want to use 'dest' as the return slot except under two
-  /// conditions:
-  ///   - The destination slot requires garbage collection, so we
-  /// need to use the GC API.
-  ///   - The destination slot is potentially aliased.
-  bool shouldUseDestForReturnSlot() const {
-return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
-  }
-
-  ReturnValueSlot getReturnValueSlot() const {
-if (!shouldUseDestForReturnSlot())
-  return ReturnValueSlot();
-
-return ReturnValueSlot(Dest.getAddress(), Dest.isVolatile(),
-   IsResultUnused);
-  }
-
   AggValueSlot EnsureSlot(QualType T) {
 if (!Dest.isIgnored()) return Dest;
 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
@@ -63,6 +46,15 @@ class AggExprEmitter : public StmtVisito
 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
   }
 
+  // Calls `Fn` with a valid return value slot, potentially creating a 
temporary
+  // to do so. If a temporary is created, an appropriate copy into `Dest` will
+  // be emitted.
+  //
+  // The given function should take a ReturnValueSlot, and return an RValue 
that
+  // points to said slot.
+  void withReturnValueSlot(const Expr *E,
+   llvm::function_ref Fn);
+
 public:
   AggExprEmitter(CodeGenFunction , AggValueSlot Dest, bool IsResultUnused)
 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
@@ -242,34 +234,44 @@ bool AggExprEmitter::TypeRequiresGCollec
   return Record->hasObjectMember();
 }
 
-/// \brief Perform the final move to DestPtr if for some reason
-/// getReturnValueSlot() didn't use it directly.
-///
-/// The idea is that you do something like this:
-///   RValue Result = EmitSomething(..., getReturnValueSlot());
-///   EmitMoveFromReturnSlot(E, Result);
-///
-/// If nothing interferes, this will cause the result to be emitted
-/// directly into the return value slot.  Otherwise, a final move
-/// will be performed.
-void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
-  // Push destructor if the result is ignored and the type is a C struct that
-  // is non-trivial to destroy.
-  QualType Ty = E->getType();
-  if (Dest.isIgnored() &&
-  Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
-CGF.pushDestroy(Ty.isDestructedType(), src.getAggregateAddress(), Ty);
-
-  if (shouldUseDestForReturnSlot()) {
-// Logically, Dest.getAddr() should equal Src.getAggregateAddr().
-// The possibility of undef rvalues complicates that a lot,
-// though, so we can't really assert.
-return;
+void AggExprEmitter::withReturnValueSlot(
+const Expr *E, llvm::function_ref EmitCall) {
+  QualType RetTy = E->getType();
+  bool RequiresDestruction =
+  Dest.isIgnored() &&
+  RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
+
+  // If it makes no observable difference, save a memcpy + temporary.
+  //
+  // We need to always provide our own temporary if destruction is required.
+  // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
+  // its lifetime before we have the chance to emit a proper destructor call.
+  bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
+ (RequiresDestruction && !Dest.getAddress().isValid());
+
+  Address RetAddr = Address::invalid();
+  if (!UseTemp) {
+RetAddr = Dest.getAddress();
+  } else {
+RetAddr = CGF.CreateMemTemp(RetTy);
+uint64_t Size =
+CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
+if 

r326988 - [CodeGen] Emit lifetime.ends in both EH and non-EH blocks

2018-03-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar  7 21:32:30 2018
New Revision: 326988

URL: http://llvm.org/viewvc/llvm-project?rev=326988=rev
Log:
[CodeGen] Emit lifetime.ends in both EH and non-EH blocks

Before this, we'd only emit lifetime.ends for these temps in
non-exceptional paths. This potentially made our stack larger than it
needed to be for any code that follows an EH cleanup. e.g. in

```
struct Foo { char cs[32]; };

void escape(void *);

struct Bar { ~Bar() { char cs[64]; escape(cs); } };

Foo getFoo();

void baz() {
  Bar b;
  getFoo();
}
```

baz() would require 96 bytes of stack, since the temporary from getFoo()
only had a lifetime.end on the non-exceptional path.

This also makes us keep hold of the Value* returned by
EmitLifetimeStart, so we don't have to remake it later.

Added:
cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp
Modified:
cfe/trunk/lib/CodeGen/CGCall.cpp

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=326988=326987=326988=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Mar  7 21:32:30 2018
@@ -3790,7 +3790,7 @@ RValue CodeGenFunction::EmitCall(const C
   // If the call returns a temporary with struct return, create a temporary
   // alloca to hold the result, unless one is given to us.
   Address SRetPtr = Address::invalid();
-  size_t UnusedReturnSize = 0;
+  llvm::Value *UnusedReturnSizePtr = nullptr;
   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
 if (!ReturnValue.isNull()) {
   SRetPtr = ReturnValue.getValue();
@@ -3799,8 +3799,7 @@ RValue CodeGenFunction::EmitCall(const C
   if (HaveInsertPoint() && ReturnValue.isUnused()) {
 uint64_t size =
 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
-if (EmitLifetimeStart(size, SRetPtr.getPointer()))
-  UnusedReturnSize = size;
+UnusedReturnSizePtr = EmitLifetimeStart(size, SRetPtr.getPointer());
   }
 }
 if (IRFunctionArgs.hasSRetArg()) {
@@ -4231,6 +4230,15 @@ RValue CodeGenFunction::EmitCall(const C
 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
  llvm::Attribute::NoUnwind);
   }
+
+  // If we made a temporary, be sure to clean up after ourselves. Note that we
+  // can't depend on being inside of an ExprWithCleanups, so we need to 
manually
+  // pop this cleanup later on. Being eager about this is OK, since this
+  // temporary is 'invisible' outside of the callee.
+  if (UnusedReturnSizePtr)
+pushFullExprCleanup(NormalEHLifetimeMarker, SRetPtr,
+ UnusedReturnSizePtr);
+
   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
 
   SmallVector BundleList =
@@ -4284,9 +4292,8 @@ RValue CodeGenFunction::EmitCall(const C
   // insertion point; this allows the rest of IRGen to discard
   // unreachable code.
   if (CS.doesNotReturn()) {
-if (UnusedReturnSize)
-  EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
-  SRetPtr.getPointer());
+if (UnusedReturnSizePtr)
+  PopCleanupBlock();
 
 // Strip away the noreturn attribute to better diagnose unreachable UB.
 if (SanOpts.has(SanitizerKind::Unreachable)) {
@@ -4355,9 +4362,8 @@ RValue CodeGenFunction::EmitCall(const C
 case ABIArgInfo::InAlloca:
 case ABIArgInfo::Indirect: {
   RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
-  if (UnusedReturnSize)
-EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
-SRetPtr.getPointer());
+  if (UnusedReturnSizePtr)
+PopCleanupBlock();
   return ret;
 }
 

Added: cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp?rev=326988=auto
==
--- cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp Wed Mar  7 21:32:30 
2018
@@ -0,0 +1,189 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -o - -emit-llvm -O1 \
+// RUN: -fexceptions -fcxx-exceptions | FileCheck %s
+//
+// We should emit lifetime.ends for these temporaries in both the 'exception'
+// and 'normal' paths in functions.
+//
+// -O1 is necessary to make lifetime markers appear.
+
+struct Large {
+  int cs[32];
+};
+
+Large getLarge();
+
+// Used to ensure we emit invokes.
+struct NontrivialDtor {
+  int i;
+  ~NontrivialDtor();
+};
+
+// CHECK-LABEL: define void @_Z33cleanupsAreEmittedWithoutTryCatchv
+void cleanupsAreEmittedWithoutTryCatch() {
+// CHECK: %[[CLEAN:[^ ]+]] = bitcast %struct.NontrivialDtor* %{{[^ ]+}} to i8*
+// 

r326980 - Fix an unused variable warning; NFC

2018-03-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar  7 18:15:12 2018
New Revision: 326980

URL: http://llvm.org/viewvc/llvm-project?rev=326980=rev
Log:
Fix an unused variable warning; NFC

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

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=326980=326979=326980=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Wed Mar  7 18:15:12 2018
@@ -2466,7 +2466,7 @@ void ExprEngine::VisitCommonDeclRefExpr(
   ProgramPoint::PostLValueKind);
 return;
   }
-  if (const auto* BD = dyn_cast(D)) {
+  if (isa(D)) {
 // FIXME: proper support for bound declarations.
 // For now, let's just prevent crashing.
 return;


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


r326968 - Fix a doc typo; NFC

2018-03-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar  7 16:22:04 2018
New Revision: 326968

URL: http://llvm.org/viewvc/llvm-project?rev=326968=rev
Log:
Fix a doc typo; NFC

Modified:
cfe/trunk/lib/CodeGen/CGExpr.cpp

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=326968=326967=326968=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Wed Mar  7 16:22:04 2018
@@ -187,7 +187,7 @@ RValue CodeGenFunction::EmitAnyExpr(cons
   llvm_unreachable("bad evaluation kind");
 }
 
-/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
+/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
 /// always be accessible even if no aggregate location is provided.
 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
   AggValueSlot AggSlot = AggValueSlot::ignored();


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


r326873 - Remove a placeholder

2018-03-06 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Mar  6 21:02:27 2018
New Revision: 326873

URL: http://llvm.org/viewvc/llvm-project?rev=326873=rev
Log:
Remove a placeholder

...Running tests in the wrong directory will often make them seem to
pass. Oops. :)

Modified:
cfe/trunk/test/CodeGenCXX/alloc-size.cpp

Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/alloc-size.cpp?rev=326873=326872=326873=diff
==
--- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Tue Mar  6 21:02:27 2018
@@ -79,7 +79,7 @@ struct Foo {
 
 void *my_malloc(const Foo &, int N) __attribute__((alloc_size(2)));
 
-// CHECK-LABEL: define i32 lalala
+// CHECK-LABEL: define i32 @_ZN24alloc_size_with_cleanups6testItEv
 int testIt() {
   int *const p = (int *)my_malloc(Foo{}, 3);
   // CHECK: ret i32 3


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


Re: r326766 - [ExprConstant] Look through ExprWithCleanups for `allocsize`

2018-03-06 Thread George Burgess IV via cfe-commits
Relanded in r326872. Thanks!

On Tue, Mar 6, 2018 at 7:03 PM, Nico Weber <tha...@chromium.org> wrote:

> Apologies, I had to revert the change that touched alloc-size.cpp before
> this change in r326862. After that revert, your new test here failed, and
> since I didn't understand how to make it passed, I reverted your change
> in 326869 too. It should hopefully be easy for you to reland it.
>
> On Tue, Mar 6, 2018 at 2:42 AM, George Burgess IV via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: gbiv
>> Date: Mon Mar  5 23:42:36 2018
>> New Revision: 326766
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=326766=rev
>> Log:
>> [ExprConstant] Look through ExprWithCleanups for `allocsize`
>>
>> Modified:
>> cfe/trunk/lib/AST/ExprConstant.cpp
>> cfe/trunk/test/CodeGenCXX/alloc-size.cpp
>>
>> Modified: cfe/trunk/lib/AST/ExprConstant.cpp
>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprCo
>> nstant.cpp?rev=326766=326765=326766=diff
>> 
>> ==
>> --- cfe/trunk/lib/AST/ExprConstant.cpp (original)
>> +++ cfe/trunk/lib/AST/ExprConstant.cpp Mon Mar  5 23:42:36 2018
>> @@ -133,7 +133,11 @@ namespace {
>>
>>  E = E->IgnoreParens();
>>  // If we're doing a variable assignment from e.g. malloc(N), there
>> will
>> -// probably be a cast of some kind. Ignore it.
>> +// probably be a cast of some kind. In exotic cases, we might also
>> see a
>> +// top-level ExprWithCleanups. Ignore them either way.
>> +if (const auto *EC = dyn_cast(E))
>> +  E = EC->getSubExpr()->IgnoreParens();
>> +
>>  if (const auto *Cast = dyn_cast(E))
>>E = Cast->getSubExpr()->IgnoreParens();
>>
>>
>> Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp
>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCX
>> X/alloc-size.cpp?rev=326766=326765=326766=diff
>> 
>> ==
>> --- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original)
>> +++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Mon Mar  5 23:42:36 2018
>> @@ -88,3 +88,15 @@ int callMemberCalloc() {
>>// CHECK: ret i32 32
>>return __builtin_object_size(C().my_calloc(16, 2), 0);
>>  }
>> +
>> +struct D {
>> +  ~D();
>> +  void *my_malloc(int N) __attribute__((alloc_size(2)));
>> +};
>> +
>> +// CHECK-LABEL: define i32 @_Z20callExprWithCleanupsv
>> +int callExprWithCleanups() {
>> +  int *const p = (int *)D().my_malloc(3);
>> +  // CHECK: ret i32 3
>> +  return __builtin_object_size(p, 0);
>> +}
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326872 - Reland r326766 (with a slightly modified test)

2018-03-06 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Mar  6 20:52:34 2018
New Revision: 326872

URL: http://llvm.org/viewvc/llvm-project?rev=326872=rev
Log:
Reland r326766 (with a slightly modified test)

The original revert was done in r326869, since reverting r326602 broke
the test added by this.

The new test should be less dependent on r326602.

Modified:
cfe/trunk/lib/AST/ExprConstant.cpp
cfe/trunk/test/CodeGenCXX/alloc-size.cpp

Modified: cfe/trunk/lib/AST/ExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=326872=326871=326872=diff
==
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)
+++ cfe/trunk/lib/AST/ExprConstant.cpp Tue Mar  6 20:52:34 2018
@@ -133,7 +133,11 @@ namespace {
 
 E = E->IgnoreParens();
 // If we're doing a variable assignment from e.g. malloc(N), there will
-// probably be a cast of some kind. Ignore it.
+// probably be a cast of some kind. In exotic cases, we might also see a
+// top-level ExprWithCleanups. Ignore them either way.
+if (const auto *EC = dyn_cast(E))
+  E = EC->getSubExpr()->IgnoreParens();
+
 if (const auto *Cast = dyn_cast(E))
   E = Cast->getSubExpr()->IgnoreParens();
 

Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/alloc-size.cpp?rev=326872=326871=326872=diff
==
--- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Tue Mar  6 20:52:34 2018
@@ -70,3 +70,19 @@ int testIt() {
  __builtin_object_size(dependent_calloc2(), 0);
 }
 } // namespace templated_alloc_size
+
+// Be sure that an ExprWithCleanups doesn't deter us.
+namespace alloc_size_with_cleanups {
+struct Foo {
+  ~Foo();
+};
+
+void *my_malloc(const Foo &, int N) __attribute__((alloc_size(2)));
+
+// CHECK-LABEL: define i32 lalala
+int testIt() {
+  int *const p = (int *)my_malloc(Foo{}, 3);
+  // CHECK: ret i32 3
+  return __builtin_object_size(p, 0);
+}
+} // namespace alloc_size_with_cleanups


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


r326845 - Fix a typo from r326844; NFC

2018-03-06 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Mar  6 15:09:01 2018
New Revision: 326845

URL: http://llvm.org/viewvc/llvm-project?rev=326845=rev
Log:
Fix a typo from r326844; NFC

Modified:
cfe/trunk/test/CodeGen/64bit-swiftcall.c

Modified: cfe/trunk/test/CodeGen/64bit-swiftcall.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/64bit-swiftcall.c?rev=326845=326844=326845=diff
==
--- cfe/trunk/test/CodeGen/64bit-swiftcall.c (original)
+++ cfe/trunk/test/CodeGen/64bit-swiftcall.c Tue Mar  6 15:09:01 2018
@@ -1033,7 +1033,7 @@ TEST(union_hom_fp_partial2)
 // X86-64-LABEL: take_union_hom_fp_partial2(i64, float)
 // ARM64-LABEL: take_union_hom_fp_partial2(i64, float)
 
-// At one point, we emitted lifetime.ends without a matching lifetime.begin for
+// At one point, we emitted lifetime.ends without a matching lifetime.start for
 // CoerceAndExpanded args. Since we're not performing optimizations, neither
 // intrinsic should be emitted.
 // CHECK-LABEL: define void @no_lifetime_markers


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


r326844 - [CodeGen] Don't emit lifetime.end without lifetime.start

2018-03-06 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Mar  6 15:07:00 2018
New Revision: 326844

URL: http://llvm.org/viewvc/llvm-project?rev=326844=rev
Log:
[CodeGen] Don't emit lifetime.end without lifetime.start

EmitLifetimeStart returns a non-null `size` pointer if it actually
emits a lifetime.start. Later in this function, we use `tempSize`'s
nullness to determine whether or not we should emit a lifetime.end.

Modified:
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/test/CodeGen/64bit-swiftcall.c

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=326844=326843=326844=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Tue Mar  6 15:07:00 2018
@@ -4010,13 +4010,11 @@ RValue CodeGenFunction::EmitCall(const C
 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
 auto scalarAlign = 
CGM.getDataLayout().getPrefTypeAlignment(scalarType);
 
-tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
-
 // Materialize to a temporary.
 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
  CharUnits::fromQuantity(std::max(layout->getAlignment(),
   scalarAlign)));
-EmitLifetimeStart(scalarSize, addr.getPointer());
+tempSize = EmitLifetimeStart(scalarSize, addr.getPointer());
 
 Builder.CreateStore(RV.getScalarVal(), addr);
   }

Modified: cfe/trunk/test/CodeGen/64bit-swiftcall.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/64bit-swiftcall.c?rev=326844=326843=326844=diff
==
--- cfe/trunk/test/CodeGen/64bit-swiftcall.c (original)
+++ cfe/trunk/test/CodeGen/64bit-swiftcall.c Tue Mar  6 15:07:00 2018
@@ -1032,3 +1032,12 @@ typedef union {
 TEST(union_hom_fp_partial2)
 // X86-64-LABEL: take_union_hom_fp_partial2(i64, float)
 // ARM64-LABEL: take_union_hom_fp_partial2(i64, float)
+
+// At one point, we emitted lifetime.ends without a matching lifetime.begin for
+// CoerceAndExpanded args. Since we're not performing optimizations, neither
+// intrinsic should be emitted.
+// CHECK-LABEL: define void @no_lifetime_markers
+void no_lifetime_markers() {
+  // CHECK-NOT: call void @llvm.lifetime.
+  take_int5(return_int5());
+}


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


r326767 - Fix an unused variable warning; NFC

2018-03-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Mar  5 23:45:11 2018
New Revision: 326767

URL: http://llvm.org/viewvc/llvm-project?rev=326767=rev
Log:
Fix an unused variable warning; NFC

Modified:
cfe/trunk/lib/Analysis/CFG.cpp

Modified: cfe/trunk/lib/Analysis/CFG.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/CFG.cpp?rev=326767=326766=326767=diff
==
--- cfe/trunk/lib/Analysis/CFG.cpp (original)
+++ cfe/trunk/lib/Analysis/CFG.cpp Mon Mar  5 23:45:11 2018
@@ -1165,6 +1165,7 @@ void CFGBuilder::consumeConstructionCont
 const ConstructionContextLayer *Layer, CXXConstructExpr *CE) {
   if (const ConstructionContextLayer *PreviouslyStoredLayer =
   ConstructionContextMap.lookup(CE)) {
+(void)PreviouslyStoredLayer;
 // We might have visited this child when we were finding construction
 // contexts within its parents.
 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&


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


r326766 - [ExprConstant] Look through ExprWithCleanups for `allocsize`

2018-03-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Mar  5 23:42:36 2018
New Revision: 326766

URL: http://llvm.org/viewvc/llvm-project?rev=326766=rev
Log:
[ExprConstant] Look through ExprWithCleanups for `allocsize`

Modified:
cfe/trunk/lib/AST/ExprConstant.cpp
cfe/trunk/test/CodeGenCXX/alloc-size.cpp

Modified: cfe/trunk/lib/AST/ExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=326766=326765=326766=diff
==
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)
+++ cfe/trunk/lib/AST/ExprConstant.cpp Mon Mar  5 23:42:36 2018
@@ -133,7 +133,11 @@ namespace {
 
 E = E->IgnoreParens();
 // If we're doing a variable assignment from e.g. malloc(N), there will
-// probably be a cast of some kind. Ignore it.
+// probably be a cast of some kind. In exotic cases, we might also see a
+// top-level ExprWithCleanups. Ignore them either way.
+if (const auto *EC = dyn_cast(E))
+  E = EC->getSubExpr()->IgnoreParens();
+
 if (const auto *Cast = dyn_cast(E))
   E = Cast->getSubExpr()->IgnoreParens();
 

Modified: cfe/trunk/test/CodeGenCXX/alloc-size.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/alloc-size.cpp?rev=326766=326765=326766=diff
==
--- cfe/trunk/test/CodeGenCXX/alloc-size.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/alloc-size.cpp Mon Mar  5 23:42:36 2018
@@ -88,3 +88,15 @@ int callMemberCalloc() {
   // CHECK: ret i32 32
   return __builtin_object_size(C().my_calloc(16, 2), 0);
 }
+
+struct D {
+  ~D();
+  void *my_malloc(int N) __attribute__((alloc_size(2)));
+};
+
+// CHECK-LABEL: define i32 @_Z20callExprWithCleanupsv
+int callExprWithCleanups() {
+  int *const p = (int *)D().my_malloc(3);
+  // CHECK: ret i32 3
+  return __builtin_object_size(p, 0);
+}


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


r326607 - Range-ify a for loop. NFC

2018-03-02 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Mar  2 12:10:38 2018
New Revision: 326607

URL: http://llvm.org/viewvc/llvm-project?rev=326607=rev
Log:
Range-ify a for loop. NFC

Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=326607=326606=326607=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Fri Mar  2 12:10:38 2018
@@ -713,11 +713,8 @@ static void enterBlockScope(CodeGenFunct
 /// kind of cleanup object is a BlockDecl*.
 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) 
{
   assert(E->getNumObjects() != 0);
-  ArrayRef cleanups = E->getObjects();
-  for (ArrayRef::iterator
- i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
-enterBlockScope(*this, *i);
-  }
+  for (const ExprWithCleanups::CleanupObject  : E->getObjects())
+enterBlockScope(*this, C);
 }
 
 /// Find the layout for the given block in a linked list and remove it.


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


r326416 - Remove redundant casts. NFC

2018-02-28 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Feb 28 21:43:23 2018
New Revision: 326416

URL: http://llvm.org/viewvc/llvm-project?rev=326416=rev
Log:
Remove redundant casts. NFC

So I wrote a clang-tidy check to lint out redundant `isa`, `cast`, and
`dyn_cast`s for fun. This is a portion of what it found for clang; I
plan to do similar cleanups in LLVM and other subprojects when I find
time.

Because of the volume of changes, I explicitly avoided making any change
that wasn't highly local and obviously correct to me (e.g. we still have
a number of foo(cast(baz)) that I didn't touch, since overloading
is a thing and the cast did actually change the type -- just up the
class hierarchy).

I also tried to leave the types we were cast<>ing to somewhere nearby,
in cases where it wasn't locally obvious what we were dealing with
before.

Modified:
cfe/trunk/include/clang/AST/DeclCXX.h
cfe/trunk/include/clang/AST/Expr.h
cfe/trunk/include/clang/AST/ExprObjC.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/AST/CXXInheritance.cpp
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/lib/AST/DeclCXX.cpp
cfe/trunk/lib/AST/DeclPrinter.cpp
cfe/trunk/lib/AST/Expr.cpp
cfe/trunk/lib/AST/ExprConstant.cpp
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/lib/AST/MicrosoftCXXABI.cpp
cfe/trunk/lib/AST/MicrosoftMangle.cpp
cfe/trunk/lib/AST/RecordLayoutBuilder.cpp
cfe/trunk/lib/AST/TemplateBase.cpp
cfe/trunk/lib/AST/Type.cpp
cfe/trunk/lib/CodeGen/CGCoroutine.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGObjCGNU.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/lib/CodeGen/CodeGenTypes.cpp
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/lib/Frontend/ASTUnit.cpp
cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp
cfe/trunk/lib/Frontend/Rewrite/RewriteObjC.cpp
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/lib/Sema/SemaCodeComplete.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/lib/Sema/SemaDeclObjC.cpp
cfe/trunk/lib/Sema/SemaExceptionSpec.cpp
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/lib/Sema/SemaObjCProperty.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/Sema/SemaTemplate.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp

Modified: cfe/trunk/include/clang/AST/DeclCXX.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclCXX.h?rev=326416=326415=326416=diff
==
--- cfe/trunk/include/clang/AST/DeclCXX.h (original)
+++ cfe/trunk/include/clang/AST/DeclCXX.h Wed Feb 28 21:43:23 2018
@@ -2062,8 +2062,7 @@ public:
   bool isVolatile() const { return 
getType()->castAs()->isVolatile(); }
 
   bool isVirtual() const {
-CXXMethodDecl *CD =
-  
cast(const_cast(this)->getCanonicalDecl());
+CXXMethodDecl *CD = const_cast(this)->getCanonicalDecl();
 
 // Member function is virtual if it is marked explicitly so, or if it is
 // declared in __interface -- then it is automatically pure virtual.

Modified: cfe/trunk/include/clang/AST/Expr.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Expr.h?rev=326416=326415=326416=diff
==
--- cfe/trunk/include/clang/AST/Expr.h (original)
+++ cfe/trunk/include/clang/AST/Expr.h Wed Feb 28 21:43:23 2018
@@ -2169,19 +2169,19 @@ public:
   void setRHS(Expr *E) { SubExprs[RHS] = E; }
 
   Expr *getBase() {
-return cast(getRHS()->getType()->isIntegerType() ? 
getLHS():getRHS());
+return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
   }
 
   const Expr *getBase() const {
-return cast(getRHS()->getType()->isIntegerType() ? 
getLHS():getRHS());
+return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
   }
 
   Expr *getIdx() {
-return cast(getRHS()->getType()->isIntegerType() ? 
getRHS():getLHS());
+return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
   }
 
   const Expr *getIdx() const {
-return cast(getRHS()->getType()->isIntegerType() ? 
getRHS():getLHS());
+return 

r322618 - [CodeGen] Fix a crash on mangling multiversioned functions

2018-01-16 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Jan 16 20:46:04 2018
New Revision: 322618

URL: http://llvm.org/viewvc/llvm-project?rev=322618=rev
Log:
[CodeGen] Fix a crash on mangling multiversioned functions

`multiVersionSortPriority` expects features to have no prefix. We
currently carry them around in the format "+${feature}".

Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/test/CodeGen/attr-target-mv.c

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=322618=322617=322618=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Tue Jan 16 20:46:04 2018
@@ -753,8 +753,12 @@ static void AppendTargetMangling(const C
   const auto  = CGM.getTarget();
   TargetAttr::ParsedTargetAttr Info =
   Attr->parse([](StringRef LHS, StringRef RHS) {
-return Target.multiVersionSortPriority(LHS) >
-   Target.multiVersionSortPriority(RHS);
+// Multiversioning doesn't allow "no-${feature}", so we can
+// only have "+" prefixes here.
+assert(LHS.startswith("+") && RHS.startswith("+") &&
+   "Features should always have a prefix.");
+return Target.multiVersionSortPriority(LHS.substr(1)) >
+   Target.multiVersionSortPriority(RHS.substr(1));
   });
 
   bool IsFirst = true;

Modified: cfe/trunk/test/CodeGen/attr-target-mv.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-target-mv.c?rev=322618=322617=322618=diff
==
--- cfe/trunk/test/CodeGen/attr-target-mv.c (original)
+++ cfe/trunk/test/CodeGen/attr-target-mv.c Tue Jan 16 20:46:04 2018
@@ -25,6 +25,14 @@ void bar3() {
 inline __attribute__((target("default"))) void foo_decls(void) {}
 inline __attribute__((target("sse4.2"))) void foo_decls(void) {}
 
+inline __attribute__((target("default"))) void foo_multi(void) {}
+inline __attribute__((target("avx,sse4.2"))) void foo_multi(void) {}
+inline __attribute__((target("sse4.2,fma4"))) void foo_multi(void) {}
+inline __attribute__((target("arch=ivybridge,fma4,sse4.2"))) void 
foo_multi(void) {}
+void bar4() {
+  foo_multi();
+}
+
 // CHECK: @foo.ifunc = ifunc i32 (), i32 ()* ()* @foo.resolver
 // CHECK: @foo_inline.ifunc = ifunc i32 (), i32 ()* ()* @foo_inline.resolver
 // CHECK: @foo_decls.ifunc = ifunc void (), void ()* ()* @foo_decls.resolver
@@ -77,3 +85,7 @@ inline __attribute__((target("sse4.2")))
 // CHECK: define available_externally void @foo_decls()
 // CHECK: define available_externally void @foo_decls.sse4.2()
 
+// CHECK: define available_externally void @foo_multi.avx_sse4.2()
+// CHECK: define available_externally void @foo_multi.fma4_sse4.2()
+// CHECK: define available_externally void 
@foo_multi.arch_ivybridge_fma4_sse4.2()
+


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


r322530 - [Sema] Fix a crash on invalid features in multiversioning

2018-01-15 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Jan 15 19:01:50 2018
New Revision: 322530

URL: http://llvm.org/viewvc/llvm-project?rev=322530=rev
Log:
[Sema] Fix a crash on invalid features in multiversioning

We were trying to emit a diag::err_bad_multiversion_option diagnostic,
which expects an int as its first argument, with a string argument. As
it happens, the string `Feature` that was causing this was shadowing an
int `Feature` from the surrounding scope. :)

Modified:
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/test/SemaCXX/attr-target-mv.cpp

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=322530=322529=322530=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Mon Jan 15 19:01:50 2018
@@ -9175,9 +9175,9 @@ static bool CheckMultiVersionValue(Sema
 return true;
   }
 
-  for (const auto  : ParseInfo.Features) {
-auto BareFeat = StringRef{Feature}.substr(1);
-if (Feature[0] == '-') {
+  for (const auto  : ParseInfo.Features) {
+auto BareFeat = StringRef{Feat}.substr(1);
+if (Feat[0] == '-') {
   S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
   << Feature << ("no-" + BareFeat).str();
   return true;

Modified: cfe/trunk/test/SemaCXX/attr-target-mv.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/attr-target-mv.cpp?rev=322530=322529=322530=diff
==
--- cfe/trunk/test/SemaCXX/attr-target-mv.cpp (original)
+++ cfe/trunk/test/SemaCXX/attr-target-mv.cpp Mon Jan 15 19:01:50 2018
@@ -1,4 +1,11 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu  -fsyntax-only -verify 
-fexceptions -fcxx-exceptions %s -std=c++14
+void __attribute__((target("default"))) invalid_features(void);
+//expected-error@+2 {{function multiversioning doesn't support feature 
'hello_world'}}
+//expected-warning@+1 {{ignoring unsupported 'hello_world' in the target 
attribute string}}
+void __attribute__((target("hello_world"))) invalid_features(void);
+//expected-error@+1 {{function multiversioning doesn't support feature 
'no-sse4.2'}}
+void __attribute__((target("no-sse4.2"))) invalid_features(void);
+
 void __attribute__((target("sse4.2"))) no_default(void);
 void __attribute__((target("arch=sandybridge")))  no_default(void);
 


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


Re: r315951 - Make __builtin_types_compatible_p more like GCC's

2017-10-16 Thread George Burgess IV via cfe-commits
Yuck, sorry for the typos in the commit message. It should read:

GCC ignores qualifiers on array types. Since we seem to have this
function primarily for GCC compatibility, we should try to match that
behavior.

This also adds a few more test-cases for __builtin_types_compatible_p,
which were inspired by GCC's documentation on the builtin.

On Mon, Oct 16, 2017 at 3:58 PM, George Burgess IV via cfe-commits
<cfe-commits@lists.llvm.org> wrote:
> Author: gbiv
> Date: Mon Oct 16 15:58:37 2017
> New Revision: 315951
>
> URL: http://llvm.org/viewvc/llvm-project?rev=315951=rev
> Log:
> Make __builtin_types_compatible_p more like GCC's
>
> GCC ignore qualifiers on array types. Since we seem to have this
> function primarily for GCC compatibility, we should try to match that
> behavior.
>
> This also adds a few more test-cases __builtin_types_compatible_p,
> which were inspired by GCC's documentation on the builtin.
>
> Modified:
> cfe/trunk/lib/Sema/SemaExprCXX.cpp
> cfe/trunk/test/Parser/builtin_types_compatible.c
>
> Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=315951=315950=315951=diff
> ==
> --- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Mon Oct 16 15:58:37 2017
> @@ -4824,9 +4824,13 @@ static bool EvaluateBinaryTypeTrait(Sema
>}
>case BTT_IsSame:
>  return Self.Context.hasSameType(LhsT, RhsT);
> -  case BTT_TypeCompatible:
> -return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
> -   RhsT.getUnqualifiedType());
> +  case BTT_TypeCompatible: {
> +// GCC ignores cv-qualifiers on arrays for this builtin.
> +Qualifiers LhsQuals, RhsQuals;
> +QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, 
> LhsQuals);
> +QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, 
> RhsQuals);
> +return Self.Context.typesAreCompatible(Lhs, Rhs);
> +  }
>case BTT_IsConvertible:
>case BTT_IsConvertibleTo: {
>  // C++0x [meta.rel]p4:
>
> Modified: cfe/trunk/test/Parser/builtin_types_compatible.c
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/builtin_types_compatible.c?rev=315951=315950=315951=diff
> ==
> --- cfe/trunk/test/Parser/builtin_types_compatible.c (original)
> +++ cfe/trunk/test/Parser/builtin_types_compatible.c Mon Oct 16 15:58:37 2017
> @@ -41,3 +41,20 @@ static void test()
>
>  }
>
> +enum E1 { E1Foo };
> +enum E2 { E2Foo };
> +
> +static void testGccCompatibility() {
> +  _Static_assert(__builtin_types_compatible_p(const volatile int, int), "");
> +  _Static_assert(__builtin_types_compatible_p(int[5], int[]), "");
> +  _Static_assert(!__builtin_types_compatible_p(int[5], int[4]), "");
> +  _Static_assert(!__builtin_types_compatible_p(int *, int **), "");
> +  _Static_assert(!__builtin_types_compatible_p(const int *, int *), "");
> +  _Static_assert(!__builtin_types_compatible_p(enum E1, enum E2), "");
> +
> +  // GCC's __builtin_types_compatible_p ignores qualifiers on arrays.
> +  _Static_assert(__builtin_types_compatible_p(const int[4], int[4]), "");
> +  _Static_assert(__builtin_types_compatible_p(int[4], const int[4]), "");
> +  _Static_assert(__builtin_types_compatible_p(const int[5][4], int[][4]), 
> "");
> +  _Static_assert(!__builtin_types_compatible_p(const int(*)[], int(*)[]), 
> "");
> +}
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315951 - Make __builtin_types_compatible_p more like GCC's

2017-10-16 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Oct 16 15:58:37 2017
New Revision: 315951

URL: http://llvm.org/viewvc/llvm-project?rev=315951=rev
Log:
Make __builtin_types_compatible_p more like GCC's

GCC ignore qualifiers on array types. Since we seem to have this
function primarily for GCC compatibility, we should try to match that
behavior.

This also adds a few more test-cases __builtin_types_compatible_p,
which were inspired by GCC's documentation on the builtin.

Modified:
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/test/Parser/builtin_types_compatible.c

Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=315951=315950=315951=diff
==
--- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Mon Oct 16 15:58:37 2017
@@ -4824,9 +4824,13 @@ static bool EvaluateBinaryTypeTrait(Sema
   }
   case BTT_IsSame:
 return Self.Context.hasSameType(LhsT, RhsT);
-  case BTT_TypeCompatible:
-return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
-   RhsT.getUnqualifiedType());
+  case BTT_TypeCompatible: {
+// GCC ignores cv-qualifiers on arrays for this builtin.
+Qualifiers LhsQuals, RhsQuals;
+QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, 
LhsQuals);
+QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, 
RhsQuals);
+return Self.Context.typesAreCompatible(Lhs, Rhs);
+  }
   case BTT_IsConvertible:
   case BTT_IsConvertibleTo: {
 // C++0x [meta.rel]p4:

Modified: cfe/trunk/test/Parser/builtin_types_compatible.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/builtin_types_compatible.c?rev=315951=315950=315951=diff
==
--- cfe/trunk/test/Parser/builtin_types_compatible.c (original)
+++ cfe/trunk/test/Parser/builtin_types_compatible.c Mon Oct 16 15:58:37 2017
@@ -41,3 +41,20 @@ static void test()
 
 }
 
+enum E1 { E1Foo };
+enum E2 { E2Foo };
+
+static void testGccCompatibility() {
+  _Static_assert(__builtin_types_compatible_p(const volatile int, int), "");
+  _Static_assert(__builtin_types_compatible_p(int[5], int[]), "");
+  _Static_assert(!__builtin_types_compatible_p(int[5], int[4]), "");
+  _Static_assert(!__builtin_types_compatible_p(int *, int **), "");
+  _Static_assert(!__builtin_types_compatible_p(const int *, int *), "");
+  _Static_assert(!__builtin_types_compatible_p(enum E1, enum E2), "");
+
+  // GCC's __builtin_types_compatible_p ignores qualifiers on arrays.
+  _Static_assert(__builtin_types_compatible_p(const int[4], int[4]), "");
+  _Static_assert(__builtin_types_compatible_p(int[4], const int[4]), "");
+  _Static_assert(__builtin_types_compatible_p(const int[5][4], int[][4]), "");
+  _Static_assert(!__builtin_types_compatible_p(const int(*)[], int(*)[]), "");
+}


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


r311051 - Fix typos in comments; NFC

2017-08-16 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Aug 16 15:44:17 2017
New Revision: 311051

URL: http://llvm.org/viewvc/llvm-project?rev=311051=rev
Log:
Fix typos in comments; NFC

Modified:
cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h?rev=311051=311050=311051=diff
==
--- cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h (original)
+++ cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h Wed Aug 16 15:44:17 2017
@@ -92,7 +92,7 @@ public:
 TheMacro = nullptr;
   }
 
-  /// getHasReadAnyTokensVal - This is used for the \#ifndef hande-shake at the
+  /// getHasReadAnyTokensVal - This is used for the \#ifndef handshake at the
   /// top of the file when reading preprocessor directives.  Otherwise, reading
   /// the "ifndef x" would count as reading tokens.
   bool getHasReadAnyTokensVal() const { return ReadAnyTokens; }

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=311051=311050=311051=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Aug 16 15:44:17 2017
@@ -995,7 +995,7 @@ static QualType handleComplexFloatConver
   return ResultType;
 }
 
-/// \brief Hande arithmetic conversion from integer to float.  Helper function
+/// \brief Handle arithmetic conversion from integer to float.  Helper function
 /// of UsualArithmeticConversions()
 static QualType handleIntToFloatConversion(Sema , ExprResult ,
ExprResult ,


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


Re: r310403 - Thread Safety Analysis: warn on nonsensical attributes.

2017-08-10 Thread George Burgess IV via cfe-commits
Sorry, I meant

bin/clang -Wthread-safety-attributes -Wthread-safety-analysis
/tmp/tc.cpp -std=c++17 -c -o/dev/null

(had -Wthread-safety-attributes twice in the email)

George

On Thu, Aug 10, 2017 at 4:08 PM, George Burgess IV
 wrote:
> Hello!
>
> It looks like this is causing buildbot failures related to libc++'s
> lock_guard and scoped_lock:
> http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/consoleFull
>
> Here's a reduced test-case (from libc++'s __mutex_base):
>
> struct __attribute__((capability("mutex"))) mutex {
>   mutex();
>   ~mutex();
> };
>
> template  struct __attribute__((scoped_lockable)) Foo {
>   _Mutex &__m_;
>
>   explicit Foo(_Mutex &__m) __attribute__((acquire_capability(__m)))
>   : __m_(__m) {}
>
>   ~Foo() __attribute__((release_capability())) {}
> };
>
> int main() {
>   ::mutex m;
>   Foo f(m);
> }
>
>
> Built with `clang -Wthread-safety-attributes
> -Wthread-safety-attributes /tmp/tc.cpp -std=c++17 -c -o/dev/null`, I
> see the following warning:
> warning: 'release_capability' attribute requires type annotated with
> 'capability' attribute; type here is 'Foo<_Mutex> *'
> [-Wthread-safety-attributes]
>
> If I change ~Foo to release_capability(__m_), I get warnings about
> both 'm' being held at the end of main, and about releasing f.__m_,
> which was not held.
>
> Since the buildbot uses -Werror, ...
>
> Can you look into this, please? :)
>
> Thanks,
> George
>
> On Tue, Aug 8, 2017 at 12:44 PM, Josh Gao via cfe-commits
>  wrote:
>> Author: jmgao
>> Date: Tue Aug  8 12:44:35 2017
>> New Revision: 310403
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=310403=rev
>> Log:
>> Thread Safety Analysis: warn on nonsensical attributes.
>>
>> Add warnings in cases where an implicit `this` argument is expected to
>> attributes because either `this` doesn't exist because the attribute is
>> on a free function, or because `this` is on a type that doesn't have a
>> corresponding capability/lockable/scoped_lockable attribute.
>>
>> Reviewers: delesley, aaron.ballman
>>
>> Differential Revision: https://reviews.llvm.org/D36237
>>
>> Modified:
>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
>> cfe/trunk/test/Sema/attr-capabilities.c
>> cfe/trunk/test/SemaCXX/warn-thread-safety-parsing.cpp
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=310403=310402=310403=diff
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Aug  8 12:44:35 
>> 2017
>> @@ -2932,6 +2932,16 @@ def warn_thread_attribute_decl_not_locka
>>"%0 attribute can only be applied in a context annotated "
>>"with 'capability(\"mutex\")' attribute">,
>>InGroup, DefaultIgnore;
>> +def warn_thread_attribute_noargs_not_lockable : Warning<
>> +  "%0 attribute requires type annotated with 'capability' attribute; "
>> +  "type here is %1">,
>> +  InGroup, DefaultIgnore;
>> +def warn_thread_attribute_noargs_not_method : Warning<
>> +  "%0 attribute without arguments can only be applied to a method of a 
>> class">,
>> +  InGroup, DefaultIgnore;
>> +def warn_thread_attribute_noargs_static_method : Warning<
>> +  "%0 attribute without arguments cannot be applied to a static method">,
>> +  InGroup, DefaultIgnore;
>>  def warn_thread_attribute_decl_not_pointer : Warning<
>>"%0 only applies to pointer types; type here is %1">,
>>InGroup, DefaultIgnore;
>>
>> Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=310403=310402=310403=diff
>> ==
>> --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Tue Aug  8 12:44:35 2017
>> @@ -480,7 +480,7 @@ static const RecordType *getRecordType(Q
>>return nullptr;
>>  }
>>
>> -static bool checkRecordTypeForCapability(Sema , QualType Ty) {
>> +template  static bool checkRecordTypeForAttr(Sema , QualType 
>> Ty) {
>>const RecordType *RT = getRecordType(Ty);
>>
>>if (!RT)
>> @@ -497,7 +497,7 @@ static bool checkRecordTypeForCapability
>>
>>// Check if the record itself has a capability.
>>RecordDecl *RD = RT->getDecl();
>> -  if (RD->hasAttr())
>> +  if (RD->hasAttr())
>>  return true;
>>
>>// Else check if any base classes have a capability.
>> @@ -505,14 +505,14 @@ static bool checkRecordTypeForCapability
>>  CXXBasePaths BPaths(false, false);
>>  if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
>>const auto *Type = BS->getType()->getAs();
>> -  return Type->getDecl()->hasAttr();
>> +  

Re: r310436 - [AST] Move visibility computations into a class; NFC

2017-08-10 Thread George Burgess IV via cfe-commits
Okay, apparently release_capability doesn't work how I assumed, so it
looks like this may be a bug in r310403. Pinged that thread.

On Thu, Aug 10, 2017 at 3:24 PM, George Burgess IV
<george.burgess...@gmail.com> wrote:
> Following up, 
> http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/console
> no longer shows ubsan failures.
>
> Looks like the attempt to fix Driver/openmp-offload.c is in r310580
> (the linked build was r310538).
>
> The libc++ test failures all seem to be a result of -Werror clang
> emitting warnings as a result of r310403, which gave us more
> diagnostics about thread safety annotations. Glancing at it, seems
> legit. Working on a fix now.
>
> On Wed, Aug 9, 2017 at 2:22 PM, George Burgess IV
> <george.burgess...@gmail.com> wrote:
>> Sorry about that!
>>
>> Attempted fix is r310523. I'll keep an eye on the bot to make sure it
>> turns green.
>>
>> On Wed, Aug 9, 2017 at 1:23 PM, Juergen Ributzka <juer...@ributzka.de> wrote:
>>> This seems to cause UBSAN issues:
>>>
>>> runtime error: load of value 4294967295, which is not a valid value for type
>>> 'clang::LVComputationKind'
>>>
>>> See ASAN+UBSAN bot on Green Dragon:
>>> http://lab.llvm.org:8080/green/job/clang-stage2-cmake-RgSan_check/4065/console
>>>
>>> On Tue, Aug 8, 2017 at 9:02 PM, George Burgess IV via cfe-commits
>>> <cfe-commits@lists.llvm.org> wrote:
>>>>
>>>> Author: gbiv
>>>> Date: Tue Aug  8 21:02:49 2017
>>>> New Revision: 310436
>>>>
>>>> URL: http://llvm.org/viewvc/llvm-project?rev=310436=rev
>>>> Log:
>>>> [AST] Move visibility computations into a class; NFC
>>>>
>>>> This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal
>>>> is to cache decl visibility/linkage for the duration of each
>>>> visibility+linkage query.
>>>>
>>>> The simplest way I can see to do this is to put the visibility
>>>> calculation code that needs to (transitively) access this cache into a
>>>> class, which is what this patch does. Actual caching will come in patch
>>>> 2. (Another way would be to keep the cache in ASTContext + manually
>>>> invalidate it or something, but that felt way too subtle to me.)
>>>>
>>>> Caching visibility results across multiple queries seems a bit tricky,
>>>> since the user can add visibility attributes ~whenever they want, and
>>>> these attributes can apparently have far-reaching effects (e.g. class
>>>> visibility extends to its members, ...). Because a cache that's dropped
>>>> at the end of each top-level query seems to work nearly as well and
>>>> doesn't require any eviction logic, I opted for that design.
>>>>
>>>> Added:
>>>> cfe/trunk/lib/AST/Linkage.h
>>>> Modified:
>>>> cfe/trunk/lib/AST/Decl.cpp
>>>> cfe/trunk/lib/AST/Type.cpp
>>>>
>>>> Modified: cfe/trunk/lib/AST/Decl.cpp
>>>> URL:
>>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436=310435=310436=diff
>>>>
>>>> ==
>>>> --- cfe/trunk/lib/AST/Decl.cpp (original)
>>>> +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug  8 21:02:49 2017
>>>> @@ -12,6 +12,7 @@
>>>>
>>>> //===--===//
>>>>
>>>>  #include "clang/AST/Decl.h"
>>>> +#include "Linkage.h"
>>>>  #include "clang/AST/ASTContext.h"
>>>>  #include "clang/AST/ASTLambda.h"
>>>>  #include "clang/AST/ASTMutationListener.h"
>>>> @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl
>>>>  // and 'matcher' is a type only matters when looking for attributes
>>>>  // and settings from the immediate context.
>>>>
>>>> -const static unsigned IgnoreExplicitVisibilityBit = 2;
>>>> -const static unsigned IgnoreAllVisibilityBit = 4;
>>>> -
>>>> -/// Kinds of LV computation.  The linkage side of the computation is
>>>> -/// always the same, but different things can change how visibility is
>>>> -/// computed.
>>>> -enum LVComputationKind {
>>>> -  /// Do an LV computation for, ultimately, a type.
>>>> -  /// Visibility may be restricted by

Re: r310403 - Thread Safety Analysis: warn on nonsensical attributes.

2017-08-10 Thread George Burgess IV via cfe-commits
Hello!

It looks like this is causing buildbot failures related to libc++'s
lock_guard and scoped_lock:
http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/consoleFull

Here's a reduced test-case (from libc++'s __mutex_base):

struct __attribute__((capability("mutex"))) mutex {
  mutex();
  ~mutex();
};

template  struct __attribute__((scoped_lockable)) Foo {
  _Mutex &__m_;

  explicit Foo(_Mutex &__m) __attribute__((acquire_capability(__m)))
  : __m_(__m) {}

  ~Foo() __attribute__((release_capability())) {}
};

int main() {
  ::mutex m;
  Foo f(m);
}


Built with `clang -Wthread-safety-attributes
-Wthread-safety-attributes /tmp/tc.cpp -std=c++17 -c -o/dev/null`, I
see the following warning:
warning: 'release_capability' attribute requires type annotated with
'capability' attribute; type here is 'Foo<_Mutex> *'
[-Wthread-safety-attributes]

If I change ~Foo to release_capability(__m_), I get warnings about
both 'm' being held at the end of main, and about releasing f.__m_,
which was not held.

Since the buildbot uses -Werror, ...

Can you look into this, please? :)

Thanks,
George

On Tue, Aug 8, 2017 at 12:44 PM, Josh Gao via cfe-commits
 wrote:
> Author: jmgao
> Date: Tue Aug  8 12:44:35 2017
> New Revision: 310403
>
> URL: http://llvm.org/viewvc/llvm-project?rev=310403=rev
> Log:
> Thread Safety Analysis: warn on nonsensical attributes.
>
> Add warnings in cases where an implicit `this` argument is expected to
> attributes because either `this` doesn't exist because the attribute is
> on a free function, or because `this` is on a type that doesn't have a
> corresponding capability/lockable/scoped_lockable attribute.
>
> Reviewers: delesley, aaron.ballman
>
> Differential Revision: https://reviews.llvm.org/D36237
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> cfe/trunk/test/Sema/attr-capabilities.c
> cfe/trunk/test/SemaCXX/warn-thread-safety-parsing.cpp
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=310403=310402=310403=diff
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Aug  8 12:44:35 
> 2017
> @@ -2932,6 +2932,16 @@ def warn_thread_attribute_decl_not_locka
>"%0 attribute can only be applied in a context annotated "
>"with 'capability(\"mutex\")' attribute">,
>InGroup, DefaultIgnore;
> +def warn_thread_attribute_noargs_not_lockable : Warning<
> +  "%0 attribute requires type annotated with 'capability' attribute; "
> +  "type here is %1">,
> +  InGroup, DefaultIgnore;
> +def warn_thread_attribute_noargs_not_method : Warning<
> +  "%0 attribute without arguments can only be applied to a method of a 
> class">,
> +  InGroup, DefaultIgnore;
> +def warn_thread_attribute_noargs_static_method : Warning<
> +  "%0 attribute without arguments cannot be applied to a static method">,
> +  InGroup, DefaultIgnore;
>  def warn_thread_attribute_decl_not_pointer : Warning<
>"%0 only applies to pointer types; type here is %1">,
>InGroup, DefaultIgnore;
>
> Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=310403=310402=310403=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Tue Aug  8 12:44:35 2017
> @@ -480,7 +480,7 @@ static const RecordType *getRecordType(Q
>return nullptr;
>  }
>
> -static bool checkRecordTypeForCapability(Sema , QualType Ty) {
> +template  static bool checkRecordTypeForAttr(Sema , QualType 
> Ty) {
>const RecordType *RT = getRecordType(Ty);
>
>if (!RT)
> @@ -497,7 +497,7 @@ static bool checkRecordTypeForCapability
>
>// Check if the record itself has a capability.
>RecordDecl *RD = RT->getDecl();
> -  if (RD->hasAttr())
> +  if (RD->hasAttr())
>  return true;
>
>// Else check if any base classes have a capability.
> @@ -505,14 +505,14 @@ static bool checkRecordTypeForCapability
>  CXXBasePaths BPaths(false, false);
>  if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
>const auto *Type = BS->getType()->getAs();
> -  return Type->getDecl()->hasAttr();
> +  return Type->getDecl()->hasAttr();
>  }, BPaths))
>return true;
>}
>return false;
>  }
>
> -static bool checkTypedefTypeForCapability(QualType Ty) {
> +template  static bool checkTypedefTypeForAttr(QualType Ty) {
>const auto *TD = Ty->getAs();
>if (!TD)
>  return false;
> @@ -521,19 +521,27 @@ static bool checkTypedefTypeForCapabilit
>if (!TN)
>  return false;
>
> -  return 

Re: r310436 - [AST] Move visibility computations into a class; NFC

2017-08-10 Thread George Burgess IV via cfe-commits
Following up, 
http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan_check/4070/console
no longer shows ubsan failures.

Looks like the attempt to fix Driver/openmp-offload.c is in r310580
(the linked build was r310538).

The libc++ test failures all seem to be a result of -Werror clang
emitting warnings as a result of r310403, which gave us more
diagnostics about thread safety annotations. Glancing at it, seems
legit. Working on a fix now.

On Wed, Aug 9, 2017 at 2:22 PM, George Burgess IV
<george.burgess...@gmail.com> wrote:
> Sorry about that!
>
> Attempted fix is r310523. I'll keep an eye on the bot to make sure it
> turns green.
>
> On Wed, Aug 9, 2017 at 1:23 PM, Juergen Ributzka <juer...@ributzka.de> wrote:
>> This seems to cause UBSAN issues:
>>
>> runtime error: load of value 4294967295, which is not a valid value for type
>> 'clang::LVComputationKind'
>>
>> See ASAN+UBSAN bot on Green Dragon:
>> http://lab.llvm.org:8080/green/job/clang-stage2-cmake-RgSan_check/4065/console
>>
>> On Tue, Aug 8, 2017 at 9:02 PM, George Burgess IV via cfe-commits
>> <cfe-commits@lists.llvm.org> wrote:
>>>
>>> Author: gbiv
>>> Date: Tue Aug  8 21:02:49 2017
>>> New Revision: 310436
>>>
>>> URL: http://llvm.org/viewvc/llvm-project?rev=310436=rev
>>> Log:
>>> [AST] Move visibility computations into a class; NFC
>>>
>>> This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal
>>> is to cache decl visibility/linkage for the duration of each
>>> visibility+linkage query.
>>>
>>> The simplest way I can see to do this is to put the visibility
>>> calculation code that needs to (transitively) access this cache into a
>>> class, which is what this patch does. Actual caching will come in patch
>>> 2. (Another way would be to keep the cache in ASTContext + manually
>>> invalidate it or something, but that felt way too subtle to me.)
>>>
>>> Caching visibility results across multiple queries seems a bit tricky,
>>> since the user can add visibility attributes ~whenever they want, and
>>> these attributes can apparently have far-reaching effects (e.g. class
>>> visibility extends to its members, ...). Because a cache that's dropped
>>> at the end of each top-level query seems to work nearly as well and
>>> doesn't require any eviction logic, I opted for that design.
>>>
>>> Added:
>>> cfe/trunk/lib/AST/Linkage.h
>>> Modified:
>>> cfe/trunk/lib/AST/Decl.cpp
>>> cfe/trunk/lib/AST/Type.cpp
>>>
>>> Modified: cfe/trunk/lib/AST/Decl.cpp
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436=310435=310436=diff
>>>
>>> ==
>>> --- cfe/trunk/lib/AST/Decl.cpp (original)
>>> +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug  8 21:02:49 2017
>>> @@ -12,6 +12,7 @@
>>>
>>> //===--===//
>>>
>>>  #include "clang/AST/Decl.h"
>>> +#include "Linkage.h"
>>>  #include "clang/AST/ASTContext.h"
>>>  #include "clang/AST/ASTLambda.h"
>>>  #include "clang/AST/ASTMutationListener.h"
>>> @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl
>>>  // and 'matcher' is a type only matters when looking for attributes
>>>  // and settings from the immediate context.
>>>
>>> -const static unsigned IgnoreExplicitVisibilityBit = 2;
>>> -const static unsigned IgnoreAllVisibilityBit = 4;
>>> -
>>> -/// Kinds of LV computation.  The linkage side of the computation is
>>> -/// always the same, but different things can change how visibility is
>>> -/// computed.
>>> -enum LVComputationKind {
>>> -  /// Do an LV computation for, ultimately, a type.
>>> -  /// Visibility may be restricted by type visibility settings and
>>> -  /// the visibility of template arguments.
>>> -  LVForType = NamedDecl::VisibilityForType,
>>> -
>>> -  /// Do an LV computation for, ultimately, a non-type declaration.
>>> -  /// Visibility may be restricted by value visibility settings and
>>> -  /// the visibility of template arguments.
>>> -  LVForValue = NamedDecl::VisibilityForValue,
>>> -
>>> -  /// Do an LV computation for, ultimately, a type that already has
>>> -  /// some sort of explicit visibility.  Visibi

Re: r310436 - [AST] Move visibility computations into a class; NFC

2017-08-09 Thread George Burgess IV via cfe-commits
Sorry about that!

Attempted fix is r310523. I'll keep an eye on the bot to make sure it
turns green.

On Wed, Aug 9, 2017 at 1:23 PM, Juergen Ributzka <juer...@ributzka.de> wrote:
> This seems to cause UBSAN issues:
>
> runtime error: load of value 4294967295, which is not a valid value for type
> 'clang::LVComputationKind'
>
> See ASAN+UBSAN bot on Green Dragon:
> http://lab.llvm.org:8080/green/job/clang-stage2-cmake-RgSan_check/4065/console
>
> On Tue, Aug 8, 2017 at 9:02 PM, George Burgess IV via cfe-commits
> <cfe-commits@lists.llvm.org> wrote:
>>
>> Author: gbiv
>> Date: Tue Aug  8 21:02:49 2017
>> New Revision: 310436
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=310436=rev
>> Log:
>> [AST] Move visibility computations into a class; NFC
>>
>> This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal
>> is to cache decl visibility/linkage for the duration of each
>> visibility+linkage query.
>>
>> The simplest way I can see to do this is to put the visibility
>> calculation code that needs to (transitively) access this cache into a
>> class, which is what this patch does. Actual caching will come in patch
>> 2. (Another way would be to keep the cache in ASTContext + manually
>> invalidate it or something, but that felt way too subtle to me.)
>>
>> Caching visibility results across multiple queries seems a bit tricky,
>> since the user can add visibility attributes ~whenever they want, and
>> these attributes can apparently have far-reaching effects (e.g. class
>> visibility extends to its members, ...). Because a cache that's dropped
>> at the end of each top-level query seems to work nearly as well and
>> doesn't require any eviction logic, I opted for that design.
>>
>> Added:
>> cfe/trunk/lib/AST/Linkage.h
>> Modified:
>> cfe/trunk/lib/AST/Decl.cpp
>> cfe/trunk/lib/AST/Type.cpp
>>
>> Modified: cfe/trunk/lib/AST/Decl.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436=310435=310436=diff
>>
>> ==
>> --- cfe/trunk/lib/AST/Decl.cpp (original)
>> +++ cfe/trunk/lib/AST/Decl.cpp Tue Aug  8 21:02:49 2017
>> @@ -12,6 +12,7 @@
>>
>> //===--===//
>>
>>  #include "clang/AST/Decl.h"
>> +#include "Linkage.h"
>>  #include "clang/AST/ASTContext.h"
>>  #include "clang/AST/ASTLambda.h"
>>  #include "clang/AST/ASTMutationListener.h"
>> @@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl
>>  // and 'matcher' is a type only matters when looking for attributes
>>  // and settings from the immediate context.
>>
>> -const static unsigned IgnoreExplicitVisibilityBit = 2;
>> -const static unsigned IgnoreAllVisibilityBit = 4;
>> -
>> -/// Kinds of LV computation.  The linkage side of the computation is
>> -/// always the same, but different things can change how visibility is
>> -/// computed.
>> -enum LVComputationKind {
>> -  /// Do an LV computation for, ultimately, a type.
>> -  /// Visibility may be restricted by type visibility settings and
>> -  /// the visibility of template arguments.
>> -  LVForType = NamedDecl::VisibilityForType,
>> -
>> -  /// Do an LV computation for, ultimately, a non-type declaration.
>> -  /// Visibility may be restricted by value visibility settings and
>> -  /// the visibility of template arguments.
>> -  LVForValue = NamedDecl::VisibilityForValue,
>> -
>> -  /// Do an LV computation for, ultimately, a type that already has
>> -  /// some sort of explicit visibility.  Visibility may only be
>> -  /// restricted by the visibility of template arguments.
>> -  LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
>> -
>> -  /// Do an LV computation for, ultimately, a non-type declaration
>> -  /// that already has some sort of explicit visibility.  Visibility
>> -  /// may only be restricted by the visibility of template arguments.
>> -  LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
>> -
>> -  /// Do an LV computation when we only care about the linkage.
>> -  LVForLinkageOnly =
>> -  LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
>> -};
>> -
>>  /// Does this computation kind permit us to consider additional
>>  /// visibility settings from attributes and the like?
>>  static bool hasExplicitVisibilityAlready(LVC

r310523 - Use unsigned instead of an enum for map keys

2017-08-09 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Aug  9 14:20:41 2017
New Revision: 310523

URL: http://llvm.org/viewvc/llvm-project?rev=310523=rev
Log:
Use unsigned instead of an enum for map keys

ubsan's enum sanitizer doesn't like the latter, and we had to have
out-of-bounds values for DenseMapInfo's tombstone/empty keys.

Modified:
cfe/trunk/lib/AST/Linkage.h

Modified: cfe/trunk/lib/AST/Linkage.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Linkage.h?rev=310523=310522=310523=diff
==
--- cfe/trunk/lib/AST/Linkage.h (original)
+++ cfe/trunk/lib/AST/Linkage.h Wed Aug  9 14:20:41 2017
@@ -55,27 +55,7 @@ enum LVComputationKind {
   LVForLinkageOnly =
   LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
 };
-} // namespace clang
 
-namespace llvm {
-template <> struct DenseMapInfo {
-  static inline clang::LVComputationKind getEmptyKey() {
-return static_cast(-1);
-  }
-  static inline clang::LVComputationKind getTombstoneKey() {
-return static_cast(-2);
-  }
-  static unsigned getHashValue(const clang::LVComputationKind ) {
-return Val;
-  }
-  static bool isEqual(const clang::LVComputationKind ,
-  const clang::LVComputationKind ) {
-return LHS == RHS;
-  }
-};
-} // namespace llvm
-
-namespace clang {
 class LinkageComputer {
   // We have a cache for repeated linkage/visibility computations. This saves 
us
   // from exponential behavior in heavily templated code, such as:
@@ -85,18 +65,27 @@ class LinkageComputer {
   // using B = Foo;
   // using C = Foo;
   // using D = Foo;
-  using QueryType = std::pair;
+  //
+  // Note that the unsigned is actually a LVComputationKind; ubsan's enum
+  // sanitizer doesn't like tombstone/empty markers outside of
+  // LVComputationKind's range.
+  using QueryType = std::pair;
   llvm::SmallDenseMap CachedLinkageInfo;
+
+  static QueryType makeCacheKey(const NamedDecl *ND, LVComputationKind Kind) {
+return std::make_pair(ND, static_cast(Kind));
+  }
+
   llvm::Optional lookup(const NamedDecl *ND,
  LVComputationKind Kind) const {
-auto Iter = CachedLinkageInfo.find(std::make_pair(ND, Kind));
+auto Iter = CachedLinkageInfo.find(makeCacheKey(ND, Kind));
 if (Iter == CachedLinkageInfo.end())
   return None;
 return Iter->second;
   }
 
   void cache(const NamedDecl *ND, LVComputationKind Kind, LinkageInfo Info) {
-CachedLinkageInfo[std::make_pair(ND, Kind)] = Info;
+CachedLinkageInfo[makeCacheKey(ND, Kind)] = Info;
   }
 
   LinkageInfo getLVForTemplateArgumentList(ArrayRef Args,


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


r310445 - Attempt #2 to appease buildbots

2017-08-09 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Aug  8 23:07:08 2017
New Revision: 310445

URL: http://llvm.org/viewvc/llvm-project?rev=310445=rev
Log:
Attempt #2 to appease buildbots

"error: unable to create target: 'No available targets are compatible
with this triple.'"

Modified:
cfe/trunk/test/CodeGenCXX/pr29160.cpp

Modified: cfe/trunk/test/CodeGenCXX/pr29160.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/pr29160.cpp?rev=310445=310444=310445=diff
==
--- cfe/trunk/test/CodeGenCXX/pr29160.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/pr29160.cpp Tue Aug  8 23:07:08 2017
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++11 -triple i686-linux %s -o /dev/null -S
+// RUN: %clang_cc1 -std=c++11 -triple i686-linux-gnu %s -o /dev/null -S 
-emit-llvm
 //
 // This test's failure mode is running ~forever. (For some value of "forever"
 // that's greater than 25 minutes on my machine)


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


r310444 - Attempt to appease msc buildbot

2017-08-08 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Aug  8 22:20:05 2017
New Revision: 310444

URL: http://llvm.org/viewvc/llvm-project?rev=310444=rev
Log:
Attempt to appease msc buildbot

It was timing out on this test, but for reasons unrelated to the
specific bug it was testing for. Randomly breaking in gdb with `clang
-target i686-windows -fmsc-version=1700` reveals *many* frames from
MicrosoftCXXNameMangler. So, it would seem that some caching is needed
there, as well...

Fingers crossed that specifying a triple is sufficient to work around
this.

Modified:
cfe/trunk/test/CodeGenCXX/pr29160.cpp

Modified: cfe/trunk/test/CodeGenCXX/pr29160.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/pr29160.cpp?rev=310444=310443=310444=diff
==
--- cfe/trunk/test/CodeGenCXX/pr29160.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/pr29160.cpp Tue Aug  8 22:20:05 2017
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++11 %s -o /dev/null -S
+// RUN: %clang_cc1 -std=c++11 -triple i686-linux %s -o /dev/null -S
 //
 // This test's failure mode is running ~forever. (For some value of "forever"
 // that's greater than 25 minutes on my machine)


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


r310437 - [AST] Cache intermediate visibility/linkage results

2017-08-08 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Aug  8 21:12:17 2017
New Revision: 310437

URL: http://llvm.org/viewvc/llvm-project?rev=310437=rev
Log:
[AST] Cache intermediate visibility/linkage results

This is a follow-up to r310436 with actual functional changes. Please
see that commit message for a description of why a cache is appearing
here.

Suggestions for less-bad ways of testing this are appreciated. :)

This fixes PR29160.

Added:
cfe/trunk/test/CodeGenCXX/pr29160.cpp
Modified:
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/lib/AST/Linkage.h
cfe/trunk/lib/AST/Type.cpp

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310437=310436=310437=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Tue Aug  8 21:12:17 2017
@@ -192,7 +192,7 @@ LinkageInfo LinkageComputer::getLVForTyp
   LVComputationKind computation) {
   if (computation == LVForLinkageOnly)
 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
-  return T.getLinkageAndVisibility();
+  return getTypeLinkageAndVisibility();
 }
 
 /// \brief Get the most restrictive linkage for the types in the given
@@ -224,7 +224,7 @@ LinkageInfo LinkageComputer::getLVForTem
   for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
 QualType type = NTTP->getExpansionType(i);
 if (!type->isDependentType())
-  LV.merge(type->getLinkageAndVisibility());
+  LV.merge(getTypeLinkageAndVisibility(type));
   }
   continue;
 }
@@ -291,7 +291,7 @@ LinkageComputer::getLVForTemplateArgumen
   continue;
 
 case TemplateArgument::NullPtr:
-  LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
+  LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
   continue;
 
 case TemplateArgument::Template:
@@ -610,7 +610,7 @@ LinkageComputer::getLVForNamespaceScopeD
  PrevVar = PrevVar->getPreviousDecl()) {
   if (PrevVar->getStorageClass() == SC_PrivateExtern &&
   Var->getStorageClass() == SC_None)
-return PrevVar->getLinkageAndVisibility();
+return getDeclLinkageAndVisibility(PrevVar);
   // Explicitly declared static.
   if (PrevVar->getStorageClass() == SC_Static)
 return getInternalLinkageFor(Var);
@@ -1358,11 +1358,15 @@ LinkageInfo LinkageComputer::getLVForDec
   if (computation == LVForLinkageOnly && D->hasCachedLinkage())
 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
 
+  if (llvm::Optional LI = lookup(D, computation))
+return *LI;
+
   LinkageInfo LV = computeLVForDecl(D, computation);
   if (D->hasCachedLinkage())
 assert(D->getCachedLinkage() == LV.getLinkage());
 
   D->setCachedLinkage(LV.getLinkage());
+  cache(D, computation, LV);
 
 #ifndef NDEBUG
   // In C (because of gnu inline) and in c++ with microsoft extensions an

Modified: cfe/trunk/lib/AST/Linkage.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Linkage.h?rev=310437=310436=310437=diff
==
--- cfe/trunk/lib/AST/Linkage.h (original)
+++ cfe/trunk/lib/AST/Linkage.h Tue Aug  8 21:12:17 2017
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Optional.h"
 
 namespace clang {
 enum : unsigned {
@@ -54,8 +55,50 @@ enum LVComputationKind {
   LVForLinkageOnly =
   LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
 };
+} // namespace clang
 
+namespace llvm {
+template <> struct DenseMapInfo {
+  static inline clang::LVComputationKind getEmptyKey() {
+return static_cast(-1);
+  }
+  static inline clang::LVComputationKind getTombstoneKey() {
+return static_cast(-2);
+  }
+  static unsigned getHashValue(const clang::LVComputationKind ) {
+return Val;
+  }
+  static bool isEqual(const clang::LVComputationKind ,
+  const clang::LVComputationKind ) {
+return LHS == RHS;
+  }
+};
+} // namespace llvm
+
+namespace clang {
 class LinkageComputer {
+  // We have a cache for repeated linkage/visibility computations. This saves 
us
+  // from exponential behavior in heavily templated code, such as:
+  //
+  // template  struct {};
+  // using A = int;
+  // using B = Foo;
+  // using C = Foo;
+  // using D = Foo;
+  using QueryType = std::pair;
+  llvm::SmallDenseMap CachedLinkageInfo;
+  llvm::Optional lookup(const NamedDecl *ND,
+ LVComputationKind Kind) const {
+auto Iter = CachedLinkageInfo.find(std::make_pair(ND, Kind));
+if (Iter == CachedLinkageInfo.end())
+  return None;
+return Iter->second;
+  }
+
+  void cache(const NamedDecl *ND, LVComputationKind Kind, LinkageInfo Info) {
+CachedLinkageInfo[std::make_pair(ND, 

r310436 - [AST] Move visibility computations into a class; NFC

2017-08-08 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Aug  8 21:02:49 2017
New Revision: 310436

URL: http://llvm.org/viewvc/llvm-project?rev=310436=rev
Log:
[AST] Move visibility computations into a class; NFC

This is patch 1 in a 2 patch series that aims to fix PR29160. Its goal
is to cache decl visibility/linkage for the duration of each
visibility+linkage query.

The simplest way I can see to do this is to put the visibility
calculation code that needs to (transitively) access this cache into a
class, which is what this patch does. Actual caching will come in patch
2. (Another way would be to keep the cache in ASTContext + manually
invalidate it or something, but that felt way too subtle to me.)

Caching visibility results across multiple queries seems a bit tricky,
since the user can add visibility attributes ~whenever they want, and
these attributes can apparently have far-reaching effects (e.g. class
visibility extends to its members, ...). Because a cache that's dropped
at the end of each top-level query seems to work nearly as well and
doesn't require any eviction logic, I opted for that design.

Added:
cfe/trunk/lib/AST/Linkage.h
Modified:
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/lib/AST/Type.cpp

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=310436=310435=310436=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Tue Aug  8 21:02:49 2017
@@ -12,6 +12,7 @@
 
//===--===//
 
 #include "clang/AST/Decl.h"
+#include "Linkage.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTLambda.h"
 #include "clang/AST/ASTMutationListener.h"
@@ -99,38 +100,6 @@ TranslationUnitDecl::TranslationUnitDecl
 // and 'matcher' is a type only matters when looking for attributes
 // and settings from the immediate context.
 
-const static unsigned IgnoreExplicitVisibilityBit = 2;
-const static unsigned IgnoreAllVisibilityBit = 4;
-
-/// Kinds of LV computation.  The linkage side of the computation is
-/// always the same, but different things can change how visibility is
-/// computed.
-enum LVComputationKind {
-  /// Do an LV computation for, ultimately, a type.
-  /// Visibility may be restricted by type visibility settings and
-  /// the visibility of template arguments.
-  LVForType = NamedDecl::VisibilityForType,
-
-  /// Do an LV computation for, ultimately, a non-type declaration.
-  /// Visibility may be restricted by value visibility settings and
-  /// the visibility of template arguments.
-  LVForValue = NamedDecl::VisibilityForValue,
-
-  /// Do an LV computation for, ultimately, a type that already has
-  /// some sort of explicit visibility.  Visibility may only be
-  /// restricted by the visibility of template arguments.
-  LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
-
-  /// Do an LV computation for, ultimately, a non-type declaration
-  /// that already has some sort of explicit visibility.  Visibility
-  /// may only be restricted by the visibility of template arguments.
-  LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
-
-  /// Do an LV computation when we only care about the linkage.
-  LVForLinkageOnly =
-  LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
-};
-
 /// Does this computation kind permit us to consider additional
 /// visibility settings from attributes and the like?
 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
@@ -219,8 +188,8 @@ static Optional getVisibilit
   return None;
 }
 
-static LinkageInfo
-getLVForType(const Type , LVComputationKind computation) {
+LinkageInfo LinkageComputer::getLVForType(const Type ,
+  LVComputationKind computation) {
   if (computation == LVForLinkageOnly)
 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
   return T.getLinkageAndVisibility();
@@ -229,9 +198,8 @@ getLVForType(const Type , LVComputatio
 /// \brief Get the most restrictive linkage for the types in the given
 /// template parameter list.  For visibility purposes, template
 /// parameters are part of the signature of a template.
-static LinkageInfo
-getLVForTemplateParameterList(const TemplateParameterList *Params,
-  LVComputationKind computation) {
+LinkageInfo LinkageComputer::getLVForTemplateParameterList(
+const TemplateParameterList *Params, LVComputationKind computation) {
   LinkageInfo LV;
   for (const NamedDecl *P : *Params) {
 // Template type parameters are the most common and never
@@ -283,10 +251,6 @@ getLVForTemplateParameterList(const Temp
   return LV;
 }
 
-/// getLVForDecl - Get the linkage and visibility for the given declaration.
-static LinkageInfo getLVForDecl(const NamedDecl *D,
-LVComputationKind computation);
-
 static const Decl 

r310299 - Mark static variables static; NFC.

2017-08-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Aug  7 13:26:33 2017
New Revision: 310299

URL: http://llvm.org/viewvc/llvm-project?rev=310299=rev
Log:
Mark static variables static; NFC.

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=310299=310298=310299=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Mon Aug  7 13:26:33 2017
@@ -99,8 +99,8 @@ TranslationUnitDecl::TranslationUnitDecl
 // and 'matcher' is a type only matters when looking for attributes
 // and settings from the immediate context.
 
-const unsigned IgnoreExplicitVisibilityBit = 2;
-const unsigned IgnoreAllVisibilityBit = 4;
+const static unsigned IgnoreExplicitVisibilityBit = 2;
+const static unsigned IgnoreAllVisibilityBit = 4;
 
 /// Kinds of LV computation.  The linkage side of the computation is
 /// always the same, but different things can change how visibility is


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


r307995 - Add release notes for the overloadable attribute

2017-07-13 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Jul 13 20:23:57 2017
New Revision: 307995

URL: http://llvm.org/viewvc/llvm-project?rev=307995=rev
Log:
Add release notes for the overloadable attribute

Modified:
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=307995=307994=307995=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 13 20:23:57 2017
@@ -82,7 +82,9 @@ Clang now supports the ...
 Attribute Changes in Clang
 --
 
--  ...
+-  The ``overloadable`` attribute now allows at most one function with a given
+   name to lack the ``overloadable`` attribute. This unmarked function will not
+   have its name mangled.
 
 Windows Support
 ---


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


r306899 - [Parse] Use normalized attr name for late-parsing checks.

2017-06-30 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Jun 30 15:33:24 2017
New Revision: 306899

URL: http://llvm.org/viewvc/llvm-project?rev=306899=rev
Log:
[Parse] Use normalized attr name for late-parsing checks.

Modified:
cfe/trunk/lib/Parse/ParseDecl.cpp
cfe/trunk/test/Sema/diagnose_if.c

Modified: cfe/trunk/lib/Parse/ParseDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDecl.cpp?rev=306899=306898=306899=diff
==
--- cfe/trunk/lib/Parse/ParseDecl.cpp (original)
+++ cfe/trunk/lib/Parse/ParseDecl.cpp Fri Jun 30 15:33:24 2017
@@ -71,11 +71,18 @@ TypeResult Parser::ParseTypeName(SourceR
   return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
 }
 
+/// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
+static StringRef normalizeAttrName(StringRef Name) {
+  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
+return Name.drop_front(2).drop_back(2);
+  return Name;
+}
+
 /// isAttributeLateParsed - Return true if the attribute has arguments that
 /// require late parsing.
 static bool isAttributeLateParsed(const IdentifierInfo ) {
 #define CLANG_ATTR_LATE_PARSED_LIST
-return llvm::StringSwitch(II.getName())
+return llvm::StringSwitch(normalizeAttrName(II.getName()))
 #include "clang/Parse/AttrParserStringSwitches.inc"
 .Default(false);
 #undef CLANG_ATTR_LATE_PARSED_LIST
@@ -200,13 +207,6 @@ void Parser::ParseGNUAttributes(ParsedAt
   }
 }
 
-/// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
-static StringRef normalizeAttrName(StringRef Name) {
-  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
-Name = Name.drop_front(2).drop_back(2);
-  return Name;
-}
-
 /// \brief Determine whether the given attribute has an identifier argument.
 static bool attributeHasIdentifierArg(const IdentifierInfo ) {
 #define CLANG_ATTR_IDENTIFIER_ARG_LIST

Modified: cfe/trunk/test/Sema/diagnose_if.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/diagnose_if.c?rev=306899=306898=306899=diff
==
--- cfe/trunk/test/Sema/diagnose_if.c (original)
+++ cfe/trunk/test/Sema/diagnose_if.c Fri Jun 30 15:33:24 2017
@@ -153,3 +153,7 @@ void runAlwaysWarnWithArg(int a) {
 
 // Test that diagnose_if warnings generated in system headers are not ignored.
 #include "Inputs/diagnose-if-warn-system-header.h"
+
+// Bug: we would complain about `a` being undeclared if this was spelled
+// __diagnose_if__.
+void underbarName(int a) __attribute__((__diagnose_if__(a, "", "warning")));


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


r306467 - [Sema] Allow unmarked overloadable functions.

2017-06-27 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Jun 27 14:31:31 2017
New Revision: 306467

URL: http://llvm.org/viewvc/llvm-project?rev=306467=rev
Log:
[Sema] Allow unmarked overloadable functions.

This patch extends the `overloadable` attribute to allow for one
function with a given name to not be marked with the `overloadable`
attribute. The overload without the `overloadable` attribute will not
have its name mangled.

So, the following code is now legal:

  void foo(void) __attribute__((overloadable));
  void foo(int);
  void foo(float) __attribute__((overloadable));

In addition, this patch fixes a bug where we'd accept code with
`__attribute__((overloadable))` inconsistently applied. In other words,
we used to accept:

  void foo(void);
  void foo(void) __attribute__((overloadable));

But we will do this no longer, since it defeats the original purpose of
requiring `__attribute__((overloadable))` on all redeclarations of a
function.

This breakage seems to not be an issue in practice, since the only code
I could find that had this pattern often looked like:

  void foo(void);
  void foo(void) __attribute__((overloadable)) __asm__("foo");
  void foo(int) __attribute__((overloadable));

...Which can now be simplified by simply removing the asm label and
overloadable attribute from the redeclaration of `void foo(void);`

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

Modified:
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Lex/PPMacroExpansion.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/test/CodeGen/mangle-ms.c
cfe/trunk/test/CodeGen/mangle.c
cfe/trunk/test/CodeGenCXX/mangle-ms.cpp
cfe/trunk/test/PCH/attrs.c
cfe/trunk/test/Sema/overloadable.c

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=306467=306466=306467=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Tue Jun 27 14:31:31 2017
@@ -605,20 +605,27 @@ semantics:
   for ``T`` and ``U`` to be incompatible.
 
 The declaration of ``overloadable`` functions is restricted to function
-declarations and definitions.  Most importantly, if any function with a given
-name is given the ``overloadable`` attribute, then all function declarations
-and definitions with that name (and in that scope) must have the
-``overloadable`` attribute.  This rule even applies to redeclarations of
-functions whose original declaration had the ``overloadable`` attribute, e.g.,
+declarations and definitions.  If a function is marked with the 
``overloadable``
+attribute, then all declarations and definitions of functions with that name,
+except for at most one (see the note below about unmarked overloads), must have
+the ``overloadable`` attribute.  In addition, redeclarations of a function with
+the ``overloadable`` attribute must have the ``overloadable`` attribute, and
+redeclarations of a function without the ``overloadable`` attribute must *not*
+have the ``overloadable`` attribute. e.g.,
 
 .. code-block:: c
 
   int f(int) __attribute__((overloadable));
   float f(float); // error: declaration of "f" must have the "overloadable" 
attribute
+  int f(int); // error: redeclaration of "f" must have the "overloadable" 
attribute
 
   int g(int) __attribute__((overloadable));
   int g(int) { } // error: redeclaration of "g" must also have the 
"overloadable" attribute
 
+  int h(int);
+  int h(int) __attribute__((overloadable)); // error: declaration of "h" must 
not
+// have the "overloadable" 
attribute
+
 Functions marked ``overloadable`` must have prototypes.  Therefore, the
 following code is ill-formed:
 
@@ -651,7 +658,28 @@ caveats to this use of name mangling:
   linkage specification, it's name *will* be mangled in the same way as it
   would in C.
 
-Query for this feature with ``__has_extension(attribute_overloadable)``.
+For the purpose of backwards compatibility, at most one function with the same
+name as other ``overloadable`` functions may omit the ``overloadable``
+attribute. In this case, the function without the ``overloadable`` attribute
+will not have its name mangled.
+
+For example:
+
+.. code-block:: c
+
+  // Notes with mangled names assume Itanium mangling.
+  int f(int);
+  int f(double) __attribute__((overloadable));
+  void foo() {
+f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
+  // was marked with overloadable).
+f(1.0); // Emits a call to _Z1fd.
+  }
+
+Support for unmarked overloads is not present in some versions of clang. You 
may
+query for it using ``__has_extension(overloadable_unmarked)``.
+
+Query for this attribute with ``__has_attribute(overloadable)``.
   }];
 }
 

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 

r305947 - [test] Make absolute line numbers relative; NFC

2017-06-21 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Jun 21 14:59:05 2017
New Revision: 305947

URL: http://llvm.org/viewvc/llvm-project?rev=305947=rev
Log:
[test] Make absolute line numbers relative; NFC

Done to remove noise from https://reviews.llvm.org/D32332 (and to make
this test more resilient to changes in general).

Modified:
cfe/trunk/test/Sema/overloadable.c

Modified: cfe/trunk/test/Sema/overloadable.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/overloadable.c?rev=305947=305946=305947=diff
==
--- cfe/trunk/test/Sema/overloadable.c (original)
+++ cfe/trunk/test/Sema/overloadable.c Wed Jun 21 14:59:05 2017
@@ -106,8 +106,8 @@ void fn_type_conversions() {
   void foo(char *c) __attribute__((overloadable));
   void (*ptr1)(void *) = 
   void (*ptr2)(char *) = 
-  void (*ambiguous)(int *) =  // expected-error{{initializing 'void 
(*)(int *)' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate 
function}}
-  void *vp_ambiguous =  // expected-error{{initializing 'void *' with an 
expression of incompatible type ''}} 
expected-note@105{{candidate function}} expected-note@106{{candidate function}}
+  void (*ambiguous)(int *) =  // expected-error{{initializing 'void 
(*)(int *)' with an expression of incompatible type ''}} expected-note@-4{{candidate function}} expected-note@-3{{candidate 
function}}
+  void *vp_ambiguous =  // expected-error{{initializing 'void *' with an 
expression of incompatible type ''}} 
expected-note@-5{{candidate function}} expected-note@-4{{candidate function}}
 
   void (*specific1)(int *) = (void (*)(void *)) // 
expected-warning{{incompatible function pointer types initializing 'void 
(*)(int *)' with an expression of type 'void (*)(void *)'}}
   void *specific2 = (void (*)(void *))
@@ -117,8 +117,8 @@ void fn_type_conversions() {
   void disabled(char *c) __attribute__((overloadable, enable_if(1, "The 
function name lies.")));
   // To be clear, these should all point to the last overload of 'disabled'
   void (*dptr1)(char *c) = 
-  void (*dptr2)(void *c) =  // expected-warning{{incompatible 
pointer types initializing 'void (*)(void *)' with an expression of type 
''}} expected-note@115{{candidate function made 
ineligible by enable_if}} expected-note@116{{candidate function made ineligible 
by enable_if}} expected-note@117{{candidate function has type mismatch at 1st 
parameter (expected 'void *' but has 'char *')}}
-  void (*dptr3)(int *c) =  // expected-warning{{incompatible pointer 
types initializing 'void (*)(int *)' with an expression of type ''}} expected-note@115{{candidate function made ineligible by 
enable_if}} expected-note@116{{candidate function made ineligible by 
enable_if}} expected-note@117{{candidate function has type mismatch at 1st 
parameter (expected 'int *' but has 'char *')}}
+  void (*dptr2)(void *c) =  // expected-warning{{incompatible 
pointer types initializing 'void (*)(void *)' with an expression of type 
''}} expected-note@-5{{candidate function made 
ineligible by enable_if}} expected-note@-4{{candidate function made ineligible 
by enable_if}} expected-note@-3{{candidate function has type mismatch at 1st 
parameter (expected 'void *' but has 'char *')}}
+  void (*dptr3)(int *c) =  // expected-warning{{incompatible pointer 
types initializing 'void (*)(int *)' with an expression of type ''}} expected-note@-6{{candidate function made ineligible by 
enable_if}} expected-note@-5{{candidate function made ineligible by enable_if}} 
expected-note@-4{{candidate function has type mismatch at 1st parameter 
(expected 'int *' but has 'char *')}}
 
   void *specific_disabled = 
 }
@@ -131,14 +131,14 @@ void incompatible_pointer_type_conversio
   void foo(char *c) __attribute__((overloadable));
   void foo(short *c) __attribute__((overloadable));
   foo(charbuf);
-  foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} 
expected-note@131{{candidate function}} expected-note@132{{candidate function}}
-  foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} 
expected-note@131{{candidate function}} expected-note@132{{candidate function}}
+  foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} 
expected-note@-3{{candidate function}} expected-note@-2{{candidate function}}
+  foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} 
expected-note@-4{{candidate function}} expected-note@-3{{candidate function}}
 
   void bar(unsigned char *c) __attribute__((overloadable));
   void bar(signed char *c) __attribute__((overloadable));
-  bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} 
expected-note@137{{candidate function}} expected-note@138{{candidate function}}
+  bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} 
expected-note@-2{{candidate function}} expected-note@-1{{candidate function}}
   bar(ucharbuf);
-  bar(intbuf); // expected-error{{call to 'bar' is ambiguous}} 

r305207 - [Sema] Use the right FoldingSet.

2017-06-12 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Jun 12 12:44:30 2017
New Revision: 305207

URL: http://llvm.org/viewvc/llvm-project?rev=305207=rev
Log:
[Sema] Use the right FoldingSet.

We were doing FindNodeOrInsertPos on SubstTemplateTypeParmPackTypes, so
we should presumably be inserting into SubstTemplateTypeParmPackTypes.

Looks like the FoldingSet API can be tweaked a bit so that we can catch
things like this at compile-time. I'll look into that shortly.

I'm unsure of how to test this; suggestions welcome.

Thanks to Vladimir Voskresensky for bringing this up!

Modified:
cfe/trunk/lib/AST/ASTContext.cpp

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=305207=305206=305207=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Mon Jun 12 12:44:30 2017
@@ -3565,7 +3565,7 @@ QualType ASTContext::getSubstTemplateTyp
 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
ArgPack);
   Types.push_back(SubstParm);
-  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
+  SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
   return QualType(SubstParm, 0);  
 }
 


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


r305013 - [Sema] Refactor OverloadCandidate::BuiltinTypes. NFC.

2017-06-08 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Jun  8 15:55:21 2017
New Revision: 305013

URL: http://llvm.org/viewvc/llvm-project?rev=305013=rev
Log:
[Sema] Refactor OverloadCandidate::BuiltinTypes. NFC.

As promised in r304996.

Modified:
cfe/trunk/include/clang/Sema/Overload.h
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/lib/Sema/SemaOverload.cpp

Modified: cfe/trunk/include/clang/Sema/Overload.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Overload.h?rev=305013=305012=305013=diff
==
--- cfe/trunk/include/clang/Sema/Overload.h (original)
+++ cfe/trunk/include/clang/Sema/Overload.h Thu Jun  8 15:55:21 2017
@@ -633,11 +633,9 @@ namespace clang {
 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
 DeclAccessPair FoundDecl;
 
-/// BuiltinTypes - Provides the parameter types of a built-in overload
+/// BuiltinParamTypes - Provides the parameter types of a built-in overload
 /// candidate. Only valid when Function is NULL.
-struct {
-  QualType ParamTypes[3];
-} BuiltinTypes;
+QualType BuiltinParamTypes[3];
 
 /// Surrogate - The conversion function for which this candidate
 /// is a surrogate, but only if IsSurrogate is true.

Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=305013=305012=305013=diff
==
--- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Thu Jun  8 15:55:21 2017
@@ -5281,16 +5281,16 @@ static bool FindConditionalOverload(Sema
   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
 case OR_Success: {
   // We found a match. Perform the conversions on the arguments and move 
on.
-  ExprResult LHSRes =
-Self.PerformImplicitConversion(LHS.get(), 
Best->BuiltinTypes.ParamTypes[0],
-   Best->Conversions[0], 
Sema::AA_Converting);
+  ExprResult LHSRes = Self.PerformImplicitConversion(
+  LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
+  Sema::AA_Converting);
   if (LHSRes.isInvalid())
 break;
   LHS = LHSRes;
 
-  ExprResult RHSRes =
-Self.PerformImplicitConversion(RHS.get(), 
Best->BuiltinTypes.ParamTypes[1],
-   Best->Conversions[1], 
Sema::AA_Converting);
+  ExprResult RHSRes = Self.PerformImplicitConversion(
+  RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
+  Sema::AA_Converting);
   if (RHSRes.isInvalid())
 break;
   RHS = RHSRes;

Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=305013=305012=305013=diff
==
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Thu Jun  8 15:55:21 2017
@@ -7150,8 +7150,7 @@ void Sema::AddBuiltinCandidate(QualType
   Candidate.Function = nullptr;
   Candidate.IsSurrogate = false;
   Candidate.IgnoreObjectArgument = false;
-  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
-Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
+  std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
 
   // Determine the implicit conversion sequences for each of the
   // arguments.
@@ -10143,13 +10142,13 @@ static void NoteBuiltinOperatorCandidate
   std::string TypeStr("operator");
   TypeStr += Opc;
   TypeStr += "(";
-  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
+  TypeStr += Cand->BuiltinParamTypes[0].getAsString();
   if (Cand->Conversions.size() == 1) {
 TypeStr += ")";
 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
   } else {
 TypeStr += ", ";
-TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
+TypeStr += Cand->BuiltinParamTypes[1].getAsString();
 TypeStr += ")";
 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
   }
@@ -10386,7 +10385,7 @@ static void CompleteNonViableCandidate(S
   } else {
 // Builtin operator.
 assert(ConvCount <= 3);
-ParamTypes = Cand->BuiltinTypes.ParamTypes;
+ParamTypes = Cand->BuiltinParamTypes;
   }
 
   // Fill in the rest of the conversions.
@@ -11992,9 +11991,8 @@ Sema::CreateOverloadedUnaryOp(SourceLoca
   // We matched a built-in operator. Convert the arguments, then
   // break out so that we will build the appropriate built-in
   // operator node.
-  ExprResult InputRes =
-PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
-  Best->Conversions[0], AA_Passing);
+  ExprResult InputRes = PerformImplicitConversion(
+  Input, Best->BuiltinParamTypes[0], 

r304996 - [Sema] Remove unused field from OverloadCandidate.

2017-06-08 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Jun  8 13:19:25 2017
New Revision: 304996

URL: http://llvm.org/viewvc/llvm-project?rev=304996=rev
Log:
[Sema] Remove unused field from OverloadCandidate.

The only use in-tree I can find for BuiltinTypes.ResultTy is a single
store to it. We otherwise just recompute what it should be later on (and
sometimes do things like argument conversions in the process of
recomputing it).

Since it's impossible to test if the value stored there is sane, and we
don't use it anyway, we should probably just drop the field.

I'll do a follow-up patch to rename BuiltinTypes.ParamTypes ->
BuiltinParamTypes in a bit. Wanted to keep this patch relatively
minimal.

Thanks to Petr Kudryavtsev for bringing this up!

Modified:
cfe/trunk/include/clang/Sema/Overload.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaOverload.cpp

Modified: cfe/trunk/include/clang/Sema/Overload.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Overload.h?rev=304996=304995=304996=diff
==
--- cfe/trunk/include/clang/Sema/Overload.h (original)
+++ cfe/trunk/include/clang/Sema/Overload.h Thu Jun  8 13:19:25 2017
@@ -633,10 +633,9 @@ namespace clang {
 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
 DeclAccessPair FoundDecl;
 
-// BuiltinTypes - Provides the return and parameter types of a
-// built-in overload candidate. Only valid when Function is NULL.
+/// BuiltinTypes - Provides the parameter types of a built-in overload
+/// candidate. Only valid when Function is NULL.
 struct {
-  QualType ResultTy;
   QualType ParamTypes[3];
 } BuiltinTypes;
 

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=304996=304995=304996=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Thu Jun  8 13:19:25 2017
@@ -2727,8 +2727,7 @@ public:
SourceLocation OpLoc, ArrayRef Args,
OverloadCandidateSet& CandidateSet,
SourceRange OpRange = SourceRange());
-  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
-   ArrayRef Args,
+  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);

Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=304996=304995=304996=diff
==
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Thu Jun  8 13:19:25 2017
@@ -7136,8 +7136,7 @@ void Sema::AddMemberOperatorCandidates(O
 /// operator. NumContextualBoolArguments is the number of arguments
 /// (at the beginning of the argument list) that will be contextually
 /// converted to bool.
-void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
-   ArrayRef Args,
+void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator,
unsigned NumContextualBoolArguments) {
@@ -7151,7 +7150,6 @@ void Sema::AddBuiltinCandidate(QualType
   Candidate.Function = nullptr;
   Candidate.IsSurrogate = false;
   Candidate.IgnoreObjectArgument = false;
-  Candidate.BuiltinTypes.ResultTy = ResultTy;
   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
 
@@ -7492,7 +7490,7 @@ static void AddBuiltinAssignmentOperator
   // T& operator=(T&, T)
   ParamTypes[0] = S.Context.getLValueReferenceType(T);
   ParamTypes[1] = T;
-  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
+  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
 /*IsAssignmentOperator=*/true);
 
   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
@@ -7500,7 +7498,7 @@ static void AddBuiltinAssignmentOperator
 ParamTypes[0]
   = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
 ParamTypes[1] = T;
-S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
+S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
   /*IsAssignmentOperator=*/true);
   }
 }
@@ -7620,64 +7618,6 @@ class BuiltinOperatorOverloadBuilder {
 return S.Context.*ArithmeticTypes[index];
   }
 
-  /// \brief Gets the canonical type resulting from the usual arithemetic

r303962 - [docs] Point coroutine link to an actual document

2017-05-25 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu May 25 21:56:51 2017
New Revision: 303962

URL: http://llvm.org/viewvc/llvm-project?rev=303962=rev
Log:
[docs] Point coroutine link to an actual document

Unsure if there's a better document, but what we had before led to a
404. :)

Modified:
cfe/trunk/www/cxx_status.html

Modified: cfe/trunk/www/cxx_status.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/www/cxx_status.html?rev=303962=303961=303962=diff
==
--- cfe/trunk/www/cxx_status.html (original)
+++ cfe/trunk/www/cxx_status.html Thu May 25 21:56:51 2017
@@ -831,7 +831,7 @@ and library features that are not part o
 
 
   [DRAFT TS] Coroutines
-  http://wg21.link/p0057r7;>P0057R7
+  http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0057r7.pdf;>P0057R7
   
   WIP
 


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


r302506 - [Sema] Make typeof(OverloadedFunctionName) not a pointer.

2017-05-08 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon May  8 23:06:24 2017
New Revision: 302506

URL: http://llvm.org/viewvc/llvm-project?rev=302506=rev
Log:
[Sema] Make typeof(OverloadedFunctionName) not a pointer.

We were sometimes doing a function->pointer conversion in
Sema::CheckPlaceholderExpr, which isn't the job of CheckPlaceholderExpr.

So, when we saw typeof(OverloadedFunctionName), where
OverloadedFunctionName referenced a name with only one function that
could have its address taken, we'd give back a function pointer type
instead of a function type. This is incorrect.

I kept the logic for doing the function pointer conversion in
resolveAndFixAddressOfOnlyViableOverloadCandidate because it was more
consistent with existing ResolveAndFix* methods.

Modified:
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaCast.cpp
cfe/trunk/lib/Sema/SemaOverload.cpp
cfe/trunk/test/Sema/overloadable.c
cfe/trunk/test/SemaCXX/enable_if.cpp

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=302506=302505=302506=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Mon May  8 23:06:24 2017
@@ -2726,7 +2726,8 @@ public:
   resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
   DeclAccessPair );
 
-  bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult );
+  bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
+  ExprResult , bool DoFunctionPointerConversion = false);
 
   FunctionDecl *
   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,

Modified: cfe/trunk/lib/Sema/SemaCast.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCast.cpp?rev=302506=302505=302506=diff
==
--- cfe/trunk/lib/Sema/SemaCast.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCast.cpp Mon May  8 23:06:24 2017
@@ -1871,7 +1871,8 @@ static bool fixOverloadedReinterpretCast
   // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
   // preserves Result.
   Result = E;
-  if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
+  if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
+  Result, /*DoFunctionPointerConversion=*/true))
 return false;
   return Result.isUsable();
 }

Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=302506=302505=302506=diff
==
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Mon May  8 23:06:24 2017
@@ -11210,12 +11210,12 @@ Sema::resolveAddressOfOnlyViableOverload
 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
 /// will perform access checks, diagnose the use of the resultant decl, and, if
-/// necessary, perform a function-to-pointer decay.
+/// requested, potentially perform a function-to-pointer decay.
 ///
 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
 /// Otherwise, returns true. This may emit diagnostics and return true.
 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
-ExprResult ) {
+ExprResult , bool DoFunctionPointerConverion) {
   Expr *E = SrcExpr.get();
   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
 
@@ -11230,7 +11230,7 @@ bool Sema::resolveAndFixAddressOfOnlyVia
   DiagnoseUseOfDecl(Found, E->getExprLoc());
   CheckAddressOfMemberAccess(E, DAP);
   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
-  if (Fixed->getType()->isFunctionType())
+  if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
   else
 SrcExpr = Fixed;

Modified: cfe/trunk/test/Sema/overloadable.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/overloadable.c?rev=302506=302505=302506=diff
==
--- cfe/trunk/test/Sema/overloadable.c (original)
+++ cfe/trunk/test/Sema/overloadable.c Mon May  8 23:06:24 2017
@@ -151,3 +151,18 @@ void dropping_qualifiers_is_incompatible
   foo(ccharbuf); // expected-error{{call to 'foo' is ambiguous}} 
expected-note@148{{candidate function}} expected-note@149{{candidate function}}
   foo(vcharbuf); // expected-error{{call to 'foo' is ambiguous}} 
expected-note@148{{candidate function}} expected-note@149{{candidate function}}
 }
+
+// Bug: we used to treat `__typeof__(foo)` as though it was `__typeof__()`
+// if `foo` was overloaded with only one function that could have its address
+// taken.
+void 

r301970 - [Sema] Update function doc; NFC

2017-05-02 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue May  2 15:24:56 2017
New Revision: 301970

URL: http://llvm.org/viewvc/llvm-project?rev=301970=rev
Log:
[Sema] Update function doc; NFC

Modified:
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=301970=301969=301970=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Tue May  2 15:24:56 2017
@@ -15372,7 +15372,7 @@ static ExprResult diagnoseUnknownAnyExpr
 }
 
 /// Check for operands with placeholder types and complain if found.
-/// Returns true if there was an error and no recovery was possible.
+/// Returns ExprError() if there was an error and no recovery was possible.
 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
   if (!getLangOpts().CPlusPlus) {
 // C cannot handle TypoExpr nodes on either side of a binop because it


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


r301601 - Use a consistent style. NFC

2017-04-27 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Apr 27 18:59:45 2017
New Revision: 301601

URL: http://llvm.org/viewvc/llvm-project?rev=301601=rev
Log:
Use a consistent style. NFC

Modified:
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=301601=301600=301601=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Thu Apr 27 18:59:45 2017
@@ -6431,14 +6431,13 @@ static QualType checkConditionalPointerC
   return S.Context
   .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
   .withCVRQualifiers(MergedCVRQual);
-} else
-  return CompositeTy.withCVRQualifiers(MergedCVRQual);
+}
+return CompositeTy.withCVRQualifiers(MergedCVRQual);
   }();
   if (IsBlockPointer)
 ResultTy = S.Context.getBlockPointerType(ResultTy);
-  else {
+  else
 ResultTy = S.Context.getPointerType(ResultTy);
-  }
 
   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);


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


r301486 - Fix comment. NFC

2017-04-26 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Apr 26 17:37:38 2017
New Revision: 301486

URL: http://llvm.org/viewvc/llvm-project?rev=301486=rev
Log:
Fix comment. NFC

Modified:
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=301486=301485=301486=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Apr 26 17:37:38 2017
@@ -5275,8 +5275,7 @@ ExprResult Sema::ActOnCallExpr(Scope *Sc
   if (Fn->getType() == Context.OverloadTy) {
 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
 
-// We aren't supposed to apply this logic for if there'Scope an '&'
-// involved.
+// We aren't supposed to apply this logic if there's an '&' involved.
 if (!find.HasFormOfMemberPointer) {
   OverloadExpr *ovl = find.Expression;
   if (UnresolvedLookupExpr *ULE = dyn_cast(ovl))


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


r300283 - Fix PR31934: forming refs to functions with enable_if attrs.

2017-04-13 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Apr 13 18:47:08 2017
New Revision: 300283

URL: http://llvm.org/viewvc/llvm-project?rev=300283=rev
Log:
Fix PR31934: forming refs to functions with enable_if attrs.

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/SemaCXX/enable_if.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=300283=300282=300283=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Thu Apr 13 18:47:08 2017
@@ -6684,6 +6684,19 @@ InitializationSequence::Perform(Sema ,
   if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
 return ExprError();
 
+  // We don't check for e.g. function pointers here, since address
+  // availability checks should only occur when the function first decays
+  // into a pointer or reference.
+  if (CurInit.get()->getType()->isFunctionProtoType()) {
+if (auto *DRE = dyn_cast(CurInit.get()->IgnoreParens())) {
+  if (auto *FD = dyn_cast(DRE->getDecl())) {
+if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
+ DRE->getLocStart()))
+  return ExprError();
+  }
+}
+  }
+
   // Even though we didn't materialize a temporary, the binding may still
   // extend the lifetime of a temporary. This happens if we bind a 
reference
   // to the result of a cast to reference type.

Modified: cfe/trunk/test/SemaCXX/enable_if.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/enable_if.cpp?rev=300283=300282=300283=diff
==
--- cfe/trunk/test/SemaCXX/enable_if.cpp (original)
+++ cfe/trunk/test/SemaCXX/enable_if.cpp Thu Apr 13 18:47:08 2017
@@ -472,3 +472,30 @@ namespace instantiate_constexpr_in_enabl
   };
   void g() { X().f(); }
 }
+
+namespace PR31934 {
+int foo(int a) __attribute__((enable_if(a, "")));
+int runFn(int (&)(int));
+
+void run() {
+  {
+int ()(int) = foo; // expected-error{{cannot take address of function 
'foo'}}
+int baz = runFn(foo); // expected-error{{cannot take address of function 
'foo'}}
+  }
+
+  {
+int ()(int) = (foo); // expected-error{{cannot take address of 
function 'foo'}}
+int baz = runFn((foo)); // expected-error{{cannot take address of function 
'foo'}}
+  }
+
+  {
+int ()(int) = static_cast(foo); // 
expected-error{{cannot take address of function 'foo'}}
+int baz = runFn(static_cast(foo)); // expected-error{{cannot 
take address of function 'foo'}}
+  }
+
+  {
+int ()(int) = static_cast((foo)); // 
expected-error{{cannot take address of function 'foo'}}
+int baz = runFn(static_cast((foo))); // 
expected-error{{cannot take address of function 'foo'}}
+  }
+}
+}


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


r299603 - [Sema] Update CheckOverload docs

2017-04-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Apr  5 19:23:31 2017
New Revision: 299603

URL: http://llvm.org/viewvc/llvm-project?rev=299603=rev
Log:
[Sema] Update CheckOverload docs

- Replace documented return values (true/false) with what's actually
  returned
- Doxygenify the comment
- Reflow said comment to 80 cols

Not overly familiar with Doxygen, so nits are welcome. :)

Modified:
cfe/trunk/lib/Sema/SemaOverload.cpp

Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=299603=299602=299603=diff
==
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Wed Apr  5 19:23:31 2017
@@ -917,40 +917,39 @@ static bool checkArgPlaceholdersForOverl
   return false;
 }
 
-// IsOverload - Determine whether the given New declaration is an
-// overload of the declarations in Old. This routine returns false if
-// New and Old cannot be overloaded, e.g., if New has the same
-// signature as some function in Old (C++ 1.3.10) or if the Old
-// declarations aren't functions (or function templates) at all. When
-// it does return false, MatchedDecl will point to the decl that New
-// cannot be overloaded with.  This decl may be a UsingShadowDecl on
-// top of the underlying declaration.
-//
-// Example: Given the following input:
-//
-//   void f(int, float); // #1
-//   void f(int, int); // #2
-//   int f(int, int); // #3
-//
-// When we process #1, there is no previous declaration of "f",
-// so IsOverload will not be used.
-//
-// When we process #2, Old contains only the FunctionDecl for #1.  By
-// comparing the parameter types, we see that #1 and #2 are overloaded
-// (since they have different signatures), so this routine returns
-// false; MatchedDecl is unchanged.
-//
-// When we process #3, Old is an overload set containing #1 and #2. We
-// compare the signatures of #3 to #1 (they're overloaded, so we do
-// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
-// identical (return types of functions are not part of the
-// signature), IsOverload returns false and MatchedDecl will be set to
-// point to the FunctionDecl for #2.
-//
-// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
-// into a class by a using declaration.  The rules for whether to hide
-// shadow declarations ignore some properties which otherwise figure
-// into a function template's signature.
+/// Determine whether the given New declaration is an overload of the
+/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
+/// New and Old cannot be overloaded, e.g., if New has the same signature as
+/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
+/// functions (or function templates) at all. When it does return Ovl_Match or
+/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
+/// overloaded with. This decl may be a UsingShadowDecl on top of the 
underlying
+/// declaration.
+///
+/// Example: Given the following input:
+///
+///   void f(int, float); // #1
+///   void f(int, int); // #2
+///   int f(int, int); // #3
+///
+/// When we process #1, there is no previous declaration of "f", so IsOverload
+/// will not be used.
+///
+/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
+/// the parameter types, we see that #1 and #2 are overloaded (since they have
+/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
+/// unchanged.
+///
+/// When we process #3, Old is an overload set containing #1 and #2. We compare
+/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
+/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
+/// functions are not part of the signature), IsOverload returns Ovl_Match and
+/// MatchedDecl will be set to point to the FunctionDecl for #2.
+///
+/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a 
class
+/// by a using declaration. The rules for whether to hide shadow declarations
+/// ignore some properties which otherwise figure into a function template's
+/// signature.
 Sema::OverloadKind
 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult ,
 NamedDecl *, bool NewIsUsingDecl) {


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


r299601 - Simplify. NFC.

2017-04-05 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Apr  5 19:08:35 2017
New Revision: 299601

URL: http://llvm.org/viewvc/llvm-project?rev=299601=rev
Log:
Simplify. NFC.

Two simplifications:
- We check `!Previous.empty()` above and only use `Previous` in const
  contexts after that check, so the `!Previous.empty()` check seems
  redundant.
- The null check looks pointless, as well: AFAICT, `LookupResults`
  should never contain null entries, and `OldDecl` should always be
  non-null if `Redeclaration` is true.

Modified:
cfe/trunk/lib/Sema/SemaDecl.cpp

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=299601=299600=299601=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Wed Apr  5 19:08:35 2017
@@ -9038,14 +9038,10 @@ bool Sema::CheckFunctionDeclaration(Scop
 // with that name must be marked "overloadable".
 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
   << Redeclaration << NewFD;
-NamedDecl *OverloadedDecl = nullptr;
-if (Redeclaration)
-  OverloadedDecl = OldDecl;
-else if (!Previous.empty())
-  OverloadedDecl = Previous.getRepresentativeDecl();
-if (OverloadedDecl)
-  Diag(OverloadedDecl->getLocation(),
-   diag::note_attribute_overloadable_prev_overload);
+NamedDecl *OverloadedDecl =
+Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
+Diag(OverloadedDecl->getLocation(),
+ diag::note_attribute_overloadable_prev_overload);
 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
   }
 }


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


r298431 - Let llvm.objectsize be conservative with null pointers

2017-03-21 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Mar 21 15:09:35 2017
New Revision: 298431

URL: http://llvm.org/viewvc/llvm-project?rev=298431=rev
Log:
Let llvm.objectsize be conservative with null pointers

D28494 adds another parameter to @llvm.objectsize. Clang needs to be
sure to pass that third arg whenever applicable.

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/test/CodeGen/alloc-size.c
cfe/trunk/test/CodeGen/catch-undef-behavior.c
cfe/trunk/test/CodeGen/object-size.c
cfe/trunk/test/CodeGen/object-size.cpp
cfe/trunk/test/CodeGen/sanitize-recover.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=298431=298430=298431=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Tue Mar 21 15:09:35 2017
@@ -470,10 +470,13 @@ CodeGenFunction::emitBuiltinObjectSize(c
   assert(Ptr->getType()->isPointerTy() &&
  "Non-pointer passed to __builtin_object_size?");
 
-  // LLVM only supports 0 and 2, make sure that we pass along that as a 
boolean.
-  auto *CI = ConstantInt::get(Builder.getInt1Ty(), (Type & 2) >> 1);
   Value *F = CGM.getIntrinsic(Intrinsic::objectsize, {ResType, 
Ptr->getType()});
-  return Builder.CreateCall(F, {Ptr, CI});
+
+  // LLVM only supports 0 and 2, make sure that we pass along that as a 
boolean.
+  Value *Min = Builder.getInt1((Type & 2) != 0);
+  // For GCC compatability, __builtin_object_size treat NULL as unknown size.
+  Value *NullIsUnknown = Builder.getTrue();
+  return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown});
 }
 
 // Many of MSVC builtins are on both x64 and ARM; to avoid repeating code, we

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=298431=298430=298431=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Tue Mar 21 15:09:35 2017
@@ -581,10 +581,11 @@ void CodeGenFunction::EmitTypeCheck(Type
 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
 llvm::Value *Min = Builder.getFalse();
+llvm::Value *NullIsUnknown = Builder.getFalse();
 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
-llvm::Value *LargeEnough =
-Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
-  llvm::ConstantInt::get(IntPtrTy, Size));
+llvm::Value *LargeEnough = Builder.CreateICmpUGE(
+Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
+llvm::ConstantInt::get(IntPtrTy, Size));
 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
   }
 

Modified: cfe/trunk/test/CodeGen/alloc-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/alloc-size.c?rev=298431=298430=298431=diff
==
--- cfe/trunk/test/CodeGen/alloc-size.c (original)
+++ cfe/trunk/test/CodeGen/alloc-size.c Tue Mar 21 15:09:35 2017
@@ -231,7 +231,7 @@ void test7() {
 void test8() {
   // Non-const pointers aren't currently supported.
   void *buf = my_calloc(100, 5);
-  // CHECK: @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false)
+  // CHECK: @llvm.objectsize.i64.p0i8(i8* %{{.*}}, i1 false, i1 true)
   gi = __builtin_object_size(buf, 0);
   // CHECK: @llvm.objectsize
   gi = __builtin_object_size(buf, 1);

Modified: cfe/trunk/test/CodeGen/catch-undef-behavior.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/catch-undef-behavior.c?rev=298431=298430=298431=diff
==
--- cfe/trunk/test/CodeGen/catch-undef-behavior.c (original)
+++ cfe/trunk/test/CodeGen/catch-undef-behavior.c Tue Mar 21 15:09:35 2017
@@ -35,7 +35,7 @@ void foo() {
   union { int i; } u;
 
   // CHECK-COMMON:  %[[I8PTR:.*]] = bitcast i32* %[[PTR:.*]] to i8*
-  // CHECK-COMMON-NEXT: %[[SIZE:.*]] = call i64 @llvm.objectsize.i64.p0i8(i8* 
%[[I8PTR]], i1 false)
+  // CHECK-COMMON-NEXT: %[[SIZE:.*]] = call i64 @llvm.objectsize.i64.p0i8(i8* 
%[[I8PTR]], i1 false, i1 false)
   // CHECK-COMMON-NEXT: %[[CHECK0:.*]] = icmp uge i64 %[[SIZE]], 4
 
   // CHECK-COMMON:  %[[PTRTOINT:.*]] = ptrtoint {{.*}}* %[[PTR]] to i64

Modified: cfe/trunk/test/CodeGen/object-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/object-size.c?rev=298431=298430=298431=diff
==
--- cfe/trunk/test/CodeGen/object-size.c (original)
+++ cfe/trunk/test/CodeGen/object-size.c Tue Mar 21 15:09:35 2017
@@ -40,7 +40,7 @@ void test4() {
 // CHECK-LABEL: define void @test5
 void test5() {
   // CHECK: = 

Re: r295252 - [Modules] Consider enable_if attrs in isSameEntity.

2017-02-23 Thread George Burgess IV via cfe-commits
WFM; added them to ExtParameterInfo in r296076. Thanks for the idea!

On Wed, Feb 15, 2017 at 5:44 PM, Richard Smith <rich...@metafoo.co.uk>
wrote:

> On 15 February 2017 at 17:32, George Burgess IV <
> george.burgess...@gmail.com> wrote:
>
>> I remember that we wanted to pretend that pass_object_size isn't a part
>> of the FunctionType during the review that added it, though.
>>
>
> I remember we wanted to not add extra fake "parameters" to the
> FunctionType to model pass_object_size. I don't remember whether or why we
> wanted it to not be part of the function type at all -- on reflection, it
> seems as much a part of the type as, say, a calling convention (which it
> is, in some sense).
>
>
>> Do you think that would be better than serializing parameters before we
>> serialize template info? AFAICT, we only do merging after we start reading
>> the template info, so I can't immediately see why that wouldn't work.
>>
>
> I would be concerned about the possibility of that introducing dependency
> cycles into the deserialization process. For instance, merging default
> arguments for function parameters may require us to have already merged the
> function itself into its redeclaration chain (we don't currently model that
> quite correctly, so we probably won't hit it today).
>
>
>> On Wed, Feb 15, 2017 at 4:55 PM, Richard Smith <rich...@metafoo.co.uk>
>> wrote:
>>
>>> On 15 February 2017 at 14:43, George Burgess IV via cfe-commits <
>>> cfe-commits@lists.llvm.org> wrote:
>>>
>>>> Author: gbiv
>>>> Date: Wed Feb 15 16:43:27 2017
>>>> New Revision: 295252
>>>>
>>>> URL: http://llvm.org/viewvc/llvm-project?rev=295252=rev
>>>> Log:
>>>> [Modules] Consider enable_if attrs in isSameEntity.
>>>>
>>>> Two functions that differ only in their enable_if attributes are
>>>> considered overloads, so we should check for those when we're trying to
>>>> figure out if two functions are mergeable.
>>>>
>>>> We need to do the same thing for pass_object_size, as well. Looks like
>>>> that'll be a bit less trivial, since we sometimes do these merging
>>>> checks before we have pass_object_size attributes available (see the
>>>> merge checks in ASTDeclReader::VisitFunctionDecl that happen before we
>>>> read parameters, and merge checks in calls to ReadDeclAs<>()).
>>>>
>>>
>>> Perhaps the best way to tackle this would be to track the presence of
>>> pass_object_size as part of the function type (in the ExtParameterInfo data
>>> on the function type).
>>>
>>> Added:
>>>> cfe/trunk/test/Modules/Inputs/overloadable-attrs/
>>>> cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h
>>>> cfe/trunk/test/Modules/Inputs/overloadable-attrs/module.modulemap
>>>> cfe/trunk/test/Modules/overloadable-attrs.cpp
>>>> Modified:
>>>> cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
>>>>
>>>> Modified: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
>>>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serializat
>>>> ion/ASTReaderDecl.cpp?rev=295252=295251=295252=diff
>>>> 
>>>> ==
>>>> --- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp (original)
>>>> +++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp Wed Feb 15 16:43:27
>>>> 2017
>>>> @@ -2656,6 +2656,44 @@ static bool isSameTemplateParameterList(
>>>>return true;
>>>>  }
>>>>
>>>> +/// Determine whether the attributes we can overload on are identical
>>>> for A and
>>>> +/// B. Expects A and B to (otherwise) have the same type.
>>>> +static bool hasSameOverloadableAttrs(const FunctionDecl *A,
>>>> + const FunctionDecl *B) {
>>>> +  SmallVector AEnableIfs;
>>>> +  // Since this is an equality check, we can ignore that enable_if
>>>> attrs show up
>>>> +  // in reverse order.
>>>> +  for (const auto *EIA : A->specific_attrs())
>>>> +AEnableIfs.push_back(EIA);
>>>> +
>>>> +  SmallVector BEnableIfs;
>>>> +  for (const auto *EIA : B->specific_attrs())
>>>> +BEnableIfs.push_back(EIA);
>>>> +
>>>> +  // Two very common cases: either we have 0 enable_if attrs, or we
>>>>

r296076 - Represent pass_object_size attrs in ExtParameterInfo

2017-02-23 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Feb 23 20:49:47 2017
New Revision: 296076

URL: http://llvm.org/viewvc/llvm-project?rev=296076=rev
Log:
Represent pass_object_size attrs in ExtParameterInfo

The goal of this is to fix a bug in modules where we'd merge
FunctionDecls that differed in their pass_object_size attributes. Since
we can overload on the presence of pass_object_size attributes, this
behavior is incorrect.

We don't represent `N` in `pass_object_size(N)` as part of
ExtParameterInfo, since it's an error to overload solely on the value of
N. This means that we have a bug if we have two modules that declare
functions that differ only in their pass_object_size attrs, like so:

// In module A, from a.h
void foo(char *__attribute__((pass_object_size(0;

// In module B, from b.h
void foo(char *__attribute__((pass_object_size(1;

// In module C, in main.c
#include "a.h"
#include "b.h"

At the moment, we'll merge the foo decls, when we should instead emit a
diagnostic about an invalid overload. We seem to have similar (silent)
behavior if we overload only on the return type of `foo` instead; I'll
try to find a good place to put a FIXME (or I'll just file a bug) soon.

This patch also fixes a bug where we'd not output the proper extended
parameter info for declarations with pass_object_size attrs.

Modified:
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm
cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h
cfe/trunk/test/Modules/overloadable-attrs.cpp

Modified: cfe/trunk/include/clang/AST/Type.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Type.h?rev=296076=296075=296076=diff
==
--- cfe/trunk/include/clang/AST/Type.h (original)
+++ cfe/trunk/include/clang/AST/Type.h Thu Feb 23 20:49:47 2017
@@ -3116,9 +3116,11 @@ public:
   class ExtParameterInfo {
 enum {
   ABIMask = 0x0F,
-  IsConsumed  = 0x10
+  IsConsumed  = 0x10,
+  HasPassObjSize  = 0x20,
 };
 unsigned char Data;
+
   public:
 ExtParameterInfo() : Data(0) {}
 
@@ -3147,6 +3149,15 @@ public:
   return copy;
 }
 
+bool hasPassObjectSize() const {
+  return Data & HasPassObjSize;
+}
+ExtParameterInfo withHasPassObjectSize() const {
+  ExtParameterInfo Copy = *this;
+  Copy.Data |= HasPassObjSize;
+  return Copy;
+}
+
 unsigned char getOpaqueValue() const { return Data; }
 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
   ExtParameterInfo result;

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=296076=296075=296076=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Thu Feb 23 20:49:47 2017
@@ -101,39 +101,64 @@ CodeGenTypes::arrangeFreeFunctionType(Ca
  FTNP->getExtInfo(), {}, RequiredArgs(0));
 }
 
-/// Adds the formal parameters in FPT to the given prefix. If any parameter in
+static void addExtParameterInfosForCall(
+ llvm::SmallVectorImpl 
,
+const FunctionProtoType *proto,
+unsigned prefixArgs,
+unsigned totalArgs) {
+  assert(proto->hasExtParameterInfos());
+  assert(paramInfos.size() <= prefixArgs);
+  assert(proto->getNumParams() + prefixArgs <= totalArgs);
+
+  paramInfos.reserve(totalArgs);
+
+  // Add default infos for any prefix args that don't already have infos.
+  paramInfos.resize(prefixArgs);
+
+  // Add infos for the prototype.
+  for (const auto  : proto->getExtParameterInfos()) {
+paramInfos.push_back(ParamInfo);
+// pass_object_size params have no parameter info.
+if (ParamInfo.hasPassObjectSize())
+  paramInfos.emplace_back();
+  }
+
+  assert(paramInfos.size() <= totalArgs &&
+ "Did we forget to insert pass_object_size args?");
+  // Add default infos for the variadic and/or suffix arguments.
+  paramInfos.resize(totalArgs);
+}
+
+/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
 /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
 static void appendParameterTypes(const CodeGenTypes ,
  SmallVectorImpl ,
   SmallVectorImpl ,
- CanQual FPT,
- const FunctionDecl *FD) {
-  // Fill out paramInfos.
-  if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
-assert(paramInfos.size() <= prefix.size());
-auto protoParamInfos = FPT->getExtParameterInfos();
-paramInfos.reserve(prefix.size() + protoParamInfos.size());

Re: r296034 - [CodeGen] Silence unused variable warning in Release builds.

2017-02-23 Thread George Burgess IV via cfe-commits
Thanks for catching this! :)

On Thu, Feb 23, 2017 at 2:47 PM, Benjamin Kramer via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: d0k
> Date: Thu Feb 23 16:47:56 2017
> New Revision: 296034
>
> URL: http://llvm.org/viewvc/llvm-project?rev=296034=rev
> Log:
> [CodeGen] Silence unused variable warning in Release builds.
>
> Modified:
> cfe/trunk/lib/CodeGen/CGVTables.cpp
>
> Modified: cfe/trunk/lib/CodeGen/CGVTables.cpp
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CG
> VTables.cpp?rev=296034=296033=296034=diff
> 
> ==
> --- cfe/trunk/lib/CodeGen/CGVTables.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CGVTables.cpp Thu Feb 23 16:47:56 2017
> @@ -284,7 +284,9 @@ void CodeGenFunction::EmitCallAndReturnF
>if (isa(MD))
>  CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD,
> CallArgs);
>
> +#ifndef NDEBUG
>unsigned PrefixArgs = CallArgs.size() - 1;
> +#endif
>// Add the rest of the arguments.
>for (const ParmVarDecl *PD : MD->parameters())
>  EmitDelegateCallArg(CallArgs, PD, SourceLocation());
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r296027 - Tighten up a regex in a test

2017-02-23 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Feb 23 16:14:55 2017
New Revision: 296027

URL: http://llvm.org/viewvc/llvm-project?rev=296027=rev
Log:
Tighten up a regex in a test

...If we're trying to match "this function has only two arguments", `.*`
probably isn't the best thing to use. :)

Modified:
cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm

Modified: cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm?rev=296027=296026=296027=diff
==
--- cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm (original)
+++ cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm Thu Feb 23 16:14:55 2017
@@ -25,7 +25,7 @@ struct VirtualBase2 {
 // emit the construction code inline.
 struct WithVirtualBaseMid : virtual VirtualBase2 {
   // Ensure we only pass in `this` and a vtable. Otherwise this test is 
useless.
-  // ITANIUM: define {{.*}} void 
@_ZN18WithVirtualBaseMidCI212VirtualBase2EP11objc_objectPv({{.*}}, {{.*}})
+  // ITANIUM: define {{.*}} void 
@_ZN18WithVirtualBaseMidCI212VirtualBase2EP11objc_objectPv({{[^,]*}}, {{[^,]*}})
   using VirtualBase2::VirtualBase2;
 };
 struct WithVirtualBaseLast : WithVirtualBaseMid {


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


r296024 - [CodeGen] Fix ExtParameterInfo bugs in C++ CodeGen code.

2017-02-23 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Feb 23 16:07:35 2017
New Revision: 296024

URL: http://llvm.org/viewvc/llvm-project?rev=296024=rev
Log:
[CodeGen] Fix ExtParameterInfo bugs in C++ CodeGen code.

This patch makes use of the prefix/suffix ABI argument distinction that
was introduced in r295870, so that we now emit ExtParameterInfo at the
correct offset for member calls that have added ABI arguments. I don't
see a good way to test the generated param info, since we don't actually
seem to use it in CGFunctionInfo outside of Swift. Any
suggestions/thoughts for how to better test this are welcome. :)

This patch also fixes a small bug with inheriting constructors: if we
decide not to pass args into an base class ctor, we would still
generate ExtParameterInfo as though we did. The added test-case is for
that behavior.

Modified:
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CGClass.cpp
cfe/trunk/lib/CodeGen/CGExprCXX.cpp
cfe/trunk/lib/CodeGen/CGVTables.cpp
cfe/trunk/lib/CodeGen/CodeGenTypes.h
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=296024=296023=296024=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Thu Feb 23 16:07:35 2017
@@ -362,18 +362,31 @@ getExtParameterInfosForCall(const Functi
 }
 
 /// Arrange a call to a C++ method, passing the given arguments.
+///
+/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
+/// parameter.
+/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
+/// args.
+/// PassProtoArgs indicates whether `args` has args for the parameters in the
+/// given CXXConstructorDecl.
 const CGFunctionInfo &
 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList ,
 const CXXConstructorDecl *D,
 CXXCtorType CtorKind,
-unsigned ExtraArgs) {
+unsigned ExtraPrefixArgs,
+unsigned ExtraSuffixArgs,
+bool PassProtoArgs) {
   // FIXME: Kill copy.
   SmallVector ArgTypes;
   for (const auto  : args)
 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
 
+  // +1 for implicit this, which should always be args[0].
+  unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
+
   CanQual FPT = GetFormalType(D);
-  RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, 
D);
+  RequiredArgs Required =
+  RequiredArgs::forPrototypePlus(FPT, TotalPrefixArgs + ExtraSuffixArgs, 
D);
   GlobalDecl GD(D, CtorKind);
   CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
? ArgTypes.front()
@@ -382,8 +395,14 @@ CodeGenTypes::arrangeCXXConstructorCall(
  : Context.VoidTy;
 
   FunctionType::ExtInfo Info = FPT->getExtInfo();
-  auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + 
ExtraArgs,
-ArgTypes.size());
+  llvm::SmallVector ParamInfos;
+  // If the prototype args are elided, we should only have ABI-specific args,
+  // which never have param info.
+  if (PassProtoArgs && FPT->hasExtParameterInfos()) {
+// ABI-specific suffix arguments are treated the same as variadic 
arguments.
+addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
+ArgTypes.size());
+  }
   return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
  /*chainCall=*/false, ArgTypes, Info,
  ParamInfos, Required);
@@ -627,15 +646,20 @@ CodeGenTypes::arrangeBuiltinFunctionDecl
 }
 
 /// Arrange a call to a C++ method, passing the given arguments.
+///
+/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
+/// does not count `this`.
 const CGFunctionInfo &
 CodeGenTypes::arrangeCXXMethodCall(const CallArgList ,
const FunctionProtoType *proto,
-   RequiredArgs required) {
-  unsigned numRequiredArgs =
-(proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
-  unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
+   RequiredArgs required,
+   unsigned numPrefixArgs) {
+  assert(numPrefixArgs + 1 <= args.size() &&
+ "Emitting a call with less args than the required prefix?");
+  // Add one to account for `this`. It's a bit awkward here, but we don't count
+  // `this` in similar places elsewhere.
   auto paramInfos =
-   

r295935 - [CodeGen] Don't reemit expressions for pass_object_size params.

2017-02-22 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Feb 22 23:59:56 2017
New Revision: 295935

URL: http://llvm.org/viewvc/llvm-project?rev=295935=rev
Log:
[CodeGen] Don't reemit expressions for pass_object_size params.

This fixes an assertion failure in cases where we had expression
statements that declared variables nested inside of pass_object_size
args. Since we were emitting the same ExprStmt twice (once for the arg,
once for the @llvm.objectsize call), we were getting issues with
redefining locals.

This also means that we can be more lax about when we emit
@llvm.objectsize for pass_object_size args: since we're reusing the
arg's value itself, we don't have to care so much about side-effects.

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h
cfe/trunk/test/CodeGen/pass-object-size.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=295935=295934=295935=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Wed Feb 22 23:59:56 2017
@@ -420,10 +420,11 @@ getDefaultBuiltinObjectSizeResult(unsign
 
 llvm::Value *
 CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
- llvm::IntegerType *ResType) {
+ llvm::IntegerType *ResType,
+ llvm::Value *EmittedE) {
   uint64_t ObjectSize;
   if (!E->tryEvaluateObjectSize(ObjectSize, getContext(), Type))
-return emitBuiltinObjectSize(E, Type, ResType);
+return emitBuiltinObjectSize(E, Type, ResType, EmittedE);
   return ConstantInt::get(ResType, ObjectSize, /*isSigned=*/true);
 }
 
@@ -432,9 +433,14 @@ CodeGenFunction::evaluateOrEmitBuiltinOb
 ///   - A llvm::Argument (if E is a param with the pass_object_size attribute 
on
 /// it)
 ///   - A call to the @llvm.objectsize intrinsic
+///
+/// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
+/// and we wouldn't otherwise try to reference a pass_object_size parameter,
+/// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
 llvm::Value *
 CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
-   llvm::IntegerType *ResType) {
+   llvm::IntegerType *ResType,
+   llvm::Value *EmittedE) {
   // We need to reference an argument if the pointer is a parameter with the
   // pass_object_size attribute.
   if (auto *D = dyn_cast(E->IgnoreParenImpCasts())) {
@@ -457,10 +463,10 @@ CodeGenFunction::emitBuiltinObjectSize(c
   // LLVM can't handle Type=3 appropriately, and __builtin_object_size 
shouldn't
   // evaluate E for side-effects. In either case, we shouldn't lower to
   // @llvm.objectsize.
-  if (Type == 3 || E->HasSideEffects(getContext()))
+  if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext(
 return getDefaultBuiltinObjectSizeResult(Type, ResType);
 
-  Value *Ptr = EmitScalarExpr(E);
+  Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
   assert(Ptr->getType()->isPointerTy() &&
  "Non-pointer passed to __builtin_object_size?");
 
@@ -965,7 +971,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(
 
 // We pass this builtin onto the optimizer so that it can figure out the
 // object size in more complex cases.
-return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType));
+return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
+ /*EmittedE=*/nullptr));
   }
   case Builtin::BI__builtin_prefetch: {
 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=295935=295934=295935=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Feb 22 23:59:56 2017
@@ -3243,7 +3243,18 @@ void CodeGenFunction::EmitCallArgs(
 EvaluationOrder Order) {
   assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
 
-  auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
+  // We *have* to evaluate arguments from right to left in the MS C++ ABI,
+  // because arguments are destroyed left to right in the callee. As a special
+  // case, there are certain language constructs that require left-to-right
+  // evaluation, and in those cases we consider the evaluation order 
requirement
+  // to trump the "destruction order is reverse construction order" guarantee.
+  bool LeftToRight =
+  CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
+  ? 

r295894 - [CodeGen] Add param info for ctors with ABI args.

2017-02-22 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Feb 22 16:38:25 2017
New Revision: 295894

URL: http://llvm.org/viewvc/llvm-project?rev=295894=rev
Log:
[CodeGen] Add param info for ctors with ABI args.

This fixes a few assertion failures. Please see the added test case.

Added:
cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm
Modified:
cfe/trunk/lib/CodeGen/CGCall.cpp

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=295894=295893=295894=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Feb 22 16:38:25 2017
@@ -288,7 +288,17 @@ CodeGenTypes::arrangeCXXStructorDeclarat
   if (PassParams)
 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
 
-  TheCXXABI.buildStructorSignature(MD, Type, argTypes);
+  CGCXXABI::AddedStructorArgs AddedArgs =
+  TheCXXABI.buildStructorSignature(MD, Type, argTypes);
+  if (!paramInfos.empty()) {
+// Note: prefix implies after the first param.
+if (AddedArgs.Prefix)
+  paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
+FunctionProtoType::ExtParameterInfo{});
+if (AddedArgs.Suffix)
+  paramInfos.append(AddedArgs.Suffix,
+FunctionProtoType::ExtParameterInfo{});
+  }
 
   RequiredArgs required =
   (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())

Added: cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm?rev=295894=auto
==
--- cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm (added)
+++ cfe/trunk/test/CodeGenObjCXX/arc-attrs-abi.mm Wed Feb 22 16:38:25 2017
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -triple x86_64-apple -emit-llvm -fobjc-arc -o - %s
+// RUN: %clang_cc1 -triple x86_64-windows -emit-llvm -fobjc-arc -o - %s
+//
+// Test caess where we weren't properly adding parameter infos declarations,
+// which caused assertions to fire. Hence, no CHECKs.
+
+struct VirtualBase {
+  VirtualBase(__attribute__((ns_consumed)) id x);
+};
+struct WithVirtualBase : virtual VirtualBase {
+  WithVirtualBase(__attribute__((ns_consumed)) id x);
+};
+
+WithVirtualBase::WithVirtualBase(__attribute__((ns_consumed)) id x)
+: VirtualBase(x) {}


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


r295870 - [CodeGen] Note where we add ABI-specific args in ctors. NFC.

2017-02-22 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Feb 22 14:28:02 2017
New Revision: 295870

URL: http://llvm.org/viewvc/llvm-project?rev=295870=rev
Log:
[CodeGen] Note where we add ABI-specific args in ctors. NFC.

Meta: The ultimate goal is to teach ExtParameterInfo about
pass_object_size attributes. This is necessary for that, since our
ExtParameterInfo is a bit buggy in C++. I plan to actually make use of
this Prefix/Suffix info in the near future, but I like small
single-purpose changes. Especially when those changes are hard to
actually test...

At the moment, some of our C++-specific CodeGen pretends that ABIs can
only add arguments to the beginning of a function call. This isn't quite
correct: args can be appended to the end, as well. It hasn't mattered
much until now, since we seem to only use this "number of arguments
added" data when calculating the ExtParameterInfo to use when making a
CGFunctionInfo. Said ExtParameterInfo is currently only used for
ParameterABIs (Swift) and ns_consumed (ObjC).

So, this patch allows ABIs to indicate whether args they added were at
the beginning or end of an argument list. We can use this information to
emit ExtParameterInfos more correctly, though like said, that bit is
coming soon.

No tests since this is theoretically a nop.

Modified:
cfe/trunk/lib/CodeGen/CGCXXABI.h
cfe/trunk/lib/CodeGen/CGClass.cpp
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp

Modified: cfe/trunk/lib/CodeGen/CGCXXABI.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCXXABI.h?rev=295870=295869=295870=diff
==
--- cfe/trunk/lib/CodeGen/CGCXXABI.h (original)
+++ cfe/trunk/lib/CodeGen/CGCXXABI.h Wed Feb 22 14:28:02 2017
@@ -291,11 +291,26 @@ public:
   /// Emit constructor variants required by this ABI.
   virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
 
+  /// Notes how many arguments were added to the beginning (Prefix) and ending
+  /// (Suffix) of an arg list.
+  ///
+  /// Note that Prefix actually refers to the number of args *after* the first
+  /// one: `this` arguments always come first.
+  struct AddedStructorArgs {
+unsigned Prefix = 0;
+unsigned Suffix = 0;
+AddedStructorArgs() = default;
+AddedStructorArgs(unsigned P, unsigned S) : Prefix(P), Suffix(S) {}
+static AddedStructorArgs prefix(unsigned N) { return {N, 0}; }
+static AddedStructorArgs suffix(unsigned N) { return {0, N}; }
+  };
+
   /// Build the signature of the given constructor or destructor variant by
   /// adding any required parameters.  For convenience, ArgTys has been
   /// initialized with the type of 'this'.
-  virtual void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
-  SmallVectorImpl ) = 
0;
+  virtual AddedStructorArgs
+  buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
+ SmallVectorImpl ) = 0;
 
   /// Returns true if the given destructor type should be emitted as a linkonce
   /// delegating thunk, regardless of whether the dtor is defined in this TU or
@@ -355,9 +370,9 @@ public:
 
   /// Add any ABI-specific implicit arguments needed to call a constructor.
   ///
-  /// \return The number of args added to the call, which is typically zero or
-  /// one.
-  virtual unsigned
+  /// \return The number of arguments added at the beginning and end of the
+  /// call, which is typically zero or one.
+  virtual AddedStructorArgs
   addImplicitConstructorArgs(CodeGenFunction , const CXXConstructorDecl *D,
  CXXCtorType Type, bool ForVirtualBase,
  bool Delegating, CallArgList ) = 0;

Modified: cfe/trunk/lib/CodeGen/CGClass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGClass.cpp?rev=295870=295869=295870=diff
==
--- cfe/trunk/lib/CodeGen/CGClass.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGClass.cpp Wed Feb 22 14:28:02 2017
@@ -2032,14 +2032,15 @@ void CodeGenFunction::EmitCXXConstructor
   }
 
   // Insert any ABI-specific implicit constructor arguments.
-  unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
-  *this, D, Type, ForVirtualBase, Delegating, Args);
+  CGCXXABI::AddedStructorArgs ExtraArgs =
+  CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, 
ForVirtualBase,
+ Delegating, Args);
 
   // Emit the call.
   llvm::Constant *CalleePtr =
 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
-  const CGFunctionInfo  =
-CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
+  const CGFunctionInfo  = CGM.getTypes().arrangeCXXConstructorCall(
+  Args, D, Type, ExtraArgs.Prefix + ExtraArgs.Suffix);
   CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
   EmitCall(Info, Callee, ReturnValueSlot(), 

r295805 - Call the correct @llvm.objectsize.

2017-02-21 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Feb 21 20:35:51 2017
New Revision: 295805

URL: http://llvm.org/viewvc/llvm-project?rev=295805=rev
Log:
Call the correct @llvm.objectsize.

The following code would crash clang:

void foo(unsigned *const __attribute__((pass_object_size(0;
void bar(unsigned *i) { foo(i); }

This is because we were always selecting the version of
`@llvm.objectsize` that takes an i8* in CodeGen. Passing an i32* as an
i8* makes LLVM very unhappy.

(Yes, I'm surprised that this remained uncaught for so long, too. :) )

As an added bonus, we'll now also use the appropriate address space when
emitting @llvm.objectsize calls.

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/pass-object-size.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=295805=295804=295805=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Tue Feb 21 20:35:51 2017
@@ -460,13 +460,14 @@ CodeGenFunction::emitBuiltinObjectSize(c
   if (Type == 3 || E->HasSideEffects(getContext()))
 return getDefaultBuiltinObjectSizeResult(Type, ResType);
 
-  // LLVM only supports 0 and 2, make sure that we pass along that
-  // as a boolean.
+  Value *Ptr = EmitScalarExpr(E);
+  assert(Ptr->getType()->isPointerTy() &&
+ "Non-pointer passed to __builtin_object_size?");
+
+  // LLVM only supports 0 and 2, make sure that we pass along that as a 
boolean.
   auto *CI = ConstantInt::get(Builder.getInt1Ty(), (Type & 2) >> 1);
-  // FIXME: Get right address space.
-  llvm::Type *Tys[] = {ResType, Builder.getInt8PtrTy(0)};
-  Value *F = CGM.getIntrinsic(Intrinsic::objectsize, Tys);
-  return Builder.CreateCall(F, {EmitScalarExpr(E), CI});
+  Value *F = CGM.getIntrinsic(Intrinsic::objectsize, {ResType, 
Ptr->getType()});
+  return Builder.CreateCall(F, {Ptr, CI});
 }
 
 // Many of MSVC builtins are on both x64 and ARM; to avoid repeating code, we

Modified: cfe/trunk/test/CodeGen/pass-object-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/pass-object-size.c?rev=295805=295804=295805=diff
==
--- cfe/trunk/test/CodeGen/pass-object-size.c (original)
+++ cfe/trunk/test/CodeGen/pass-object-size.c Tue Feb 21 20:35:51 2017
@@ -369,3 +369,29 @@ void test14(char *c) {
   // CHECK: call void (i8*, i64, ...) @my_sprintf
   my_sprintf(c, 1, 2, 3);
 }
+
+void pass_size_unsigned(unsigned *const PS(0));
+
+// Bug: we weren't lowering to the proper @llvm.objectsize for pointers that
+// don't turn into i8*s, which caused crashes.
+// CHECK-LABEL: define void @test15
+void test15(unsigned *I) {
+  // CHECK: @llvm.objectsize.i64.p0i32
+  // CHECK: call void @pass_size_unsigned
+  pass_size_unsigned(I);
+}
+
+void pass_size_as1(__attribute__((address_space(1))) void *const PS(0));
+
+void pass_size_unsigned_as1(
+__attribute__((address_space(1))) unsigned *const PS(0));
+
+// CHECK-LABEL: define void @test16
+void test16(__attribute__((address_space(1))) unsigned *I) {
+  // CHECK: call i64 @llvm.objectsize.i64.p1i8
+  // CHECK: call void @pass_size_as1
+  pass_size_as1(I);
+  // CHECK: call i64 @llvm.objectsize.i64.p1i32
+  // CHECK: call void @pass_size_unsigned_as1
+  pass_size_unsigned_as1(I);
+}


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


Re: r295252 - [Modules] Consider enable_if attrs in isSameEntity.

2017-02-15 Thread George Burgess IV via cfe-commits
I remember that we wanted to pretend that pass_object_size isn't a part of
the FunctionType during the review that added it, though. Do you think that
would be better than serializing parameters before we serialize template
info? AFAICT, we only do merging after we start reading the template info,
so I can't immediately see why that wouldn't work.

On Wed, Feb 15, 2017 at 4:55 PM, Richard Smith <rich...@metafoo.co.uk>
wrote:

> On 15 February 2017 at 14:43, George Burgess IV via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: gbiv
>> Date: Wed Feb 15 16:43:27 2017
>> New Revision: 295252
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=295252=rev
>> Log:
>> [Modules] Consider enable_if attrs in isSameEntity.
>>
>> Two functions that differ only in their enable_if attributes are
>> considered overloads, so we should check for those when we're trying to
>> figure out if two functions are mergeable.
>>
>> We need to do the same thing for pass_object_size, as well. Looks like
>> that'll be a bit less trivial, since we sometimes do these merging
>> checks before we have pass_object_size attributes available (see the
>> merge checks in ASTDeclReader::VisitFunctionDecl that happen before we
>> read parameters, and merge checks in calls to ReadDeclAs<>()).
>>
>
> Perhaps the best way to tackle this would be to track the presence of
> pass_object_size as part of the function type (in the ExtParameterInfo data
> on the function type).
>
> Added:
>> cfe/trunk/test/Modules/Inputs/overloadable-attrs/
>> cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h
>> cfe/trunk/test/Modules/Inputs/overloadable-attrs/module.modulemap
>> cfe/trunk/test/Modules/overloadable-attrs.cpp
>> Modified:
>> cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
>>
>> Modified: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
>> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serializat
>> ion/ASTReaderDecl.cpp?rev=295252=295251=295252=diff
>> 
>> ==
>> --- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp (original)
>> +++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp Wed Feb 15 16:43:27
>> 2017
>> @@ -2656,6 +2656,44 @@ static bool isSameTemplateParameterList(
>>return true;
>>  }
>>
>> +/// Determine whether the attributes we can overload on are identical
>> for A and
>> +/// B. Expects A and B to (otherwise) have the same type.
>> +static bool hasSameOverloadableAttrs(const FunctionDecl *A,
>> + const FunctionDecl *B) {
>> +  SmallVector AEnableIfs;
>> +  // Since this is an equality check, we can ignore that enable_if attrs
>> show up
>> +  // in reverse order.
>> +  for (const auto *EIA : A->specific_attrs())
>> +AEnableIfs.push_back(EIA);
>> +
>> +  SmallVector BEnableIfs;
>> +  for (const auto *EIA : B->specific_attrs())
>> +BEnableIfs.push_back(EIA);
>> +
>> +  // Two very common cases: either we have 0 enable_if attrs, or we have
>> an
>> +  // unequal number of enable_if attrs.
>> +  if (AEnableIfs.empty() && BEnableIfs.empty())
>> +return true;
>> +
>> +  if (AEnableIfs.size() != BEnableIfs.size())
>> +return false;
>> +
>> +  llvm::FoldingSetNodeID Cand1ID, Cand2ID;
>> +  for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) {
>> +Cand1ID.clear();
>> +Cand2ID.clear();
>> +
>> +AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(),
>> true);
>> +BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(),
>> true);
>> +if (Cand1ID != Cand2ID)
>> +  return false;
>> +  }
>> +
>> +  // FIXME: This doesn't currently consider pass_object_size attributes,
>> since
>> +  // we aren't guaranteed that A and B have valid parameter lists yet.
>> +  return true;
>> +}
>> +
>>  /// \brief Determine whether the two declarations refer to the same
>> entity.
>>  static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
>>assert(X->getDeclName() == Y->getDeclName() && "Declaration name
>> mismatch!");
>> @@ -2711,8 +2749,10 @@ static bool isSameEntity(NamedDecl *X, N
>>  CtorY->getInheritedConstructo
>> r().getConstructor()))
>>  return false;
>>  }
>> -return (FuncX->getLin

r295252 - [Modules] Consider enable_if attrs in isSameEntity.

2017-02-15 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Feb 15 16:43:27 2017
New Revision: 295252

URL: http://llvm.org/viewvc/llvm-project?rev=295252=rev
Log:
[Modules] Consider enable_if attrs in isSameEntity.

Two functions that differ only in their enable_if attributes are
considered overloads, so we should check for those when we're trying to
figure out if two functions are mergeable.

We need to do the same thing for pass_object_size, as well. Looks like
that'll be a bit less trivial, since we sometimes do these merging
checks before we have pass_object_size attributes available (see the
merge checks in ASTDeclReader::VisitFunctionDecl that happen before we
read parameters, and merge checks in calls to ReadDeclAs<>()).

Added:
cfe/trunk/test/Modules/Inputs/overloadable-attrs/
cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h
cfe/trunk/test/Modules/Inputs/overloadable-attrs/module.modulemap
cfe/trunk/test/Modules/overloadable-attrs.cpp
Modified:
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp

Modified: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTReaderDecl.cpp?rev=295252=295251=295252=diff
==
--- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp Wed Feb 15 16:43:27 2017
@@ -2656,6 +2656,44 @@ static bool isSameTemplateParameterList(
   return true;
 }
 
+/// Determine whether the attributes we can overload on are identical for A and
+/// B. Expects A and B to (otherwise) have the same type.
+static bool hasSameOverloadableAttrs(const FunctionDecl *A,
+ const FunctionDecl *B) {
+  SmallVector AEnableIfs;
+  // Since this is an equality check, we can ignore that enable_if attrs show 
up
+  // in reverse order.
+  for (const auto *EIA : A->specific_attrs())
+AEnableIfs.push_back(EIA);
+
+  SmallVector BEnableIfs;
+  for (const auto *EIA : B->specific_attrs())
+BEnableIfs.push_back(EIA);
+
+  // Two very common cases: either we have 0 enable_if attrs, or we have an
+  // unequal number of enable_if attrs.
+  if (AEnableIfs.empty() && BEnableIfs.empty())
+return true;
+
+  if (AEnableIfs.size() != BEnableIfs.size())
+return false;
+
+  llvm::FoldingSetNodeID Cand1ID, Cand2ID;
+  for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) {
+Cand1ID.clear();
+Cand2ID.clear();
+
+AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(), true);
+BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(), true);
+if (Cand1ID != Cand2ID)
+  return false;
+  }
+
+  // FIXME: This doesn't currently consider pass_object_size attributes, since
+  // we aren't guaranteed that A and B have valid parameter lists yet.
+  return true;
+}
+
 /// \brief Determine whether the two declarations refer to the same entity.
 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
@@ -2711,8 +2749,10 @@ static bool isSameEntity(NamedDecl *X, N
 CtorY->getInheritedConstructor().getConstructor()))
 return false;
 }
-return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
-  FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
+return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
+   FuncX->getASTContext().hasSameType(FuncX->getType(),
+  FuncY->getType()) &&
+   hasSameOverloadableAttrs(FuncX, FuncY);
   }
 
   // Variables with the same type and linkage match.

Added: cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h?rev=295252=auto
==
--- cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h (added)
+++ cfe/trunk/test/Modules/Inputs/overloadable-attrs/a.h Wed Feb 15 16:43:27 
2017
@@ -0,0 +1,16 @@
+namespace enable_if_attrs {
+constexpr int fn1() __attribute__((enable_if(0, ""))) { return 0; }
+constexpr int fn1() { return 1; }
+
+constexpr int fn2() { return 1; }
+constexpr int fn2() __attribute__((enable_if(0, ""))) { return 0; }
+
+constexpr int fn3(int i) __attribute__((enable_if(!i, ""))) { return 0; }
+constexpr int fn3(int i) __attribute__((enable_if(i, ""))) { return 1; }
+
+constexpr int fn4(int i) { return 0; }
+constexpr int fn4(int i) __attribute__((enable_if(i, ""))) { return 1; }
+
+constexpr int fn5(int i) __attribute__((enable_if(i, ""))) { return 1; }
+constexpr int fn5(int i) { return 0; }
+}

Added: cfe/trunk/test/Modules/Inputs/overloadable-attrs/module.modulemap
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/Inputs/overloadable-attrs/module.modulemap?rev=295252=auto

r295094 - Finish a comment + remove trailing whitespace. NFC

2017-02-14 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Tue Feb 14 13:34:33 2017
New Revision: 295094

URL: http://llvm.org/viewvc/llvm-project?rev=295094=rev
Log:
Finish a comment + remove trailing whitespace. NFC

Modified:
cfe/trunk/include/clang/AST/DeclBase.h

Modified: cfe/trunk/include/clang/AST/DeclBase.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h?rev=295094=295093=295094=diff
==
--- cfe/trunk/include/clang/AST/DeclBase.h (original)
+++ cfe/trunk/include/clang/AST/DeclBase.h Tue Feb 14 13:34:33 2017
@@ -654,20 +654,19 @@ public:
   /// a precompiled header or module) rather than having been parsed.
   bool isFromASTFile() const { return FromASTFile; }
 
-  /// \brief Retrieve the global declaration ID associated with this 
-  /// declaration, which specifies where in the 
-  unsigned getGlobalID() const { 
+  /// \brief Retrieve the global declaration ID associated with this
+  /// declaration, which specifies where this Decl was loaded from.
+  unsigned getGlobalID() const {
 if (isFromASTFile())
   return *((const unsigned*)this - 1);
 return 0;
   }
-  
+
   /// \brief Retrieve the global ID of the module that owns this particular
   /// declaration.
   unsigned getOwningModuleID() const {
 if (isFromASTFile())
   return *((const unsigned*)this - 2);
-
 return 0;
   }
 


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


r295032 - Delete useless / in comment. NFC.

2017-02-13 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Feb 13 23:52:57 2017
New Revision: 295032

URL: http://llvm.org/viewvc/llvm-project?rev=295032=rev
Log:
Delete useless / in comment. NFC.

Modified:
cfe/trunk/lib/Serialization/ASTReaderStmt.cpp

Modified: cfe/trunk/lib/Serialization/ASTReaderStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTReaderStmt.cpp?rev=295032=295031=295032=diff
==
--- cfe/trunk/lib/Serialization/ASTReaderStmt.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTReaderStmt.cpp Mon Feb 13 23:52:57 2017
@@ -2914,7 +2914,7 @@ Stmt *ASTReader::ReadStmtFromStream(Modu
   llvm::BitstreamCursor  = F.DeclsCursor;
 
   // Map of offset to previously deserialized stmt. The offset points
-  /// just after the stmt record.
+  // just after the stmt record.
   llvm::DenseMap StmtEntries;
 
 #ifndef NDEBUG


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


r295029 - Add a destruct-on-exit function to ASTContext.

2017-02-13 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Mon Feb 13 23:37:36 2017
New Revision: 295029

URL: http://llvm.org/viewvc/llvm-project?rev=295029=rev
Log:
Add a destruct-on-exit function to ASTContext.

It looks like the only use of AddDeallocation is to indirectly call the
destructors of objects. In one case I found
(TypeAliasTemplateDecl::Common), the destructor is a nop, so registering
it to run later seems pointless.

All of the other *::Common types have non-trivial dtors, so deleting the
useless AddDeallocation felt somewhat fragile. Happy to kill it + turn
the is_trivial_dtor check into a static_assert if people think that'd be
better.

Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/AST/DeclTemplate.h
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/lib/AST/DeclTemplate.cpp

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=295029=295028=295029=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Mon Feb 13 23:37:36 2017
@@ -66,6 +66,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -2487,6 +2488,16 @@ public:
   /// when it is called.
   void AddDeallocation(void (*Callback)(void*), void *Data);
 
+  /// If T isn't trivially destructible, calls AddDeallocation to register it
+  /// for destruction.
+  template 
+  void addDestruction(T *Ptr) {
+if (!std::is_trivially_destructible::value) {
+  auto DestroyPtr = [](void *V) { static_cast(V)->~T(); };
+  AddDeallocation(DestroyPtr, Ptr);
+}
+  }
+
   GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
   GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
 

Modified: cfe/trunk/include/clang/AST/DeclTemplate.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclTemplate.h?rev=295029=295028=295029=diff
==
--- cfe/trunk/include/clang/AST/DeclTemplate.h (original)
+++ cfe/trunk/include/clang/AST/DeclTemplate.h Mon Feb 13 23:37:36 2017
@@ -937,8 +937,6 @@ SpecEntryTraits using V = std::map;
 /// \endcode
 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
-  static void DeallocateCommon(void *Ptr);
-
 protected:
   typedef CommonBase Common;
 
@@ -2856,8 +2850,6 @@ public:
 
 /// Declaration of a variable template.
 class VarTemplateDecl : public RedeclarableTemplateDecl {
-  static void DeallocateCommon(void *Ptr);
-
 protected:
   /// \brief Data that is common to all of the declarations of a given
   /// variable template.

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=295029=295028=295029=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Mon Feb 13 23:37:36 2017
@@ -2143,13 +2143,6 @@ APValue *VarDecl::evaluateValue() const
   return evaluateValue(Notes);
 }
 
-namespace {
-// Destroy an APValue that was allocated in an ASTContext.
-void DestroyAPValue(void* UntypedValue) {
-  static_cast(UntypedValue)->~APValue();
-}
-} // namespace
-
 APValue *VarDecl::evaluateValue(
 SmallVectorImpl ) const {
   EvaluatedStmt *Eval = ensureEvaluatedStmt();
@@ -2181,7 +2174,7 @@ APValue *VarDecl::evaluateValue(
   if (!Result)
 Eval->Evaluated = APValue();
   else if (Eval->Evaluated.needsCleanup())
-getASTContext().AddDeallocation(DestroyAPValue, >Evaluated);
+getASTContext().addDestruction(>Evaluated);
 
   Eval->IsEvaluating = false;
   Eval->WasEvaluated = true;

Modified: cfe/trunk/lib/AST/DeclTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/DeclTemplate.cpp?rev=295029=295028=295029=diff
==
--- cfe/trunk/lib/AST/DeclTemplate.cpp (original)
+++ cfe/trunk/lib/AST/DeclTemplate.cpp Mon Feb 13 23:37:36 2017
@@ -208,10 +208,6 @@ void RedeclarableTemplateDecl::addSpecia
 // FunctionTemplateDecl Implementation
 
//===--===//
 
-void FunctionTemplateDecl::DeallocateCommon(void *Ptr) {
-  static_cast(Ptr)->~Common();
-}
-
 FunctionTemplateDecl *FunctionTemplateDecl::Create(ASTContext ,
DeclContext *DC,
SourceLocation L,
@@ -231,7 +227,7 @@ FunctionTemplateDecl *FunctionTemplateDe
 RedeclarableTemplateDecl::CommonBase *
 FunctionTemplateDecl::newCommon(ASTContext ) const {
   Common *CommonPtr = new (C) Common;
-  C.AddDeallocation(DeallocateCommon, CommonPtr);
+  C.addDestruction(CommonPtr);
   return CommonPtr;
 }
 
@@ -288,10 +284,6 @@ ArrayRef FunctionTempl
 // ClassTemplateDecl Implementation
 

Re: r294800 - Don't let EvaluationModes dictate whether an invalid base is OK

2017-02-10 Thread George Burgess IV via cfe-commits
Hi Hans!

This fixes PR31843, which is a release blocker. Once the bots seem happy
with it, can we merge this into the 4.0 branch, please?

(Richard okayed this when he LGTM'ed the patch)

Thanks,
George

On Fri, Feb 10, 2017 at 2:52 PM, George Burgess IV via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: gbiv
> Date: Fri Feb 10 16:52:29 2017
> New Revision: 294800
>
> URL: http://llvm.org/viewvc/llvm-project?rev=294800=rev
> Log:
> Don't let EvaluationModes dictate whether an invalid base is OK
>
> What we want to actually control this behavior is something more local
> than an EvalutationMode. Please see the linked revision for more
> discussion on why/etc.
>
> This fixes PR31843.
>
> Differential Revision: https://reviews.llvm.org/D29469
>
> Modified:
> cfe/trunk/lib/AST/ExprConstant.cpp
> cfe/trunk/test/CodeGen/object-size.c
> cfe/trunk/test/Sema/builtin-object-size.c
>
> Modified: cfe/trunk/lib/AST/ExprConstant.cpp
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprCo
> nstant.cpp?rev=294800=294799=294800=diff
> 
> ==
> --- cfe/trunk/lib/AST/ExprConstant.cpp (original)
> +++ cfe/trunk/lib/AST/ExprConstant.cpp Fri Feb 10 16:52:29 2017
> @@ -616,10 +616,12 @@ namespace {
>/// gets a chance to look at it.
>EM_PotentialConstantExpressionUnevaluated,
>
> -  /// Evaluate as a constant expression. Continue evaluating if
> either:
> -  /// - We find a MemberExpr with a base that can't be evaluated.
> -  /// - We find a variable initialized with a call to a function that
> has
> -  ///   the alloc_size attribute on it.
> +  /// Evaluate as a constant expression. In certain scenarios, if:
> +  /// - we find a MemberExpr with a base that can't be evaluated, or
> +  /// - we find a variable initialized with a call to a function that
> has
> +  ///   the alloc_size attribute on it
> +  /// then we may consider evaluation to have succeeded.
> +  ///
>/// In either case, the LValue returned shall have an invalid base;
> in the
>/// former, the base will be the invalid MemberExpr, in the latter,
> the
>/// base will be either the alloc_size CallExpr or a CastExpr
> wrapping
> @@ -902,10 +904,6 @@ namespace {
>return KeepGoing;
>  }
>
> -bool allowInvalidBaseExpr() const {
> -  return EvalMode == EM_OffsetFold;
> -}
> -
>  class ArrayInitLoopIndex {
>EvalInfo 
>uint64_t OuterIndex;
> @@ -1416,8 +1414,10 @@ static bool Evaluate(APValue , Ev
>  static bool EvaluateInPlace(APValue , EvalInfo ,
>  const LValue , const Expr *E,
>  bool AllowNonLiteralTypes = false);
> -static bool EvaluateLValue(const Expr *E, LValue , EvalInfo );
> -static bool EvaluatePointer(const Expr *E, LValue , EvalInfo
> );
> +static bool EvaluateLValue(const Expr *E, LValue , EvalInfo ,
> +   bool InvalidBaseOK = false);
> +static bool EvaluatePointer(const Expr *E, LValue , EvalInfo ,
> +bool InvalidBaseOK = false);
>  static bool EvaluateMemberPointer(const Expr *E, MemberPtr ,
>EvalInfo );
>  static bool EvaluateTemporary(const Expr *E, LValue , EvalInfo
> );
> @@ -4835,6 +4835,7 @@ class LValueExprEvaluatorBase
>: public ExprEvaluatorBase {
>  protected:
>LValue 
> +  bool InvalidBaseOK;
>typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
>typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
>
> @@ -4843,9 +4844,14 @@ protected:
>  return true;
>}
>
> +  bool evaluatePointer(const Expr *E, LValue ) {
> +return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
> +  }
> +
>  public:
> -  LValueExprEvaluatorBase(EvalInfo , LValue ) :
> -ExprEvaluatorBaseTy(Info), Result(Result) {}
> +  LValueExprEvaluatorBase(EvalInfo , LValue , bool
> InvalidBaseOK)
> +  : ExprEvaluatorBaseTy(Info), Result(Result),
> +InvalidBaseOK(InvalidBaseOK) {}
>
>bool Success(const APValue , const Expr *E) {
>  Result.setFrom(this->Info.Ctx, V);
> @@ -4857,7 +4863,7 @@ public:
>  QualType BaseTy;
>  bool EvalOK;
>  if (E->isArrow()) {
> -  EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
> +  EvalOK = evaluatePointer(E->getBase(), Result);
>BaseTy = E->getBase()->getType()->castA
> s()->getPointeeType();
>  } else if (E->getBase()->isRValue()) {
>assert(E->getBase()->getType()->isR

r294800 - Don't let EvaluationModes dictate whether an invalid base is OK

2017-02-10 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Feb 10 16:52:29 2017
New Revision: 294800

URL: http://llvm.org/viewvc/llvm-project?rev=294800=rev
Log:
Don't let EvaluationModes dictate whether an invalid base is OK

What we want to actually control this behavior is something more local
than an EvalutationMode. Please see the linked revision for more
discussion on why/etc.

This fixes PR31843.

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

Modified:
cfe/trunk/lib/AST/ExprConstant.cpp
cfe/trunk/test/CodeGen/object-size.c
cfe/trunk/test/Sema/builtin-object-size.c

Modified: cfe/trunk/lib/AST/ExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=294800=294799=294800=diff
==
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)
+++ cfe/trunk/lib/AST/ExprConstant.cpp Fri Feb 10 16:52:29 2017
@@ -616,10 +616,12 @@ namespace {
   /// gets a chance to look at it.
   EM_PotentialConstantExpressionUnevaluated,
 
-  /// Evaluate as a constant expression. Continue evaluating if either:
-  /// - We find a MemberExpr with a base that can't be evaluated.
-  /// - We find a variable initialized with a call to a function that has
-  ///   the alloc_size attribute on it.
+  /// Evaluate as a constant expression. In certain scenarios, if:
+  /// - we find a MemberExpr with a base that can't be evaluated, or
+  /// - we find a variable initialized with a call to a function that has
+  ///   the alloc_size attribute on it
+  /// then we may consider evaluation to have succeeded.
+  ///
   /// In either case, the LValue returned shall have an invalid base; in 
the
   /// former, the base will be the invalid MemberExpr, in the latter, the
   /// base will be either the alloc_size CallExpr or a CastExpr wrapping
@@ -902,10 +904,6 @@ namespace {
   return KeepGoing;
 }
 
-bool allowInvalidBaseExpr() const {
-  return EvalMode == EM_OffsetFold;
-}
-
 class ArrayInitLoopIndex {
   EvalInfo 
   uint64_t OuterIndex;
@@ -1416,8 +1414,10 @@ static bool Evaluate(APValue , Ev
 static bool EvaluateInPlace(APValue , EvalInfo ,
 const LValue , const Expr *E,
 bool AllowNonLiteralTypes = false);
-static bool EvaluateLValue(const Expr *E, LValue , EvalInfo );
-static bool EvaluatePointer(const Expr *E, LValue , EvalInfo );
+static bool EvaluateLValue(const Expr *E, LValue , EvalInfo ,
+   bool InvalidBaseOK = false);
+static bool EvaluatePointer(const Expr *E, LValue , EvalInfo ,
+bool InvalidBaseOK = false);
 static bool EvaluateMemberPointer(const Expr *E, MemberPtr ,
   EvalInfo );
 static bool EvaluateTemporary(const Expr *E, LValue , EvalInfo );
@@ -4835,6 +4835,7 @@ class LValueExprEvaluatorBase
   : public ExprEvaluatorBase {
 protected:
   LValue 
+  bool InvalidBaseOK;
   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
 
@@ -4843,9 +4844,14 @@ protected:
 return true;
   }
 
+  bool evaluatePointer(const Expr *E, LValue ) {
+return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
+  }
+
 public:
-  LValueExprEvaluatorBase(EvalInfo , LValue ) :
-ExprEvaluatorBaseTy(Info), Result(Result) {}
+  LValueExprEvaluatorBase(EvalInfo , LValue , bool InvalidBaseOK)
+  : ExprEvaluatorBaseTy(Info), Result(Result),
+InvalidBaseOK(InvalidBaseOK) {}
 
   bool Success(const APValue , const Expr *E) {
 Result.setFrom(this->Info.Ctx, V);
@@ -4857,7 +4863,7 @@ public:
 QualType BaseTy;
 bool EvalOK;
 if (E->isArrow()) {
-  EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
+  EvalOK = evaluatePointer(E->getBase(), Result);
   BaseTy = 
E->getBase()->getType()->castAs()->getPointeeType();
 } else if (E->getBase()->isRValue()) {
   assert(E->getBase()->getType()->isRecordType());
@@ -4868,7 +4874,7 @@ public:
   BaseTy = E->getBase()->getType();
 }
 if (!EvalOK) {
-  if (!this->Info.allowInvalidBaseExpr())
+  if (!InvalidBaseOK)
 return false;
   Result.setInvalid(E);
   return true;
@@ -4962,8 +4968,8 @@ namespace {
 class LValueExprEvaluator
   : public LValueExprEvaluatorBase {
 public:
-  LValueExprEvaluator(EvalInfo , LValue ) :
-LValueExprEvaluatorBaseTy(Info, Result) {}
+  LValueExprEvaluator(EvalInfo , LValue , bool InvalidBaseOK) :
+LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
 
   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
@@ -5016,10 +5022,11 @@ public:
 ///  * function designators in C, and
 ///  * "extern void" objects
 ///  * @selector() expressions in Objective-C
-static bool EvaluateLValue(const Expr *E, LValue , EvalInfo ) {
+static bool 

r294662 - Add support for armv7ve flag in clang (PR31358).

2017-02-09 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Feb  9 17:30:10 2017
New Revision: 294662

URL: http://llvm.org/viewvc/llvm-project?rev=294662=rev
Log:
Add support for armv7ve flag in clang (PR31358).

This is a followup change to add v7ve support to clang for gcc
compatibility. Please see r294661.

Patch by Manoj Gupta.

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

Modified:
cfe/trunk/lib/Basic/Targets.cpp
cfe/trunk/test/Preprocessor/arm-acle-6.4.c
cfe/trunk/test/Preprocessor/arm-acle-6.5.c
cfe/trunk/test/Preprocessor/arm-target-features.c

Modified: cfe/trunk/lib/Basic/Targets.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets.cpp?rev=294662=294661=294662=diff
==
--- cfe/trunk/lib/Basic/Targets.cpp (original)
+++ cfe/trunk/lib/Basic/Targets.cpp Thu Feb  9 17:30:10 2017
@@ -5063,6 +5063,8 @@ class ARMTargetInfo : public TargetInfo
   return "7M";
 case llvm::ARM::AK_ARMV7EM:
   return "7EM";
+case llvm::ARM::AK_ARMV7VE:
+  return "7VE";
 case llvm::ARM::AK_ARMV8A:
   return "8A";
 case llvm::ARM::AK_ARMV8_1A:

Modified: cfe/trunk/test/Preprocessor/arm-acle-6.4.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/arm-acle-6.4.c?rev=294662=294661=294662=diff
==
--- cfe/trunk/test/Preprocessor/arm-acle-6.4.c (original)
+++ cfe/trunk/test/Preprocessor/arm-acle-6.4.c Thu Feb  9 17:30:10 2017
@@ -120,6 +120,21 @@
 
 // CHECK-V7A-NO-IDIV-NOT: __ARM_FEATURE_IDIV
 
+// RUN: %clang -target arm-none-linux-eabi -march=armv7ve -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-V7VE
+
+// CHECK-V7VE: __ARM_ARCH 7
+// CHECK-V7VE: __ARM_ARCH_ISA_ARM 1
+// CHECK-V7VE: __ARM_ARCH_ISA_THUMB 2
+// CHECK-V7VE: __ARM_ARCH_PROFILE 'A'
+// CHECK-V7VE: __ARM_FEATURE_CLZ 1
+// CHECK-V7VE: __ARM_FEATURE_DSP 1
+// CHECK-V7VE: __ARM_FEATURE_IDIV 1
+// CHECK-V7VE: __ARM_FEATURE_LDREX 0xF
+// CHECK-V7VE: __ARM_FEATURE_QBIT 1
+// CHECK-V7VE: __ARM_FEATURE_SAT 1
+// CHECK-V7VE: __ARM_FEATURE_SIMD32 1
+// CHECK-V7VE: __ARM_FEATURE_UNALIGNED 1
+
 // RUN: %clang -target arm-none-linux-eabi -march=armv7-r -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-V7R
 
 // CHECK-V7R: __ARM_ARCH 7

Modified: cfe/trunk/test/Preprocessor/arm-acle-6.5.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/arm-acle-6.5.c?rev=294662=294661=294662=diff
==
--- cfe/trunk/test/Preprocessor/arm-acle-6.5.c (original)
+++ cfe/trunk/test/Preprocessor/arm-acle-6.5.c Thu Feb  9 17:30:10 2017
@@ -24,6 +24,7 @@
 // RUN: %clang -target arm-eabi -mfpu=neon -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-SP-DP
 // RUN: %clang -target armv6-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-SP-DP
 // RUN: %clang -target armv7a-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-SP-DP
+// RUN: %clang -target armv7ve-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-SP-DP
 
 // CHECK-SP-DP: __ARM_FP 0xC
 
@@ -51,6 +52,8 @@
 
 // RUN: %clang -target armv7a-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-NO-FMA
 // RUN: %clang -target armv7a-eabi -mfpu=vfpv4 -x c -E -dM %s -o - | FileCheck 
%s -check-prefix CHECK-FMA
+// RUN: %clang -target armv7ve-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-NO-FMA
+// RUN: %clang -target armv7ve-eabi -mfpu=vfpv4 -x c -E -dM %s -o - | 
FileCheck %s -check-prefix CHECK-FMA
 // RUN: %clang -target armv7r-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-NO-FMA
 // RUN: %clang -target armv7r-eabi -mfpu=vfpv4 -x c -E -dM %s -o - | FileCheck 
%s -check-prefix CHECK-FMA
 // RUN: %clang -target armv7em-eabi -x c -E -dM %s -o - | FileCheck %s 
-check-prefix CHECK-FMA

Modified: cfe/trunk/test/Preprocessor/arm-target-features.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/arm-target-features.c?rev=294662=294661=294662=diff
==
--- cfe/trunk/test/Preprocessor/arm-target-features.c (original)
+++ cfe/trunk/test/Preprocessor/arm-target-features.c Thu Feb  9 17:30:10 2017
@@ -27,6 +27,13 @@
 // CHECK-V7-NOT: __ARM_FEATURE_DIRECTED_ROUNDING
 // CHECK-V7: #define __ARM_FP 0xC
 
+// RUN: %clang -target armv7ve-none-linux-gnu -x c -E -dM %s -o - | FileCheck 
-match-full-lines --check-prefix=CHECK-V7VE %s
+// CHECK-V7VE: #define __ARMEL__ 1
+// CHECK-V7VE: #define __ARM_ARCH 7
+// CHECK-V7VE: #define __ARM_ARCH_7VE__ 1
+// CHECK-V7VE: #define __ARM_ARCH_EXT_IDIV__ 1
+// CHECK-V7VE: #define __ARM_FP 0xC
+
 // RUN: %clang -target x86_64-apple-macosx10.10 -arch armv7s -x c -E -dM %s -o 
- | FileCheck -match-full-lines --check-prefix=CHECK-V7S %s
 // CHECK-V7S: #define __ARMEL__ 1
 // CHECK-V7S: #define __ARM_ARCH 7



r293871 - Fix typo. NFC

2017-02-02 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Thu Feb  2 01:53:55 2017
New Revision: 293871

URL: http://llvm.org/viewvc/llvm-project?rev=293871=rev
Log:
Fix typo. NFC

Modified:
cfe/trunk/lib/AST/ExprConstant.cpp

Modified: cfe/trunk/lib/AST/ExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=293871=293870=293871=diff
==
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)
+++ cfe/trunk/lib/AST/ExprConstant.cpp Thu Feb  2 01:53:55 2017
@@ -9956,7 +9956,7 @@ bool Expr::EvalResult::isGlobalLValue()
 // Note that to reduce code duplication, this helper does no evaluation
 // itself; the caller checks whether the expression is evaluatable, and
 // in the rare cases where CheckICE actually cares about the evaluated
-// value, it calls into Evalute.
+// value, it calls into Evaluate.
 
 namespace {
 


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


  1   2   3   4   >