[clang] 62b59c5 - [NFC][clang] Fix comments.

2022-01-04 Thread Shao-Ce SUN via cfe-commits

Author: Shao-Ce SUN
Date: 2022-01-05T14:49:03+08:00
New Revision: 62b59c59a6d9bab0c45808dcb96cf09047b9cba1

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

LOG: [NFC][clang] Fix comments.

Added: 


Modified: 
clang/test/Parser/extra-semi-resulting-in-nullstmt.cpp

Removed: 




diff  --git a/clang/test/Parser/extra-semi-resulting-in-nullstmt.cpp 
b/clang/test/Parser/extra-semi-resulting-in-nullstmt.cpp
index a09d942c5892..2a10392c4c05 100644
--- a/clang/test/Parser/extra-semi-resulting-in-nullstmt.cpp
+++ b/clang/test/Parser/extra-semi-resulting-in-nullstmt.cpp
@@ -17,13 +17,13 @@ void test() {
   ;
 
   // This removal of extra semi also consumes all the comments.
-  // clang-format: off
+  // clang-format off
   ;;;
-  // clang-format: on
+  // clang-format on
 
-  // clang-format: off
+  // clang-format off
   ;NULLMACRO(ZZ);
-  // clang-format: on
+  // clang-format on
 
   {}; // expected-warning {{empty expression statement has no effect; remove 
unnecessary ';' to silence this warning}}
 



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


[PATCH] D115301: [clangd] Don't index __reserved_names in headers.

2022-01-04 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!




Comment at: clang-tools-extra/clangd/SourceCode.h:334
+/// Returns true if Name is reserved, like _Foo or __Vector_base.
+inline bool isReservedName(llvm::StringRef Name) {
+  // This doesn't catch all cases, but the most common.

nit: maybe move definition out-of-line.



Comment at: clang-tools-extra/clangd/unittests/QualityTests.cpp:60
-  EXPECT_FALSE(Quality.ImplementationDetail);
-  EXPECT_TRUE(Quality.ReservedName);
-  EXPECT_EQ(Quality.References, SymbolQualitySignals().References);

can we still have a test that indexes main file symbols and ensures 
`ReservedName` is set correctly?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115301/new/

https://reviews.llvm.org/D115301

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


[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-04 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:2384
+if ((CodeGenOpts.EnableNoundefAttrs ||
+ CodeGenOpts.SanitizeMemoryParamRetval) &&
+ArgNoUndef)

vitalybuka wrote:
> @eugenis Would be better to force CodeGenOpts.EnableNoundefAttrs if 
> SanitizeMemoryParamRetval is provided?
> @eugenis Would be better to force CodeGenOpts.EnableNoundefAttrs if 
> SanitizeMemoryParamRetval is provided?

To clarify, checking SanitizeMemoryParamRetval here as-is is LGTM, unless 
@eugenis or someone else thinks EnableNoundefAttrs reset is better.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116633/new/

https://reviews.llvm.org/D116633

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


[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-04 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a subscriber: eugenis.
vitalybuka added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1675
+  PosFlag, NegFlag,
+  BothFlags<[], "eager param-retval uninitialized use detection in 
MemorySanitizer">>,
+Group;

Maybe "Detect initialized parameters and return values."? and above



Comment at: clang/lib/CodeGen/CGCall.cpp:2384
+if ((CodeGenOpts.EnableNoundefAttrs ||
+ CodeGenOpts.SanitizeMemoryParamRetval) &&
+ArgNoUndef)

@eugenis Would be better to force CodeGenOpts.EnableNoundefAttrs if 
SanitizeMemoryParamRetval is provided?



Comment at: clang/lib/CodeGen/CGCall.cpp:2386
+ArgNoUndef)
   Attrs.addAttribute(llvm::Attribute::NoUndef);
 

Without this change "-enable-noundef-analysis with 
-fsanitize-memory-param-retval" can be used.
So no matter what we decide about EnableNoundefAttrs, let's move this change 
and tests below into a separate incremental patch.



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116633/new/

https://reviews.llvm.org/D116633

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


[PATCH] D116634: enable msan-eager-checks with -fsanitize-memory-param-retval.

2022-01-04 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

this patch depends on D116633 , but D116633 
 is useless without this one
a better patch order is :

1. llvm
2. clang
3. compiler-rt (but if it's just test which uses clang flag it should be OK 
merge with no.2 )

let's do just llvm here, and move clang stuff into D116633 
 with the rest

we should update 
third_party/llvm/llvm-project/llvm/lib/Passes/PassBuilder.cpp:640
after that we can update 
third_party/llvm/llvm-project/llvm/test/Instrumentation/MemorySanitizer/msan_eager.ll
with additional ; RUN: line with 
"-passes='module(msan-module),function(msan)" 
instead of -msan-eager-checks




Comment at: compiler-rt/test/msan/noundef_analysis.cpp:5
 // RUN: FileCheck %s < %t.out
+// RUN: %clangxx_msan %s -fsanitize-memory-param-retval -o %t && not %run %t 
>%t.out 2>&1
+// RUN: FileCheck %s < %t.out

we can land it with driver patch



Comment at: llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h:28
   bool Recover;
+  bool EagerChecks;
 };

maybe we should use CheckParamRetVal something here?




Comment at: llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp:496
 Recover(Options.Recover) {
+if (Options.EagerChecks) {
+  ClEagerChecks = Options.EagerChecks;

mllvm is lower level flag, so it should be opposite
-mllvm flag should override MemorySanitizerOptions

with getOptOrDefault below you don't need anything here



Comment at: llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp:676
+  Recover(getOptOrDefault(ClKeepGoing, Kernel || R)),
+  EagerChecks(ClEagerChecks || EagerChecks) {}
 

EagerChecks(getOptOrDefault(ClEagerChecks, EagerChecks))


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116634/new/

https://reviews.llvm.org/D116634

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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-01-04 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Thanks for your review!




Comment at: 
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp:177-178
 const auto  = *FunctionDecl->getParamDecl(Index);
+if (IsExplicitTemplateSpecialization && Function != FunctionDecl)
+  continue;
 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,

flx wrote:
> Could you add a comment here why we're skipping the fix here?
> Could you add a comment here why we're skipping the fix here?

Specialization template may match the primary template again by 
`getPreviousDecl`. Skipping the fix to avoid repeated fixes for the primary 
template.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp:388
+  // CHECK-MESSAGES: [[@LINE-1]]:54: warning: the parameter 'E' is copied
+  // CHECK-FIXES: T templateSpecializationFunction(const ExpensiveToCopyType& 
E) {
+  return T();

flx wrote:
> Should we apply the fixes or just issue the warning? For virtual methods we 
> suppress the fix since we can't necessarily update all overrides of the 
> method. Are template specializations always guaranteed to be in the same 
> translation unit which  would make this safe?
> Should we apply the fixes or just issue the warning? For virtual methods we 
> suppress the fix since we can't necessarily update all overrides of the 
> method. Are template specializations always guaranteed to be in the same 
> translation unit which  would make this safe?

Do you mean that specialization templates are defined in different translation 
units?  If fixing one by one translation unit does have the problem, the 
`readability-const-return-type` also has such a problem. clang-tidy can not 
analyze across translation units, but the diagnosis and fix of it are separate, 
we can specify the complete `compile_commands.json` to avoid it. 
I'm not sure whether this is reasonable, we may make a choice between 
clang-tidy's fault tolerance and advantages. What's your suggestion?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116593/new/

https://reviews.llvm.org/D116593

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


[PATCH] D116635: Add warning to detect when calls passing arguments are made to functions without prototypes.

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher added inline comments.



Comment at: clang/test/Sema/warn-calls-without-prototype.c:39
+  return a + b +c;
+}
+

delcypher wrote:
> @NoQ Any ideas about this?  It seems kind of weird that when merging 
> `not_a_prototype3` prototype with the K style definition of 
> `not_a_prototype3` that the resulting FunctionDecl we see at the call site in 
> `call_to_function_without_prototype3` is marked as not having a prototype.
> 
> If I flip the order (see `not_a_prototype6`) then the merged declaration is 
> marked as having a prototype.
> 
> I'm not sure if this is a bug in `Sema::MergeFunctionDecl` or if this just a 
> peculiarity of K style function definitions.
I suspect the problem might be here in `Sema::MergeFunctionDecl`.

```lang=c++
   // C: Function types need to be compatible, not identical. This handles
  // duplicate function decls like "void f(int); void f(enum X);" properly.
  if (!getLangOpts().CPlusPlus &&
  Context.typesAreCompatible(OldQType, NewQType)) {
const FunctionType *OldFuncType = OldQType->getAs();
const FunctionType *NewFuncType = NewQType->getAs();
const FunctionProtoType *OldProto = nullptr;
if (MergeTypeWithOld && isa(NewFuncType) &&
(OldProto = dyn_cast(OldFuncType))) {
  // The old declaration provided a function prototype, but the
  // new declaration does not. Merge in the prototype.
```

` isa(NewFuncType)` is false in this particular case, 
however `New` doesn't have a prototype (i.e. `New->hasPrototype()` is false). 
One fix might be to replace `isa(NewFuncType)` with 

```
(isa(NewFuncType) || !New->hasPrototype())
```

However, I don't really know this code well enough to know if that's the right 
fix.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116635/new/

https://reviews.llvm.org/D116635

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


[PATCH] D116016: [Clang] [PowerPC] Emit module flag for current float abi

2022-01-04 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf updated this revision to Diff 397443.
qiucf added a comment.

Only emit the flags when any instance of `long double` is used.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116016/new/

https://reviews.llvm.org/D116016

Files:
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/CodeGen/CodeGenTypes.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/ppc64-float-abi-attr.c

Index: clang/test/CodeGen/ppc64-float-abi-attr.c
===
--- /dev/null
+++ clang/test/CodeGen/ppc64-float-abi-attr.c
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu %s -emit-llvm -mabi=ieeelongdouble -o - | FileCheck %s --check-prefix=IEEE
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu %s -emit-llvm -mlong-double-64 -o - | FileCheck %s --check-prefix=LDBL64
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu %s -emit-llvm -DNOLDBL -o - | FileCheck %s --check-prefix=NOLDBL
+
+#ifndef NOLDBL
+long double foo(long double a, long double b) {
+  return a + b;
+}
+#endif
+
+int bar() { return 1; }
+
+// CHECK: !{{[0-9]+}} = !{i32 1, !"float-abi", !"doubledouble"}
+// IEEE: !{{[0-9]+}} = !{i32 1, !"float-abi", !"ieeequad"}
+// LDBL64: !{{[0-9]+}} = !{i32 1, !"float-abi", !"ieeedouble"}
+// NOLDBL-NOT: !{{[0-9]+}} = !{i32 1, !"float-abi"
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -5030,6 +5030,10 @@
 
   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction ,
llvm::Value *Address) const override;
+
+  void emitTargetMetadata(CodeGen::CodeGenModule ,
+  const llvm::MapVector
+  ) const override;
 };
 
 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
@@ -5443,6 +5447,24 @@
  /*IsAIX*/ false);
 }
 
+void PPC64_SVR4_TargetCodeGenInfo::emitTargetMetadata(
+CodeGen::CodeGenModule ,
+const llvm::MapVector ) const {
+  if (CGM.getTypes().isLongDoubleReferenced()) {
+llvm::LLVMContext  = CGM.getLLVMContext();
+const auto *flt = ().getLongDoubleFormat();
+if (flt == ::APFloat::PPCDoubleDouble())
+  CGM.getModule().addModuleFlag(llvm::Module::Error, "float-abi",
+llvm::MDString::get(Ctx, "doubledouble"));
+else if (flt == ::APFloat::IEEEquad())
+  CGM.getModule().addModuleFlag(llvm::Module::Error, "float-abi",
+llvm::MDString::get(Ctx, "ieeequad"));
+else if (flt == ::APFloat::IEEEdouble())
+  CGM.getModule().addModuleFlag(llvm::Module::Error, "float-abi",
+llvm::MDString::get(Ctx, "ieeedouble"));
+  }
+}
+
 bool
 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction ,
 llvm::Value *Address) const {
Index: clang/lib/CodeGen/CodeGenTypes.h
===
--- clang/lib/CodeGen/CodeGenTypes.h
+++ clang/lib/CodeGen/CodeGenTypes.h
@@ -95,6 +95,9 @@
   /// a recursive struct conversion, set this to true.
   bool SkippedLayout;
 
+  /// True if any instance of long double types are used.
+  bool LongDoubleReferenced;
+
   SmallVector DeferredRecords;
 
   /// This map keeps cache of llvm::Types and maps clang::Type to
@@ -310,6 +313,9 @@
 return RecordsBeingLaidOut.count(Ty);
   }
 
+  bool isLongDoubleReferenced() const {
+return LongDoubleReferenced;
+  }
 };
 
 }  // end namespace CodeGen
Index: clang/lib/CodeGen/CodeGenTypes.cpp
===
--- clang/lib/CodeGen/CodeGenTypes.cpp
+++ clang/lib/CodeGen/CodeGenTypes.cpp
@@ -33,6 +33,7 @@
 Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
 TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
   SkippedLayout = false;
+  LongDoubleReferenced = false;
 }
 
 CodeGenTypes::~CodeGenTypes() {
@@ -507,10 +508,12 @@
   Context.getLangOpts().NativeHalfType ||
   !Context.getTargetInfo().useFP16ConversionIntrinsics());
   break;
+case BuiltinType::LongDouble:
+  LongDoubleReferenced = true;
+  LLVM_FALLTHROUGH;
 case BuiltinType::BFloat16:
 case BuiltinType::Float:
 case BuiltinType::Double:
-case BuiltinType::LongDouble:
 case BuiltinType::Float128:
 case BuiltinType::Ibm128:
   ResultType = getTypeForFormat(getLLVMContext(),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D100282: [Coroutines] Set presplit attribute in Clang instead of CoroEarly pass

2022-01-04 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu closed this revision.
ChuanqiXu added a comment.

This should be covered in: https://reviews.llvm.org/D115790


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D100282/new/

https://reviews.llvm.org/D100282

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


[clang] c75cedc - [Coroutines] Set presplit attribute in Clang and mlir

2022-01-04 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-01-05T10:25:02+08:00
New Revision: c75cedc237f9747c5d5fe2a312d5ccc8531e2e70

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

LOG: [Coroutines] Set presplit attribute in Clang and mlir

This fixes bug49264.

Simply, coroutine shouldn't be inlined before CoroSplit. And the marker
for pre-splited coroutine is created in CoroEarly pass, which ran after
AlwaysInliner Pass in O0 pipeline. So that the AlwaysInliner couldn't
detect it shouldn't inline a coroutine. So here is the error.

This patch set the presplit attribute in clang and mlir. So the inliner
would always detect the attribute before splitting.

Reviewed By: rjmccall, ezhulenev

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

Added: 
clang/test/CodeGenCoroutines/coro-attributes.cpp
mlir/test/mlir-opt/async.mlir

Modified: 
clang/lib/CodeGen/CGCoroutine.cpp
clang/test/CodeGenCoroutines/coro-always-inline.cpp
llvm/docs/Coroutines.rst
llvm/lib/Transforms/Coroutines/CoroEarly.cpp
llvm/lib/Transforms/Coroutines/CoroInternal.h
llvm/test/Transforms/Coroutines/coro-async.ll
llvm/test/Transforms/Coroutines/coro-debug-O2.ll
llvm/test/Transforms/Coroutines/coro-debug-coro-frame.ll
llvm/test/Transforms/Coroutines/coro-debug-dbg.values-not_used_in_frame.ll
llvm/test/Transforms/Coroutines/coro-debug-dbg.values.ll
llvm/test/Transforms/Coroutines/coro-debug-frame-variable.ll
llvm/test/Transforms/Coroutines/coro-noalias-param.ll
llvm/test/Transforms/Coroutines/coro-split-01.ll
llvm/test/Transforms/Coroutines/coro-split-recursive.ll
llvm/test/Transforms/Coroutines/ex0.ll
llvm/test/Transforms/Coroutines/ex1.ll
llvm/test/Transforms/Coroutines/ex2.ll
llvm/test/Transforms/Coroutines/ex3.ll
llvm/test/Transforms/Coroutines/ex4.ll
llvm/test/Transforms/Coroutines/ex5.ll
llvm/test/Transforms/Coroutines/phi-coro-end.ll
llvm/test/Transforms/Coroutines/restart-trigger.ll
mlir/lib/Dialect/Async/Transforms/AsyncToAsyncRuntime.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCoroutine.cpp 
b/clang/lib/CodeGen/CGCoroutine.cpp
index 2041d2a5b4c95..c1763cbbc5a05 100644
--- a/clang/lib/CodeGen/CGCoroutine.cpp
+++ b/clang/lib/CodeGen/CGCoroutine.cpp
@@ -707,6 +707,10 @@ void CodeGenFunction::EmitCoroutineBody(const 
CoroutineBodyStmt ) {
 
   if (Stmt *Ret = S.getReturnStmt())
 EmitStmt(Ret);
+
+  // LLVM require the frontend to add the function attribute. See
+  // Coroutines.rst.
+  CurFn->addFnAttr("coroutine.presplit", "0");
 }
 
 // Emit coroutine intrinsic and patch up arguments of the token type.

diff  --git a/clang/test/CodeGenCoroutines/coro-always-inline.cpp 
b/clang/test/CodeGenCoroutines/coro-always-inline.cpp
index 39a82960e8db9..19f52af74a775 100644
--- a/clang/test/CodeGenCoroutines/coro-always-inline.cpp
+++ b/clang/test/CodeGenCoroutines/coro-always-inline.cpp
@@ -48,3 +48,15 @@ struct coroutine_traits {
 // CHECK: [[CAST3:%[0-9]+]] = bitcast %"struct.std::awaitable"* %ref.tmp{{.*}} 
to i8*
 // CHECK-NEXT: call void @llvm.lifetime.end.p0i8(i64 1, i8* [[CAST3]])
 void foo() { co_return; }
+
+// Check that bar is not inlined even it's marked as always_inline.
+
+// CHECK-LABEL:   define {{.*}} void @_Z3bazv()
+// CHECK: call void @_Z3barv(
+__attribute__((__always_inline__)) void bar() {
+  co_return;
+}
+void baz() {
+  bar();
+  co_return;
+}

diff  --git a/clang/test/CodeGenCoroutines/coro-attributes.cpp 
b/clang/test/CodeGenCoroutines/coro-attributes.cpp
new file mode 100644
index 0..df18e0c046bf0
--- /dev/null
+++ b/clang/test/CodeGenCoroutines/coro-attributes.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++20 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
+#include "Inputs/coroutine.h"
+
+using namespace std;
+
+struct coro {
+  struct promise_type {
+coro get_return_object();
+suspend_never initial_suspend();
+suspend_never final_suspend() noexcept;
+void return_void();
+static void unhandled_exception();
+  };
+};
+
+// CHECK: void @_Z3foov() #[[FOO_ATTR_NUM:[0-9]+]]
+// CHECK: attributes #[[FOO_ATTR_NUM]] = { {{.*}} "coroutine.presplit"="0"
+coro foo() {
+  co_await suspend_always{};
+}

diff  --git a/llvm/docs/Coroutines.rst b/llvm/docs/Coroutines.rst
index 5e6bc233280ba..dfb3d1b6081dd 100644
--- a/llvm/docs/Coroutines.rst
+++ b/llvm/docs/Coroutines.rst
@@ -1175,6 +1175,8 @@ duplicated.
 
 A frontend should emit exactly one `coro.id` intrinsic per coroutine.
 
+A frontend should emit function attribute `"coroutine.presplit"` for the 
coroutine.
+
 .. _coro.id.async:
 
 'llvm.coro.id.async' Intrinsic
@@ -1214,6 +1216,8 @@ Semantics:
 
 A frontend should emit exactly one `coro.id.async` intrinsic per coroutine.
 
+A 

[PATCH] D116638: [ClangFormat] Fix ignoring JavaScriptWrapImport when ColumnWidth: 0

2022-01-04 Thread Andrey Mishchenko via Phabricator via cfe-commits
andmis created this revision.
andmis added a reviewer: MyDeveloperDay.
andmis added a project: clang-format.
andmis requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Prior to this patch, when ColumnWidth: 0, all JS imports of the form `import 
{aaa, bbb, ccc} from "def";` would be formatted as multi-line, and the 
JavaScriptWrapImport flag had no effect (in most cases). This patch makes it so 
that when ColumnWidth: 0, the JavaScriptWrapImport flag causes multi-line 
imports, for example

  import {
aaa,
bbb,
ccc
  } from "jkl";

to be left alone. If JavaScriptWrapImport: false, then imports of this form are 
unwrapped to a single line in all cases, regardless of ColumnWidth. The 
behavior for ColumnWidth > 0 is unchanged.

Fixes: https://github.com/llvm/llvm-project/issues/52935


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116638

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/lib/Format/ContinuationIndenter.cpp
  clang/unittests/Format/FormatTestJS.cpp

Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -1943,10 +1943,12 @@
 }
 
 TEST_F(FormatTestJS, ImportWrapping) {
+  FormatStyle Style = getGoogleJSStyleWithColumns(80);
+  Style.JavaScriptWrapImports = false;
   verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
" VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
-   "} from 'some/module.js';");
-  FormatStyle Style = getGoogleJSStyleWithColumns(80);
+   "} from 'some/module.js';",
+   Style);
   Style.JavaScriptWrapImports = true;
   verifyFormat("import {\n"
"  VeryLongImportsAreAnnoying,\n"
@@ -1964,8 +1966,28 @@
"  A,\n"
"} from 'some/module.js';",
Style);
+  Style.ColumnLimit = 0;
+  Style.JavaScriptWrapImports = false;
+  verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
+   " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
+   "} from 'some/module.js';",
+   Style);
+  // Using the input_code/expected version of verifyFormat because we can't
+  // indiscriminately test::messUp on these tests.
+  Style.JavaScriptWrapImports = true;
+  verifyFormat("import {\n"
+   "  A,\n"
+   "  A,\n"
+   "} from 'some/module.js';\n"
+   "import {B, B} from 'other/module.js';",
+   "import {\n"
+   "  A,\n"
+   "  A,\n"
+   "} from 'some/module.js';\n"
+   "import {B, B} from 'other/module.js';",
+   Style);
   Style.ColumnLimit = 40;
-  // Using this version of verifyFormat because test::messUp hides the issue.
+  Style.JavaScriptWrapImports = true;
   verifyFormat("import {\n"
"  A,\n"
"} from\n"
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -325,12 +325,19 @@
   if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
 return false;
 
+  if (Style.isJavaScript() && State.Line->Type == LT_ImportStatement &&
+  !Style.JavaScriptWrapImports)
+return false;
+
   return !State.Stack.back().NoLineBreak;
 }
 
 bool ContinuationIndenter::mustBreak(const LineState ) {
   const FormatToken  = *State.NextToken;
   const FormatToken  = *Current.Previous;
+  if (Style.isJavaScript() && State.Line->Type == LT_ImportStatement &&
+  Style.ColumnLimit == 0)
+return false;
   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
   Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
 auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2817,22 +2817,51 @@
string1 = "foo";
string2 = "bar";
 
+**JavaScriptWrapImports** (``Boolean``) :versionbadge:`clang-format 3.9`
+  Whether to wrap JavaScript import/export statements. If ``false``, then
+  every import statement will be unwrapped to a single line.
 
+  If ``JavaScriptWrapImports`` is ``true``, then the behavior depends on the
+  value of ``ColumnWidth``:
 
-**JavaScriptWrapImports** (``Boolean``) :versionbadge:`clang-format 3.9`
-  Whether to wrap JavaScript import/export statements.
+  * If ``ColumnWidth`` is 0 (no limit on the number of columns), then import
+statements will keep the number of lines they start with.
+
+  * If ``ColumnWidth`` is non-zero (there is a limit on the number of
+ 

[PATCH] D116518: [ast-matchers] Add hasSubstatementSequence matcher

2022-01-04 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked an inline comment as done.
LegalizeAdulthood added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:5435-5442
+/// Matches two consecutive statements within a compound statement.
+///
+/// Given
+/// \code
+///   { if (x > 0) return true; return false; }
+/// \endcode
+/// compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt()))

aaron.ballman wrote:
> LegalizeAdulthood wrote:
> > aaron.ballman wrote:
> > > How do we extend this to support testing arbitrary sequences of 
> > > statements? (If this supports two statements, someone will find a need 
> > > for three, etc).
> > Yeah, I was wondering that too.  I didn't see (but didn't look extensively) 
> > any support for variadic matchers taking a parameter pack.
> > 
> > I stopped at 2 because this suits my immediate needs with 
> > `readability-simplify-boolean-expr` where I have to manually loop over 
> > `CompoundStmt` matches in order to verify that the `if (x) return true; 
> > return false;` constructs consist of two adjacent statements.
> I don't think we have any variadic matchers yet to model on, but I think if 
> this is only needed for one check, we can add it in the current form as a 
> local matcher for that check. Whenever we figure out how to give the better 
> interface through the static and dynamic matchers, then we can figure out how 
> to lift this to the general matcher interface.
> 
> WDYT?
I don't think it is harmful to make it visible to all and I think it is helpful.
Defining it in ASTMatchers, enables using it in `clang-query`, for instance.



CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116518/new/

https://reviews.llvm.org/D116518

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


[PATCH] D116637: [Clang][Sema][OpenMP] Sema support for `atomic compare`

2022-01-04 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 created this revision.
tianshilei1992 added reviewers: jdoerfert, ABataev.
Herald added subscribers: guansong, yaxunl.
tianshilei1992 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This patch adds the Sema support for `atomic compare`.
Note: codegen will come next where tests will be added.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116637

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaOpenMP.cpp

Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -10916,6 +10916,367 @@
   }
   return ErrorFound != NoError;
 }
+
+/// Get the node id of the fixed point of an expression \a S.
+llvm::FoldingSetNodeID getNodeId(ASTContext , const Expr *S) {
+  llvm::FoldingSetNodeID Id;
+  S->IgnoreParenImpCasts()->Profile(Id, Context, true);
+  return Id;
+}
+
+/// Check if two expressions are same.
+bool checkIfTwoExprsAreSame(ASTContext , const Expr *LHS,
+const Expr *RHS) {
+  return getNodeId(Context, LHS) == getNodeId(Context, RHS);
+}
+
+Expr *generateLHSCondExpr(Sema , BinaryOperator *Cond, Expr *X) {
+  if (!Cond)
+return nullptr;
+  if (Cond->getOpcode() != BO_LT && Cond->getOpcode() != BO_GT)
+return nullptr;
+  if (Cond->getOpcode() == BO_EQ)
+return Cond;
+  if (checkIfTwoExprsAreSame(SemaRef.getASTContext(), X, Cond->getLHS()))
+return Cond;
+
+  BinaryOperatorKind Op = Cond->getOpcode() == BO_LT ? BO_GT : BO_LT;
+  ExprResult Result =
+  SemaRef.CreateBuiltinBinOp(Cond->getOperatorLoc(), Op, X, Cond->getLHS());
+  assert(!Result.isInvalid());
+  return Result.get();
+}
+
+class OpenMPAtomicCompareChecker {
+public:
+  /// All kinds of errors that can occur in `atomic compare`
+  enum ErrorTy {
+/// Empty compound statement.
+NoStmt = 0,
+/// More than one statement in a compound statement.
+MoreThanOneStmt,
+/// Not an assignment binary operator.
+NotAnAssignment,
+/// Not a conditional operator.
+NotCondOp,
+/// Wrong false expr. According to the spec, 'x' should be at the false
+/// expression of a conditional expression.
+WrongFalseExpr,
+/// The condition of a conditional expression is not a binary operator.
+NotABinaryOp,
+/// Invalid binary operator (not <, >, or ==).
+InvalidBinaryOp,
+/// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x).
+InvalidComparison,
+/// X is not a lvalue.
+XNotLValue,
+/// Not a scalar integer.
+NotScalarInteger,
+/// No error.
+NoError,
+  };
+
+  struct ErrorInfoTy {
+ErrorTy Error;
+SourceLocation ErrorLoc;
+SourceRange ErrorRange;
+SourceLocation NoteLoc;
+SourceRange NoteRange;
+  };
+
+  OpenMPAtomicCompareChecker(Sema )
+  : SemaRef(S), ContextRef(S.getASTContext()) {}
+
+  /// Check if statement \a S is valid for atomic compare.
+  bool checkStmt(Stmt *S, ErrorInfoTy );
+
+private:
+  /// Reference to Sema.
+  Sema 
+  /// Reference to ASTContext
+  ASTContext 
+  /// 'x' lvalue part of the source atomic expression.
+  Expr *X = nullptr;
+  /// 'expr' or 'e' rvalue part of the source atomic expression.
+  Expr *E = nullptr;
+  /// 'd' rvalue part of the source atomic expression.
+  Expr *D = nullptr;
+  /// 'cond' part of the source atomic expression. It is in one of the following
+  /// forms:
+  /// expr ordop x
+  /// x ordop expr
+  /// x == e
+  /// e == x
+  /// If 'x' is on RHS, a corresponding LHS version will be generated for
+  /// convenience by calling function \p generateLHSCondExpr.
+  /// 'ordop' can only be '<' or '>'.
+  Expr *C = nullptr;
+
+  /// Check if it is a valid conditional update statement (cond-update-stmt).
+  bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy );
+
+  /// Check if it is a valid conditional expression statement (cond-expr-stmt).
+  bool checkCondExprStmt(Stmt *S, ErrorInfoTy );
+
+  /// Check if all captured values have right type.
+  bool checkType(ErrorInfoTy ) const;
+};
+
+bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S,
+ ErrorInfoTy ) {
+  auto *Then = S->getThen();
+  if (auto *CS = dyn_cast(Then)) {
+if (CS->size() == 0) {
+  ErrorInfo.Error = ErrorTy::NoStmt;
+  ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
+  ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
+  return false;
+}
+if (CS->size() > 1) {
+  ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
+  ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
+  ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
+  return false;
+}
+Then = CS->body_front();
+  }
+
+  auto *BO = dyn_cast(Then);
+  if (!BO) {
+ErrorInfo.Error = ErrorTy::NotAnAssignment;
+

[PATCH] D115867: [C++20] [Coroutines] Warning for always_inline coroutine

2022-01-04 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:0-3
+def warn_always_inline_coroutine : Warning<
+  "A coroutine marked always_inline might not be inlined properly."
+  >,
+  InGroup;

Quuxplusone wrote:
> ChuanqiXu wrote:
> > Quuxplusone wrote:
> > > ChuanqiXu wrote:
> > > > Quuxplusone wrote:
> > > > > FWIW, this message isn't particularly helpful to the reader. My code 
> > > > > "might" not be optimized "properly"? Does that mean it might be 
> > > > > mis-optimized, improperly, and thus break in some way at runtime? Or 
> > > > > is the compiler just saying that the attribute will be ignored? Or 
> > > > > that it //might// be ignored, but it might not? How do I (the 
> > > > > programmer) know whether the bad thing will happen?
> > > > > 
> > > > > I think as a programmer what I'd //like// to see here is just `"the 
> > > > > '%0' attribute has no effect on coroutines"`. That's very clear, and 
> > > > > easy to understand. Does that wording reflect what the compiler 
> > > > > actually //does//, though?
> > > > Thanks for suggestion. The actual behavior isn't easy to describe and 
> > > > understand. Since a coroutine would be splitted into pieces. And the 
> > > > original function would be reduced and we would call it 'ramp function' 
> > > > in compiler. And the call to other new functions would be indirect 
> > > > call. The compiler couldn't inline indirect call. But the compiler 
> > > > **might** convert the indirect call into direct call so that they could 
> > > > be inlined.
> > > > 
> > > > In summary, the actual behavior might be described as: "Only the ramp 
> > > > function are guaranteed to be inlined and the other new functions may 
> > > > or may not get inlined". But the term "ramp funciton" is used in 
> > > > compiler only (Some guys in LWG/LEWG know it too). And I believe the 
> > > > term shouldn't leak to other users. So I chose the current description. 
> > > > 
> > > > BTW, I thought the fact that coroutine would be splitted should be 
> > > > transparent to users too. This is the reason why I wrote previous 
> > > > message. But your words make sense. And I couldn't find methods to make 
> > > > it more clear and don't tell the user about coroutine splitting.
> > > IIUC, `"this coroutine will be split into pieces; only the first piece 
> > > will be inlined"` or simply `"the '%0' attribute applies to only the 
> > > initial piece of this coroutine"`. Possible synonyms for "piece" include 
> > > "section", "segment", "chunk". Is there any standardese for "the run of 
> > > stuff in between two suspension points"?
> > > 
> > > However, I stand by my initial comment that this message is not helpful 
> > > to the programmer. It's warning me that something bad will happen, right? 
> > > Instead of having that bad thing happen, why don't you just make the 
> > > compiler //ignore the attribute// in this situation?
> > > 
> > > If your answer is "Because always-inlining the initial piece isn't always 
> > > bad; maybe the programmer thinks it's //good//, and //wants// it to 
> > > happen," then this shouldn't be a `warning` at all; it should just be 
> > > documented in the attribute's documentation. Warnings should be for 
> > > bad/unintentional things, not for things someone might do on purpose.
> > >  Is there any standardese for "the run of stuff in between two suspension 
> > > points"?
> > 
> > AFAIK, there is no standard terms for it.
> > 
> > ---
> > 
> > Very Sorry, I made a mistake in previous comment. The behavior for 
> > always-inline ramp function should be: "The ramp function is guaranteed to 
> > get inlined with optimization turned on." It implies that ramp function 
> > wouldn't get inlined in O0. This is what I am trying to do in: 
> > https://reviews.llvm.org/D115790. The current behavior for always-inline 
> > coroutine in O0 would be a crash. Here is an example: 
> > https://godbolt.org/z/zssKxTPM5.
> > 
> > And GCC would warn and ban for the always-inline coroutine too: 
> > https://godbolt.org/z/7eajb1Gf8. (I understand that it isn't a good 
> > argument to say GCC did so. Just a information sharing)
> > 
> > --- 
> > 
> > > Warnings should be for bad/unintentional things, not for things someone 
> > > might do on purpose.
> > 
> > My point is that the behavior and semantic is inconsistent. The programmer 
> > might think the whole coroutine would be inlined. However, it is not the 
> > case. I think it is worth a warning.
> >>! In D115867#3218653, @ChuanqiXu wrote:
> > @Quuxplusone do you feel good with the current message?
> 
> No, it's definitely still ungrammatical English, so it shouldn't ship in this 
> state.
> Also, I think my entire previous comment stands — both the suggestions for 
> improving the English (without much changing the meaning), and my 
> higher-level suggestion that you should just change the compiler's behavior 
> to //just quietly do the 

[PATCH] D116635: Add warning to detect when calls passing arguments are made to functions without prototypes.

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher added a comment.

Patch https://reviews.llvm.org/D116636 demonstrates the changes needed if the 
warning was enabled by default:


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116635/new/

https://reviews.llvm.org/D116635

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


[PATCH] D116636: [WIP] Enable `-Wstrict-calls-without-prototype` by default

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher added a comment.

This change depends on https://reviews.llvm.org/D116635.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116636/new/

https://reviews.llvm.org/D116636

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


[PATCH] D116636: [WIP] Enable `-Wstrict-calls-without-prototype` by default

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher created this revision.
delcypher added reviewers: arphaman, rapidsna, fcloutier, NoQ.
delcypher requested review of this revision.
Herald added a project: clang.

This patch enables the `-Wstrict-calls-without-prototype` warning by
default and fixes the existing clang test suite to pass.

This patch is considered work-in-progress because the patch it is
based on is not finalized. It is also unclear at this point whether this 
warning should actually
be enabled by default. So this patch serves to illustrate the changes
that would need to be made to have the warning on by default.

rdar://87118271


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116636

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/test/Analysis/casts.c
  clang/test/Analysis/inline.c
  clang/test/Analysis/misc-ps-region-store.m
  clang/test/Analysis/misc-ps.m
  clang/test/Analysis/null-deref-ps.c
  clang/test/Analysis/solver-sym-simplification-adjustment.c
  clang/test/Analysis/solver-sym-simplification-concreteint.c
  clang/test/CodeGen/functions.c
  clang/test/Sema/arg-duplicate.c
  clang/test/Sema/block-misc.c
  clang/test/Sema/extern-redecl.c
  clang/test/Sema/function-redecl.c
  clang/test/Sema/function.c
  clang/test/Sema/knr-def-call.c
  clang/test/Sema/knr-variadic-def.c
  clang/test/Sema/merge-decls.c
  clang/test/Sema/sizeless-1.c
  clang/test/Sema/unused-expr.c
  clang/test/SemaObjC/nonnull.m
  clang/test/SemaObjC/protocol-archane.m

Index: clang/test/SemaObjC/protocol-archane.m
===
--- clang/test/SemaObjC/protocol-archane.m
+++ clang/test/SemaObjC/protocol-archane.m
@@ -5,6 +5,8 @@
 - (void) bar;
 @end
 
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wstrict-calls-without-prototype"
 void bar();
 void foo(id x) {
   bar((short)x); // expected-error {{expected ')'}} expected-note {{to match this '('}}
@@ -12,6 +14,7 @@
 
   [()x bar];  // expected-warning {{protocol has no object type specified; defaults to qualified 'id'}}
 }
+#pragma clang diagnostic pop
 
 @protocol MyProtocol
 - (void)doSomething;
Index: clang/test/SemaObjC/nonnull.m
===
--- clang/test/SemaObjC/nonnull.m
+++ clang/test/SemaObjC/nonnull.m
@@ -23,8 +23,8 @@
 extern void func4 (void (^block1)(), void (^block2)()) __attribute__((nonnull(1)))
 __attribute__((nonnull(2)));
 
-void func6();
-void func7();
+void func6(NSObject *);
+void func7(NSObject *);
 
 void
 foo (int i1, int i2, int i3, void (^cp1)(), void (^cp2)(), void (^cp3)())
@@ -63,7 +63,7 @@
 __attribute__((nonnull))
 void _dispatch_queue_push_list(dispatch_object_t _head); // no warning
 
-void func6(dispatch_object_t _head) {
+void func8(dispatch_object_t _head) {
   _dispatch_queue_push_list(0); // expected-warning {{null passed to a callee that requires a non-null argument}}
   _dispatch_queue_push_list(_head._do);  // no warning
 }
Index: clang/test/Sema/unused-expr.c
===
--- clang/test/Sema/unused-expr.c
+++ clang/test/Sema/unused-expr.c
@@ -79,10 +79,9 @@
   t5f();   // expected-warning {{ignoring return value of function declared with 'warn_unused_result' attribute}}
 }
 
-
 int fn1() __attribute__ ((warn_unused_result));
-int fn2() __attribute__ ((pure));
-int fn3() __attribute__ ((__const));
+int fn2(int, int) __attribute__((pure));
+int fn3(int) __attribute__((__const));
 // rdar://6587766
 int t6() {
   if (fn1() < 0 || fn2(2,1) < 0 || fn3(2) < 0)  // no warnings
@@ -129,18 +128,18 @@
 #define NOP(a) (a)
 #define M1(a, b) (long)foo((a), (b))
 #define M2 (long)0;
-#define M3(a) (t3(a), fn2())
+#define M3(a) (t3(a), fn2(0, 1))
 #define M4(a, b) (foo((a), (b)) ? 0 : t3(a), 1)
 #define M5(a, b) (foo((a), (b)), 1)
 #define M6() fn1()
-#define M7() fn2()
+#define M7() fn2(0, 1)
 void t11(int i, int j) {
   M1(i, j);  // no warning
   NOP((long)foo(i, j)); // expected-warning {{expression result unused}}
   M2;  // no warning
   NOP((long)0); // expected-warning {{expression result unused}}
   M3(i); // no warning
-  NOP((t3(i), fn2())); // expected-warning {{ignoring return value}}
+  NOP((t3(i), fn2(0, 0))); // expected-warning {{ignoring return value}}
   M4(i, j); // no warning
   NOP((foo(i, j) ? 0 : t3(i), 1)); // expected-warning {{expression result unused}}
   M5(i, j); // no warning
Index: clang/test/Sema/sizeless-1.c
===
--- clang/test/Sema/sizeless-1.c
+++ clang/test/Sema/sizeless-1.c
@@ -42,7 +42,7 @@
 void __attribute__((overloadable)) overf16(svint16_t); // expected-note + {{not viable}}
 void __attribute__((overloadable)) overf16(int);   // expected-note + {{not viable}}
 
-void noproto();
+void noproto(); // expected-note{{'noproto' declared here}}
 void varargs(int, ...);
 
 void unused() {
@@ -174,7 +174,7 @@
   overf16(local_int8); // expected-error {{no 

[PATCH] D116635: Add warning to detect when calls passing arguments are made to functions without prototypes.

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher added inline comments.



Comment at: clang/test/Sema/warn-calls-without-prototype.c:39
+  return a + b +c;
+}
+

@NoQ Any ideas about this?  It seems kind of weird that when merging 
`not_a_prototype3` prototype with the K style definition of 
`not_a_prototype3` that the resulting FunctionDecl we see at the call site in 
`call_to_function_without_prototype3` is marked as not having a prototype.

If I flip the order (see `not_a_prototype6`) then the merged declaration is 
marked as having a prototype.

I'm not sure if this is a bug in `Sema::MergeFunctionDecl` or if this just a 
peculiarity of K style function definitions.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116635/new/

https://reviews.llvm.org/D116635

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


[PATCH] D116635: Add warning to detect when calls passing arguments are made to functions without prototypes.

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher updated this revision to Diff 397431.
delcypher added a comment.

Add another test case for function definitions without prototypes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116635/new/

https://reviews.llvm.org/D116635

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/warn-calls-without-prototype.c

Index: clang/test/Sema/warn-calls-without-prototype.c
===
--- /dev/null
+++ clang/test/Sema/warn-calls-without-prototype.c
@@ -0,0 +1,151 @@
+// RUN: %clang_cc1 -triple i386-pc-unknown -fsyntax-only -Wstrict-calls-without-prototype -std=c99 -verify %s
+
+//--
+// Expected -Wstrict-calls-without-prototype warnings
+//--
+
+unsigned not_a_prototype();
+
+unsigned call_to_function_without_prototype(void) {
+  // expected-warning@+2{{calling function 'not_a_prototype' with arguments when function has no prototype}}
+  // expected-note@-4{{'not_a_prototype' declared here}}
+  return not_a_prototype(1);
+}
+
+// K style function declaration has no proto-type
+unsigned not_a_prototype2(a, b)
+int a;
+int b;
+{
+  return a + b;
+}
+
+unsigned call_to_function_without_prototype2(void) {
+  // expected-warning@+2{{calling function 'not_a_prototype2' with arguments when function has no prototype}}
+  // expected-note@-9{{'not_a_prototype2' declared here}}
+  return not_a_prototype2(1, 2);
+}
+
+// K style function seems to "hide" the prototype because the merged
+// FunctionDecl seems to not have a prototype.
+// FIXME(dliew): Is this a bug in `Sema::MergeFunctionDecl`?
+unsigned not_a_prototype3(int a, int b, int c); // Start with a prototype
+unsigned not_a_prototype3(a, b, c )
+  int a;
+  int b;
+  int c;
+{
+  return a + b +c;
+}
+
+unsigned call_to_function_without_prototype3(void) {
+  // FIXME(dliew): Should we actually warn about this? There is a prototype it
+  // just gets hidden when the FunctionDecls get merged.
+  // expected-warning@+2{{calling function 'not_a_prototype3' with arguments when function has no prototype}}
+  // expected-note@-12{{'not_a_prototype3' declared here}}
+  return not_a_prototype3(1, 2, 3);
+}
+
+// Merging two FunctionDecls without prototypes should result in a FunctionDecl without a prototype.
+unsigned not_a_prototype4(); // Start with something that has no prototype.
+unsigned not_a_prototype4(a, b, c)
+  int a;
+  int b;
+  int c;
+{
+  return a + b +c;
+}
+
+unsigned call_to_function_without_prototype4(void) {
+  // expected-warning@+2{{calling function 'not_a_prototype4' with arguments when function has no prototype}}
+  // expected-note@-10{{'not_a_prototype4' declared here}}
+  return not_a_prototype4(1, 2, 3);
+}
+
+// Definition does not have a prototype
+unsigned not_a_prototype5() {
+  return 0;
+}
+
+unsigned call_to_function_without_prototype5(void) {
+  // expected-warning@+3{{too many arguments in call to 'not_a_prototype5'}}
+  // expected-warning@+2{{calling function 'not_a_prototype5' with arguments when function has no prototype}}
+  // expected-note@-7{{'not_a_prototype5' declared here}}
+  return not_a_prototype5(1, 2, 3);
+}
+
+//--
+// No expected warnings from -Wstrict-calls-without-prototype
+//--
+
+unsigned call_to_function_without_declartion(void) {
+  // `-Wstrict-calls-without-prototype` doesn't emit a warning here because
+  // `-Wimplicit-function-declaration` cover this.
+  // expected-warning@+1{{implicit declaration of function 'function_without_declaration' is invalid in C99}}
+  return function_without_declaration(5);
+}
+
+unsigned call_builtins(void) {
+  // Builtin with a signature
+  int *alloc = (int *)__builtin_alloca(sizeof(int)); // no warning
+  *alloc = 5;
+
+  // Builtin without a meaningful signature
+  int gt = __builtin_isgreater(0.0, 0.1); // no warning
+
+  return *alloc + gt;
+}
+
+unsigned provides_prototype(int *a);
+unsigned provides_prototype_from_definition(int *a) {
+  return a[1];
+}
+unsigned provides_prototype2(void) {
+  return 0;
+}
+unsigned call_prototypes(void) {
+  int a[] = {0, 1, 2};
+  int result = provides_prototype_from_definition(a); // no warning
+  int result2 = provides_prototype(a); // no warning
+  // Deliberately pass arguments. Even in this case
+  //`-Wstrict-calls-without-prototype` should not fire.
+  // expected-error@+2{{too many arguments to function call, expected 0, have 1}}
+  // expected-note@-10{{'provides_prototype2' declared here}}
+  int result3 = provides_prototype2(5);
+  return result + result2 + result3;
+}
+
+unsigned will_be_refined();
+unsigned will_be_refined(void *); // refine the decl to be a 

[PATCH] D116635: Add warning to detect when calls passing arguments are made to functions without prototypes.

2022-01-04 Thread Dan Liew via Phabricator via cfe-commits
delcypher created this revision.
delcypher added reviewers: arphaman, rapidsna, fcloutier, NoQ.
delcypher requested review of this revision.
Herald added a project: clang.

The warning is currently disabled by default but can be enabled with
`-Wstrict-calls-without-prototype`. Enabling it by default will be
handled by future patches.

The warning is intended to catch C code like this:

  int f(); // No prototype, accepts any number of arguments of any type.
  
  int call(void) {
return f(1, 2, 3);
  }

While code like this is legal it can very easily invoke undefined behavior
by passing the wrong number of arguments or wrong types.

The warning only fires when arguments are passed to make it less noisy, i.e.
so that the warning does not fire on code like this:

  int g();
  int call(void) {
  return g();
  }

While the above code could invoke undefined behavior, if the definition of 
`g()` takes no
arguments then the lack of a prototype is benign.

This warning while similar to `-Wstrict-prototypes` is distinct because
it warns at call sites rather at declarations.

This patch currently warns on calls to K style function declarations where a
previous declaration has a prototype. It is currently not clear if this is the 
correct behavior
as noted in the included test case.

rdar://87118271


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116635

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/warn-calls-without-prototype.c

Index: clang/test/Sema/warn-calls-without-prototype.c
===
--- /dev/null
+++ clang/test/Sema/warn-calls-without-prototype.c
@@ -0,0 +1,131 @@
+// RUN: %clang_cc1 -triple i386-pc-unknown -fsyntax-only -Wstrict-calls-without-prototype -std=c99 -verify %s
+
+//--
+// Expected -Wstrict-calls-without-prototype warnings
+//--
+
+unsigned not_a_prototype();
+
+unsigned call_to_function_without_prototype(void) {
+  // expected-warning@+2{{calling function 'not_a_prototype' with arguments when function has no prototype}}
+  // expected-note@-4{{'not_a_prototype' declared here}}
+  return not_a_prototype(1);
+}
+
+// K style function declaration has no proto-type
+unsigned not_a_prototype2(a, b)
+int a;
+int b;
+{
+  return a + b;
+}
+
+unsigned call_to_function_without_prototype2(void) {
+  // expected-warning@+2{{calling function 'not_a_prototype2' with arguments when function has no prototype}}
+  // expected-note@-9{{'not_a_prototype2' declared here}}
+  return not_a_prototype2(1, 2);
+}
+
+// K style function seems to "hide" the prototype because the merged
+// FunctionDecl seems to not have a prototype.
+// FIXME(dliew): Is this a bug in `Sema::MergeFunctionDecl`?
+unsigned not_a_prototype3(int a, int b, int c); // Start with a prototype
+unsigned not_a_prototype3(a, b, c )
+  int a;
+  int b;
+  int c;
+{
+  return a + b +c;
+}
+
+unsigned call_to_function_without_prototype3(void) {
+  // FIXME(dliew): Should we actually warn about this? There is a prototype it
+  // just gets hidden when the FunctionDecls get merged.
+  // expected-warning@+2{{calling function 'not_a_prototype3' with arguments when function has no prototype}}
+  // expected-note@-12{{'not_a_prototype3' declared here}}
+  return not_a_prototype3(1, 2, 3);
+}
+
+// Merging two FunctionDecls without prototypes should result in a FunctionDecl without a prototype.
+unsigned not_a_prototype4(); // Start with something that has no prototype.
+unsigned not_a_prototype4(a, b, c)
+  int a;
+  int b;
+  int c;
+{
+  return a + b +c;
+}
+
+unsigned call_to_function_without_prototype4(void) {
+  // expected-warning@+2{{calling function 'not_a_prototype4' with arguments when function has no prototype}}
+  // expected-note@-10{{'not_a_prototype4' declared here}}
+  return not_a_prototype4(1, 2, 3);
+}
+
+//--
+// No expected warnings from -Wstrict-calls-without-prototype
+//--
+
+unsigned call_to_function_without_declartion(void) {
+  // `-Wstrict-calls-without-prototype` doesn't emit a warning here because
+  // `-Wimplicit-function-declaration` cover this.
+  // expected-warning@+1{{implicit declaration of function 'function_without_declaration' is invalid in C99}}
+  return function_without_declaration(5);
+}
+
+unsigned call_builtins(void) {
+  // Builtin with a signature
+  int *alloc = (int *)__builtin_alloca(sizeof(int)); // no warning
+  *alloc = 5;
+
+  // Builtin without a meaningful signature
+  int gt = __builtin_isgreater(0.0, 0.1); // no warning
+
+  return *alloc + gt;
+}
+
+unsigned provides_prototype(int *a);
+unsigned provides_prototype_from_definition(int *a) {
+  return 

[PATCH] D116634: enable msan-eager-checks with -fsanitize-memory-param-retval.

2022-01-04 Thread Kevin Athey via Phabricator via cfe-commits
kda created this revision.
kda added a reviewer: vitalybuka.
Herald added subscribers: ormris, hiraditya.
kda requested review of this revision.
Herald added projects: clang, Sanitizers, LLVM.
Herald added subscribers: llvm-commits, Sanitizers, cfe-commits.

follow up to https://reviews.llvm.org/D116633


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116634

Files:
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  compiler-rt/test/msan/noundef_analysis.cpp
  llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
  llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -493,6 +493,9 @@
   MemorySanitizer(Module , MemorySanitizerOptions Options)
   : CompileKernel(Options.Kernel), TrackOrigins(Options.TrackOrigins),
 Recover(Options.Recover) {
+if (Options.EagerChecks) {
+  ClEagerChecks = Options.EagerChecks;
+}
 initializeModule(M);
   }
 
@@ -665,10 +668,12 @@
 
 } // end anonymous namespace
 
-MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K)
+MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K,
+   bool EagerChecks)
 : Kernel(getOptOrDefault(ClEnableKmsan, K)),
   TrackOrigins(getOptOrDefault(ClTrackOrigins, Kernel ? 2 : TO)),
-  Recover(getOptOrDefault(ClKeepGoing, Kernel || R)) {}
+  Recover(getOptOrDefault(ClKeepGoing, Kernel || R)),
+  EagerChecks(ClEagerChecks || EagerChecks) {}
 
 PreservedAnalyses MemorySanitizerPass::run(Function ,
FunctionAnalysisManager ) {
Index: llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
===
--- llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
+++ llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
@@ -19,11 +19,13 @@
 namespace llvm {
 
 struct MemorySanitizerOptions {
-  MemorySanitizerOptions() : MemorySanitizerOptions(0, false, false){};
-  MemorySanitizerOptions(int TrackOrigins, bool Recover, bool Kernel);
+  MemorySanitizerOptions() : MemorySanitizerOptions(0, false, false, false){};
+  MemorySanitizerOptions(int TrackOrigins, bool Recover, bool Kernel,
+ bool EagerChecks);
   bool Kernel;
   int TrackOrigins;
   bool Recover;
+  bool EagerChecks;
 };
 
 // Insert MemorySanitizer instrumentation (detection of uninitialized reads)
Index: compiler-rt/test/msan/noundef_analysis.cpp
===
--- compiler-rt/test/msan/noundef_analysis.cpp
+++ compiler-rt/test/msan/noundef_analysis.cpp
@@ -2,6 +2,8 @@
 // RUN: FileCheck %s --check-prefix=MISSED --allow-empty < %t.out
 // RUN: %clangxx_msan %s -Xclang -enable-noundef-analysis -mllvm -msan-eager-checks=1 -o %t && not %run %t >%t.out 2>&1
 // RUN: FileCheck %s < %t.out
+// RUN: %clangxx_msan %s -fsanitize-memory-param-retval -o %t && not %run %t >%t.out 2>&1
+// RUN: FileCheck %s < %t.out
 
 struct SimpleStruct {
   int md1;
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -637,6 +637,9 @@
 }
   }
 }
+MsanParamRetval = Args.hasFlag(
+options::OPT_fsanitize_memory_param_retval,
+options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
 MsanUseAfterDtor =
 Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
  options::OPT_fno_sanitize_memory_use_after_dtor,
@@ -644,6 +647,7 @@
 NeedPIE |= !(TC.getTriple().isOSLinux() &&
  TC.getTriple().getArch() == llvm::Triple::x86_64);
   } else {
+MsanParamRetval = false;
 MsanUseAfterDtor = false;
   }
 
@@ -1093,6 +1097,9 @@
 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
  Twine(MsanTrackOrigins)));
 
+  if (MsanParamRetval)
+CmdArgs.push_back("-fsanitize-memory-param-retval");
+
   if (MsanUseAfterDtor)
 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
 
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -357,8 +357,9 @@
   const CodeGenOptions  = BuilderWrapper.getCGOpts();
   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
-  PM.add(createMemorySanitizerLegacyPassPass(
-  MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));

[PATCH] D116503: [clang] Add arguments for silencing unused argument warnings for some but not all arguments

2022-01-04 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

> Add arguments for silencing unused argument warnings for some but not all 
> arguments

More searchable subject may be `Add 
--start-no-unused-arguments/--end-no-unused-arguments to silence some unused 
argument warnings`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116503/new/

https://reviews.llvm.org/D116503

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


[PATCH] D116503: [clang] Add arguments for silencing unused argument warnings for some but not all arguments

2022-01-04 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

I know some folks who dislike aggressive unused command line option diagnostics 
but also worry about -Qunused-arguments -Wno-unused-command-line-argument 
affecting the entire command line. start/end looks good to me.




Comment at: clang/docs/ClangCommandLineReference.rst:1342
+
+Don't warn for unused arguments between these arguments.
+

The sentence will be scrubbed.

Use `path/to/clang-tblgen -gen-opt-docs -I llvm/include -I 
clang/include/clang/Driver clang/include/clang/Driver/ClangOptionDocs.td > 
clang/docs/ClangCommandLineReference.rst` to regenerate this rst.



Comment at: clang/include/clang/Driver/Options.td:3918
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
+def start_no_unused_arguments : Flag<["--"], "start-no-unused-arguments">, 
Flags<[NoXarchOption, CoreOption]>,
+  HelpText<"Don't emit warnings about unused arguments for the following 
arguments">;

Drop `NoXarchOption`. The option can be used with Darwin -Xarch 
(`test/Driver/Xarch.c`) though it is unnecessary to test it.



Comment at: clang/test/Driver/diagnostics.c:21
+// RUN:   -fsyntax-only -lfoo -Werror %s 2>&1 | FileCheck %s
 
+// With a specific -Wno-..., no diagnostic should be printed.

Looks like no command has an output. In case there is one, make sure `-o 
/dev/null`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116503/new/

https://reviews.llvm.org/D116503

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


[clang] d007e66 - [docs] Re-generate ClangCommandLineReference.rst

2022-01-04 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-01-04T16:52:24-08:00
New Revision: d007e66cb6f58042e043645fda3463de44eb4756

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

LOG: [docs] Re-generate ClangCommandLineReference.rst

Added: 


Modified: 
clang/docs/ClangCommandLineReference.rst

Removed: 




diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 97807009fd911..72d571dd10ee3 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -216,6 +216,8 @@ Trivial automatic variable initialization to zero is only 
here for benchmarks, i
 
 .. option:: -faligned-new=
 
+.. option:: -fautomatic
+
 .. option:: -ffixed-r19
 
 Reserve register r19 (Hexagon only)
@@ -242,6 +244,10 @@ Specify comma-separated list of triples OpenMP offloading 
targets to be supporte
 .. option:: -force\_load 
 .. program:: clang
 
+.. option:: -fplugin-arg--
+
+Pass  to plugin 
+
 .. option:: -framework 
 
 .. option:: -frtlib-add-rpath, -fno-rtlib-add-rpath
@@ -265,7 +271,7 @@ Build this module as a system module. Only used with 
-emit-module
 
 Method to generate ID's for compilation units for single source offloading 
languages CUDA and HIP: 'hash' (ID's generated by hashing file path and command 
line options) \| 'random' (ID's generated as random numbers) \| 'none' 
(disabled). Default is 'hash'. This option will be overridden by option 
'-cuid=\[ID\]' if it is specified.
 
-.. option:: --gcc-toolchain=, -gcc-toolchain 
+.. option:: --gcc-toolchain=
 
 Search for GCC installation in the specified directory on targets which 
commonly use GCC. The directory usually contains 
'lib{,32,64}/gcc{,-cross}/$triple' and 'include'. If specified, sysroot is 
skipped for GCC detection. Note: executables (e.g. ld) used by the compiler are 
not overridden by the selected GCC installation
 
@@ -395,6 +401,10 @@ Do not add include paths for CUDA/HIP and do not include 
the default CUDA/HIP wr
 
 Do not link device library for CUDA/HIP device compilation
 
+.. option:: -nohipwrapperinc
+
+Do not include the default HIP wrapper headers and include paths
+
 .. option:: -nolibc
 
 .. option:: -nomultidefs
@@ -423,6 +433,10 @@ Disable standard #include directories for the C++ standard 
library
 
 Write output to 
 
+.. option:: -objcmt-allowlist-dir-path=, 
-objcmt-white-list-dir-path=, -objcmt-whitelist-dir-path=
+
+Only modify files with a filename contained in the provided directory path
+
 .. option:: -objcmt-atomic-property
 
 Make migration to 'atomic' properties
@@ -483,16 +497,20 @@ Enable migration to use NS\_NONATOMIC\_IOSONLY macro for 
setting property's 'ato
 
 Enable migration to annotate property with NS\_RETURNS\_INNER\_POINTER
 
-.. option:: -objcmpt-allowlist-dir-path=, 
-objcmt-whitelist-dir-path=, -objcmt-white-list-dir-path=
+.. option:: -object
 
-Only modify files with a filename contained in the provided directory path
+.. option:: -object-file-name=, -object-file-name 
 
-.. option:: -object
+Set the output  for debug infos
 
 .. option:: --offload-arch=, --cuda-gpu-arch=, 
--no-offload-arch=
 
 CUDA offloading device architecture (e.g. sm\_35), or HIP offloading target ID 
in the form of a device architecture followed by target ID features delimited 
by a colon. Each target ID feature is a pre-defined string followed by a plus 
or minus sign (e.g. gfx908:xnack+:sramecc-).  May be specified more than once.
 
+.. option:: --offload=,...
+
+Specify comma-separated list of offloading target triples (HIP only)
+
 .. option:: -p, --profile
 
 .. option:: -pagezero\_size
@@ -901,13 +919,17 @@ Level of field padding for AddressSanitizer
 
 Enable linker dead stripping of globals in AddressSanitizer
 
+.. option:: -fsanitize-address-outline-instrumentation, 
-fno-sanitize-address-outline-instrumentation
+
+Always generate function calls for address sanitizer instrumentation
+
 .. option:: -fsanitize-address-poison-custom-array-cookie, 
-fno-sanitize-address-poison-custom-array-cookie
 
 Enable poisoning array cookies when using custom operator new\[\] in 
AddressSanitizer
 
 .. option:: -fsanitize-address-use-after-return=
 
-Select the mode of detecting stack use-after-return in AddressSanitizer
+Select the mode of detecting stack use-after-return in AddressSanitizer: never 
\| runtime (default) \| always
 
 .. option:: -fsanitize-address-use-after-scope, 
-fno-sanitize-address-use-after-scope
 
@@ -1060,10 +1082,6 @@ Pass the comma separated arguments in  to the 
preprocessor
 
 Pass  to the preprocessor
 
-.. option:: -fmacro-prefix-map=
-
-remap file source paths in predefined preprocessor macros
-
 Include path management
 ---
 
@@ -1335,12 +1353,12 @@ Enable the specified warning
 
 Enable 

[PATCH] D116633: Add -fsanitize-address-param-retval to clang.

2022-01-04 Thread Kevin Athey via Phabricator via cfe-commits
kda created this revision.
kda added a reviewer: vitalybuka.
Herald added subscribers: dexonsmith, dang.
kda requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

With the introduction of this flag, it is no longer necessary to enable noundef 
analysis with 4 separate flags.
(-Xclang -enable-noundef-analysis -mllvm -msan-eager-checks=1).
This change only covers the introduction into the compiler.
A later change will include enabling eager checks.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116633

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGen/attr-noundef.cpp
  clang/test/CodeGen/indirect-noundef.cpp


Index: clang/test/CodeGen/indirect-noundef.cpp
===
--- clang/test/CodeGen/indirect-noundef.cpp
+++ clang/test/CodeGen/indirect-noundef.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang -cc1 -x c++ -triple x86_64-unknown-unknown -O0 -emit-llvm 
-enable-noundef-analysis -o - %s | FileCheck %s
+// RUN: %clang -cc1 -x c++ -triple x86_64-unknown-unknown -O0 -emit-llvm 
-fsanitize-memory-param-retval -o - %s | FileCheck %s
 
 union u1 {
   int val;
Index: clang/test/CodeGen/attr-noundef.cpp
===
--- clang/test/CodeGen/attr-noundef.cpp
+++ clang/test/CodeGen/attr-noundef.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang -cc1 -triple x86_64-gnu-linux -x c++ -S -emit-llvm 
-enable-noundef-analysis %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-INTEL
 // RUN: %clang -cc1 -triple aarch64-gnu-linux -x c++ -S -emit-llvm 
-enable-noundef-analysis %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-AARCH
+// RUN: %clang -cc1 -triple x86_64-gnu-linux -x c++ -S -emit-llvm 
-fsanitize-memory-param-retval %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-INTEL
+// RUN: %clang -cc1 -triple aarch64-gnu-linux -x c++ -S -emit-llvm 
-fsanitize-memory-param-retval %s -o - | FileCheck %s --check-prefix=CHECK 
--check-prefix=CHECK-AARCH
 
 // Passing structs by value
 // TODO: No structs may currently be marked noundef
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -2243,7 +2243,9 @@
  getLangOpts().Sanitize.has(SanitizerKind::Return);
 
   // Determine if the return type could be partially undef
-  if (CodeGenOpts.EnableNoundefAttrs && HasStrictReturn) {
+  if ((CodeGenOpts.EnableNoundefAttrs ||
+   CodeGenOpts.SanitizeMemoryParamRetval) &&
+  HasStrictReturn) {
 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
   RetAttrs.addAttribute(llvm::Attribute::NoUndef);
@@ -2378,7 +2380,9 @@
 
 // Decide whether the argument we're handling could be partially undef
 bool ArgNoUndef = DetermineNoUndef(ParamType, getTypes(), DL, AI);
-if (CodeGenOpts.EnableNoundefAttrs && ArgNoUndef)
+if ((CodeGenOpts.EnableNoundefAttrs ||
+ CodeGenOpts.SanitizeMemoryParamRetval) &&
+ArgNoUndef)
   Attrs.addAttribute(llvm::Attribute::NoUndef);
 
 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1667,6 +1667,13 @@
   NormalizedValuesScope<"llvm::AsanDtorKind">,
   NormalizedValues<["None", "Global"]>,
   MarshallingInfoEnum, "Global">;
+defm sanitize_memory_param_retval
+  : BoolOption<"f", "sanitize-memory-param-retval",
+  CodeGenOpts<"SanitizeMemoryParamRetval">,
+  DefaultFalse,
+  PosFlag, NegFlag,
+  BothFlags<[], "eager param-retval uninitialized use detection in 
MemorySanitizer">>,
+Group;
 // Note: This flag was introduced when it was necessary to distinguish between
 //   ABI for correct codegen.  This is no longer needed, but the flag is
 //   not removed since targeting either ABI will behave the same.
Index: clang/include/clang/Basic/CodeGenOptions.def
===
--- clang/include/clang/Basic/CodeGenOptions.def
+++ clang/include/clang/Basic/CodeGenOptions.def
@@ -231,6 +231,8 @@
 ENUM_CODEGENOPT(SanitizeAddressDtor, llvm::AsanDtorKind, 2,
 llvm::AsanDtorKind::Global)  ///< Set how ASan global
  ///< destructors are emitted.
+CODEGENOPT(SanitizeMemoryParamRetval, 1, 0) ///Index: clang/test/CodeGen/indirect-noundef.cpp
===
--- clang/test/CodeGen/indirect-noundef.cpp
+++ clang/test/CodeGen/indirect-noundef.cpp
@@ 

[clang] 37be748 - Revert "[clang][ObjC] Add fix it for missing methods in impl"

2022-01-04 Thread Rumeet Dhindsa via cfe-commits

Author: Rumeet Dhindsa
Date: 2022-01-04T16:43:54-08:00
New Revision: 37be74885946f18dbeb70343ad659924c61d2549

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

LOG: Revert "[clang][ObjC] Add fix it for missing methods in impl"

This reverts commit dd72ae3dcc6895f95e1203b40aabcb069c76a0ab.

Notified the author of the internal failure and author suggested to revert it 
for
now.

Added: 


Modified: 
clang/lib/Sema/SemaDeclObjC.cpp

Removed: 
clang/test/FixIt/fixit-objc-missing-method-impl.m



diff  --git a/clang/lib/Sema/SemaDeclObjC.cpp b/clang/lib/Sema/SemaDeclObjC.cpp
index d4fefc3d18d8a..d6e659e17069c 100644
--- a/clang/lib/Sema/SemaDeclObjC.cpp
+++ b/clang/lib/Sema/SemaDeclObjC.cpp
@@ -2212,8 +2212,9 @@ void 
Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
 }
 
-static void WarnUndefinedMethod(Sema , ObjCImplDecl *Impl,
-ObjCMethodDecl *method, bool ,
+static void WarnUndefinedMethod(Sema , SourceLocation ImpLoc,
+ObjCMethodDecl *method,
+bool ,
 unsigned DiagID,
 NamedDecl *NeededFor = nullptr) {
   // No point warning no definition of method which is 'unavailable'.
@@ -2226,19 +2227,10 @@ static void WarnUndefinedMethod(Sema , ObjCImplDecl 
*Impl,
   // separate warnings.  We will give that approach a try, as that
   // matches what we do with protocols.
   {
-const Sema::SemaDiagnosticBuilder  = S.Diag(Impl->getLocation(), DiagID);
+const Sema::SemaDiagnosticBuilder  = S.Diag(ImpLoc, DiagID);
 B << method;
 if (NeededFor)
   B << NeededFor;
-
-// Add an empty definition at the end of the @implementation.
-std::string FixItStr;
-llvm::raw_string_ostream Out(FixItStr);
-method->print(Out, Impl->getASTContext().getPrintingPolicy());
-Out << " {\n}\n\n";
-
-SourceLocation Loc = Impl->getAtEndRange().getBegin();
-B << FixItHint::CreateInsertion(Loc, FixItStr);
   }
 
   // Issue a note to the original declaration.
@@ -2687,10 +2679,14 @@ static void findProtocolsWithExplicitImpls(const 
ObjCInterfaceDecl *Super,
 
 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
 /// Declared in protocol, and those referenced by it.
-static void CheckProtocolMethodDefs(
-Sema , ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool ,
-const Sema::SelectorSet , const Sema::SelectorSet ,
-ObjCContainerDecl *CDecl, LazyProtocolNameSet ) {
+static void CheckProtocolMethodDefs(Sema ,
+SourceLocation ImpLoc,
+ObjCProtocolDecl *PDecl,
+bool& IncompleteImpl,
+const Sema::SelectorSet ,
+const Sema::SelectorSet ,
+ObjCContainerDecl *CDecl,
+LazyProtocolNameSet ) 
{
   ObjCCategoryDecl *C = dyn_cast(CDecl);
   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
: dyn_cast(CDecl);
@@ -2777,8 +2773,9 @@ static void CheckProtocolMethodDefs(
   if (C || MethodInClass->isPropertyAccessor())
 continue;
 unsigned DIAG = diag::warn_unimplemented_protocol_method;
-if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
-  WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, 
PDecl);
+if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
+  WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
+  PDecl);
 }
   }
 }
@@ -2799,15 +2796,15 @@ static void CheckProtocolMethodDefs(
 continue;
 
   unsigned DIAG = diag::warn_unimplemented_protocol_method;
-  if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
-WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
+  if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
+WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
   }
 }
   }
   // Check on this protocols's referenced protocols, recursively.
   for (auto *PI : PDecl->protocols())
-CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
-ProtocolsExplictImpl);
+CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
+CDecl, ProtocolsExplictImpl);
 }
 
 /// MatchAllMethodDeclarations - Check methods declared in interface
@@ -2830,7 +2827,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet 
,
 if 

[PATCH] D111047: CUDA/HIP: Allow __int128 on the host side

2022-01-04 Thread Artem Belevich via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc99b2c63169d: CUDA/HIP: Allow __int128 on the host side 
(authored by linjamaki, committed by tra).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D111047/new/

https://reviews.llvm.org/D111047

Files:
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaCUDA/allow-int128.cu
  clang/test/SemaCUDA/spirv-int128.cu


Index: clang/test/SemaCUDA/spirv-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/spirv-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple spirv64 -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+
+__device__ __int128 d_unused;
+
+// expected-note@+1 {{'d_glb' defined here}}
+__device__ __int128 d_glb;
+
+__device__ __int128 bar() {
+  // expected-error@+1 {{'d_glb' requires 128 bit size '__int128' type 
support, but target 'spirv64' does not support it}}
+  return d_glb;
+}
Index: clang/test/SemaCUDA/allow-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/allow-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple nvptx \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+// expected-no-diagnostics
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+__device__ __int128 d_unused;
+__device__ __int128 d_glb;
+__device__ __int128 bar() {
+  return d_glb;
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1495,8 +1495,8 @@
   }
   case DeclSpec::TST_int128:
 if (!S.Context.getTargetInfo().hasInt128Type() &&
-!S.getLangOpts().SYCLIsDevice &&
-!(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
+!(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
+  (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)))
   S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
 << "__int128";
 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib/Sema/Sema.cpp
@@ -1941,7 +1941,8 @@
   };
 
   auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
-if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
+if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) 
||
+LangOpts.CUDAIsDevice)
   CheckDeviceType(Ty);
 
 QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();


Index: clang/test/SemaCUDA/spirv-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/spirv-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple spirv64 -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+
+__device__ __int128 d_unused;
+
+// expected-note@+1 {{'d_glb' defined here}}
+__device__ __int128 d_glb;
+
+__device__ __int128 bar() {
+  // expected-error@+1 {{'d_glb' requires 128 bit size '__int128' type support, but target 'spirv64' does not support it}}
+  return d_glb;
+}
Index: clang/test/SemaCUDA/allow-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/allow-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple nvptx \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+// expected-no-diagnostics
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+__device__ __int128 d_unused;
+__device__ __int128 d_glb;
+__device__ __int128 bar() {
+  return d_glb;
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1495,8 +1495,8 @@
   }
   case DeclSpec::TST_int128:
 if (!S.Context.getTargetInfo().hasInt128Type() &&
-!S.getLangOpts().SYCLIsDevice &&
-!(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
+!(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
+  (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)))
   

[clang] c99b2c6 - CUDA/HIP: Allow __int128 on the host side

2022-01-04 Thread Artem Belevich via cfe-commits

Author: Henry Linjamäki
Date: 2022-01-04T16:09:26-08:00
New Revision: c99b2c63169d5aa6499143078790cb3eb87dee45

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

LOG: CUDA/HIP: Allow __int128 on the host side

Consider case where `__int128` type is supported by the host target but
not by a device target (e.g. spirv*). Clang emits an error message for
unsupported type even if the device code does not use it. This patch
fixes this issue by emitting the error message when the device code
attempts to use the unsupported type.

Reviewed By: tra

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

Added: 
clang/test/SemaCUDA/allow-int128.cu
clang/test/SemaCUDA/spirv-int128.cu

Modified: 
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index ba69400fdbbfc..60f37c17c3f18 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1941,7 +1941,8 @@ void Sema::checkTypeSupport(QualType Ty, SourceLocation 
Loc, ValueDecl *D) {
   };
 
   auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
-if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
+if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) 
||
+LangOpts.CUDAIsDevice)
   CheckDeviceType(Ty);
 
 QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 0b3154e6bcb61..57825fe3d79b2 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -1495,8 +1495,8 @@ static QualType ConvertDeclSpecToType(TypeProcessingState 
) {
   }
   case DeclSpec::TST_int128:
 if (!S.Context.getTargetInfo().hasInt128Type() &&
-!S.getLangOpts().SYCLIsDevice &&
-!(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
+!(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
+  (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)))
   S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
 << "__int128";
 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)

diff  --git a/clang/test/SemaCUDA/allow-int128.cu 
b/clang/test/SemaCUDA/allow-int128.cu
new file mode 100644
index 0..eb7b7e7f52862
--- /dev/null
+++ b/clang/test/SemaCUDA/allow-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple nvptx \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+// expected-no-diagnostics
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+__device__ __int128 d_unused;
+__device__ __int128 d_glb;
+__device__ __int128 bar() {
+  return d_glb;
+}

diff  --git a/clang/test/SemaCUDA/spirv-int128.cu 
b/clang/test/SemaCUDA/spirv-int128.cu
new file mode 100644
index 0..b2ff5ae5f6922
--- /dev/null
+++ b/clang/test/SemaCUDA/spirv-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple spirv64 -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+
+__device__ __int128 d_unused;
+
+// expected-note@+1 {{'d_glb' defined here}}
+__device__ __int128 d_glb;
+
+__device__ __int128 bar() {
+  // expected-error@+1 {{'d_glb' requires 128 bit size '__int128' type 
support, but target 'spirv64' does not support it}}
+  return d_glb;
+}



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


[PATCH] D116615: [Clang] Extract availability mapping from VersionMap for watchOS/tvOS

2022-01-04 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Thanks! I think your tests don't actually test the added code, can you check if 
you can parse a mapping like `ios_tvos` in the constructed SDK settings?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116615/new/

https://reviews.llvm.org/D116615

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


[PATCH] D116412: [Clang][Sema] Fix attribute mismatch warning for ObjC class properties

2022-01-04 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I think we would still want to diagnose any mismatches between `class` 
properties that override a `class` property in the superclass. do you think 
that would be useful? You can adjust the lookup to take that into account.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116412/new/

https://reviews.llvm.org/D116412

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


[PATCH] D116618: [clangd] Use the localSourceRange as the default claimed range for typelocs.

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

OK, I hacked up this and your other patch into https://reviews.llvm.org/D116630.

The TypeLoc part seems a little more principled there, because:

- most types are treated the same as any other nodes
- the types that are treated differently have a precise reason, and we can be 
confident the list is exhaustive

Feel free to do what you like with that patch - review it, adopt it, discard it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116618/new/

https://reviews.llvm.org/D116618

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


[PATCH] D116630: [clangd] Handle declarators more consistently in Selection.

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: usaxena95, kadircet, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Because declarators nest inside-out, we logically need to claim tokens for
parent declarators logically before child ones.
This is the ultimate reason we had problems with DeclaratorDecl, ArrayType etc.

However actually changing the order of traversal is hard, especially for nodes
that have both declarator and non-declarator children.
Since there's only a few TypeLocs corresponding to declarators, we just
have them claim the exact tokens rather than rely on nesting.

This fixes handling of complex declarators, like
`int (*Fun(OuterT^ype))(InnerType);`.

This avoids the need for the DeclaratorDecl early-claim hack, which is
removed.
Unfortunately the DeclaratorDecl early-claims were covering up an AST
anomaly around CXXConstructExpr, so we need to fix that up too.

Based on D116623  and D116618 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116630

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -204,9 +204,9 @@
   {
   R"cpp(
 struct S { S(const char*); };
-S [[s ^= "foo"]];
+[[S s ^= "foo"]];
   )cpp",
-  "CXXConstructExpr",
+  "VarDecl",
   },
   {
   R"cpp(
@@ -231,7 +231,7 @@
   R"cpp(
 [[void (^*S)(int)]] = nullptr;
   )cpp",
-  "FunctionProtoTypeLoc",
+  "PointerTypeLoc",
   },
   {
   R"cpp(
@@ -243,7 +243,7 @@
   R"cpp(
 [[void ^(*S)(int)]] = nullptr;
   )cpp",
-  "FunctionProtoTypeLoc",
+  "ParenTypeLoc",
   },
   {
   R"cpp(
@@ -326,6 +326,8 @@
   {"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"},
   {"void func(int x) { int v_array[^[[x]]][10]; }", "DeclRefExpr"},
 
+  {"int (*getFunc([[do^uble]]))(int);", "BuiltinTypeLoc"},
+
   // FIXME: the AST has no location info for qualifiers.
   {"const [[a^uto]] x = 42;", "AutoTypeLoc"},
   {"[[co^nst auto x = 42]];", "VarDecl"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -639,11 +639,10 @@
   // Nodes *usually* nest nicely: a child's getSourceRange() lies within the
   // parent's, and a node (transitively) owns all tokens in its range.
   //
-  // Exception 1: child range claims tokens that should be owned by the parent.
-  //  e.g. in `void foo(int);`, the FunctionTypeLoc should own
-  //  `void (int)` but the parent FunctionDecl should own `foo`.
-  // To handle this case, certain nodes claim small token ranges *before*
-  // their children are traversed. (see earlySourceRange).
+  // Exception 1: when declarators nest, *inner* declarator is the *outer* type.
+  //  e.g. void foo[5](int) is an array of functions.
+  // To handle this case, declarators are careful to only claim the tokens they
+  // own, rather than claim a range and rely on claim ordering.
   //
   // Exception 2: siblings both claim the same node.
   //  e.g. `int x, y;` produces two sibling VarDecls.
@@ -690,16 +689,13 @@
   }
 
   // Pushes a node onto the ancestor stack. Pairs with pop().
-  // Performs early hit detection for some nodes (on the earlySourceRange).
   void push(DynTypedNode Node) {
-SourceRange Early = earlySourceRange(Node);
 dlog("{1}push: {0}", printNodeToString(Node, PrintPolicy), indent());
 Nodes.emplace_back();
 Nodes.back().ASTNode = std::move(Node);
 Nodes.back().Parent = Stack.top();
 Nodes.back().Selected = NoTokens;
 Stack.push(());
-claimRange(Early, Nodes.back().Selected);
   }
 
   // Pops a node off the ancestor stack, and finalizes it. Pairs with push().
@@ -721,52 +717,46 @@
 Stack.pop();
   }
 
-  // Returns the range of tokens that this node will claim directly, and
-  // is not available to the node's children.
-  // Usually empty, but sometimes children cover tokens but shouldn't own them.
-  SourceRange earlySourceRange(const DynTypedNode ) {
-if (const Decl *D = N.get()) {
-  // We want constructor name to be claimed by TypeLoc not the constructor
-  // itself. Similar for deduction guides, we rather want to select the
-  // underlying TypeLoc.
-  // FIXME: 

[PATCH] D116020: [clang][#52782] Bail on incomplete parameter type in stdcall name mangling

2022-01-04 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

> clang actually refuses taking the address of a stdcall function if it has an 
> incomplete type parameter:

I was going to say, I thought I remembered fixing this problem, and I guess 
that's how I fixed it: with errors.

MSVC doesn't add stdcall mangling suffixes to non-extern-C symbols, so we don't 
have this kind of issue in MSVC mode.

I think the change is reasonable as is.




Comment at: clang/test/CodeGen/pr52782-stdcall-func-decl.cpp:10
+class nsICanvasRenderingContextInternal {
+  NS_IMETHOD_(nsresult) InitializeWithDrawTarget(NotNull);
+} nsTBaseHashSet;

Please check for the declaration with the mangled name. In this case, we expect 
to see a `@0` suffix.

Also, the `NS_IMETHOD_` macro isn't necessary for the reduction, it can just be 
`void __stdcall InitializeWithDrawTarget(NotNull)`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116020/new/

https://reviews.llvm.org/D116020

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


[PATCH] D116618: [clangd] Use the localSourceRange as the default claimed range for typelocs.

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D116618#3220744 , @sammccall wrote:

> - claim their full range, but in the opposite order (parents before children)

To refine this a little more, for declarator type nodes:

- first, we should recurse into non-declarator children (such as array bounds 
and function parameters) and let them claim tokens
- then we claim the range
- then we recurse into declarator children

That said I think it's probably not worth it, there are only a few declarator 
nodes and the approach of not claiming the gap seems simpler.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116618/new/

https://reviews.llvm.org/D116618

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


[PATCH] D116627: [Clang] Initial support for linking offloading code in tool

2022-01-04 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: pengfei, tpr.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

This patch adds the initial support for linking NVPTX offloading code
using the clang-linker-wrapper tool. This uses the extracted device
files and runs `nvlink` on them. Currently this is then passed to the
existing toolchain for creating linkable OpenMP offloading programs
using `clang-offload-wrapper` and compiling it manually using `llc`.
More work is required to support LTO, Bitcode linking, AMDGPU, and x86
offloading.

Depends on D116545 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116627

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -28,6 +28,7 @@
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/FileOutputBuffer.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Host.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
@@ -59,22 +60,26 @@
 
 // Do not parse linker options.
 static cl::list
-LinkerArgs(cl::Sink, cl::desc("..."));
+HostLinkerArgs(cl::Sink, cl::desc("..."));
 
 /// Path of the current binary.
 static std::string LinkerExecutable;
 
+static SmallVector TempFiles;
 /// Magic section string that marks the existence of offloading data. The
 /// section string will be formatted as `.llvm.offloading..`.
-#define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
+#define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
 
+/// Information for a device offloading file extracted from the host.
 struct DeviceFile {
   DeviceFile(StringRef TheTriple, StringRef Arch, StringRef Filename)
   : TheTriple(TheTriple), Arch(Arch), Filename(Filename) {}
 
-  const Triple TheTriple;
+  const std::string TheTriple;
   const std::string Arch;
   const std::string Filename;
+
+  std::string str() const { return TheTriple + "-" + Arch; }
 };
 
 namespace {
@@ -83,6 +88,16 @@
 extractFromBuffer(std::unique_ptr Buffer,
   SmallVectorImpl );
 
+static StringRef getDeviceFileExtension(StringRef DeviceTriple,
+bool IsBitcode = false) {
+  Triple TheTriple(DeviceTriple);
+  if (TheTriple.isAMDGPU() || IsBitcode)
+return "bc";
+  if (TheTriple.isNVPTX())
+return "cubin";
+  return "o";
+}
+
 Error runLinker(std::string , SmallVectorImpl ) {
   std::vector LinkerArgs;
   LinkerArgs.push_back(LinkerPath);
@@ -154,9 +169,12 @@
 
 if (Expected Contents = Sec.getContents()) {
   SmallString<128> TempFile;
+  StringRef DeviceExtension = getDeviceFileExtension(
+  DeviceTriple, identify_magic(*Contents) == file_magic::bitcode);
   if (std::error_code EC = sys::fs::createTemporaryFile(
-  Prefix + "-device-" + DeviceTriple, Extension, TempFile))
+  Prefix + "-device-" + DeviceTriple, DeviceExtension, TempFile))
 return createFileError(TempFile, EC);
+  TempFiles.push_back(static_cast(TempFile));
 
   Expected> OutputOrErr =
   FileOutputBuffer::create(TempFile, Sec.getSize());
@@ -189,6 +207,7 @@
   if (std::error_code EC =
   sys::fs::createTemporaryFile(Prefix + "-host", Extension, TempFile))
 return createFileError(TempFile, EC);
+  TempFiles.push_back(static_cast(TempFile));
 
   SmallVector StripArgs;
   StripArgs.push_back(*StripPath);
@@ -245,9 +264,12 @@
 
 StringRef Contents = CDS->getAsString();
 SmallString<128> TempFile;
+StringRef DeviceExtension = getDeviceFileExtension(
+DeviceTriple, identify_magic(Contents) == file_magic::bitcode);
 if (std::error_code EC = sys::fs::createTemporaryFile(
-Prefix + "-device-" + DeviceTriple, Extension, TempFile))
+Prefix + "-device-" + DeviceTriple, DeviceExtension, TempFile))
   return createFileError(TempFile, EC);
+TempFiles.push_back(static_cast(TempFile));
 
 Expected> OutputOrErr =
 FileOutputBuffer::create(TempFile, Contents.size());
@@ -279,6 +301,8 @@
   if (std::error_code EC =
   sys::fs::createTemporaryFile(Prefix + "-host", Extension, TempFile))
 return createFileError(TempFile, EC);
+  TempFiles.push_back(static_cast(TempFile));
+
   std::error_code EC;
   raw_fd_ostream HostOutput(TempFile, EC, sys::fs::OF_None);
   if (EC)
@@ -349,6 +373,7 @@
   if (std::error_code EC =
   sys::fs::createTemporaryFile(Prefix + "-host", Extension, TempFile))
 return createFileError(TempFile, EC);
+  TempFiles.push_back(static_cast(TempFile));
 
   std::unique_ptr Buffer 

[PATCH] D116518: [ast-matchers] Add hasSubstatementSequence matcher

2022-01-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:5435-5442
+/// Matches two consecutive statements within a compound statement.
+///
+/// Given
+/// \code
+///   { if (x > 0) return true; return false; }
+/// \endcode
+/// compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt()))

LegalizeAdulthood wrote:
> aaron.ballman wrote:
> > How do we extend this to support testing arbitrary sequences of statements? 
> > (If this supports two statements, someone will find a need for three, etc).
> Yeah, I was wondering that too.  I didn't see (but didn't look extensively) 
> any support for variadic matchers taking a parameter pack.
> 
> I stopped at 2 because this suits my immediate needs with 
> `readability-simplify-boolean-expr` where I have to manually loop over 
> `CompoundStmt` matches in order to verify that the `if (x) return true; 
> return false;` constructs consist of two adjacent statements.
I don't think we have any variadic matchers yet to model on, but I think if 
this is only needed for one check, we can add it in the current form as a local 
matcher for that check. Whenever we figure out how to give the better interface 
through the static and dynamic matchers, then we can figure out how to lift 
this to the general matcher interface.

WDYT?



Comment at: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp:2636
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
+  const char *Text = R"code(

LegalizeAdulthood wrote:
> aaron.ballman wrote:
> > Some more complex-ish tests: can we match within function try or catch 
> > blocks and GNU statement expressions?
> Adding something for GNU statement expressions is a good idea.
> 
> I'm open for other suggestions that might improve coverage.
> 
> At the moment, I believe I have 100% coverage of the new matcher, with the 
> exception of GNU statement expressions (honestly, I just copy/pasted that 
> from another matcher on `CompoundStmt`, I wasn't even aware of this GNU 
> extension).
I just double-checked and we do model function try blocks as a body, and we 
model function body as being a `CompoundStmt`, so I think we're good enough 
there. I was more worried we did something odd with those (they're pretty easy 
to forget about given how uncommon they are).


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116518/new/

https://reviews.llvm.org/D116518

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


[PATCH] D56343: [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

2022-01-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman resigned from this revision.
aaron.ballman added a comment.

Resigning only because I don't think I have strong enough Python skills to give 
a quality review. I didn't spot anything that concerned me specific to this 
patch though.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56343/new/

https://reviews.llvm.org/D56343

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


[PATCH] D116599: Simplify AttrBuilder storage for target dependent attributes

2022-01-04 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Nice!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116599/new/

https://reviews.llvm.org/D116599

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


[PATCH] D116547: Revert "[amdgpu] Enable selection of `s_cselect_b64`."

2022-01-04 Thread David Salinas via Phabricator via cfe-commits
david-salinas abandoned this revision.
david-salinas added a comment.

Abandoning.  Will use D115960 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116547/new/

https://reviews.llvm.org/D116547

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


[PATCH] D116577: [clang-tidy] Added "boost-use-range-based-for-loop" check

2022-01-04 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added a comment.

I opened a similar issue for converting Qt's foreach to a range for loop 
.

However this check lands, it should be a simple generalization to have it 
process Qt foreach loops as well, so perhaps a check name like 
`modernize-foreach-to-range-for` would be better?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116577/new/

https://reviews.llvm.org/D116577

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


[PATCH] D115049: Fall back on Android triple w/o API level for runtimes search

2022-01-04 Thread Collin Baker via Phabricator via cfe-commits
collinbaker updated this revision to Diff 397394.
collinbaker added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115049/new/

https://reviews.llvm.org/D115049

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/VEToolchain.cpp
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/aarch64-unknown-linux-android/.keep
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/aarch64-unknown-linux-android/libclang_rt.builtins.a
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/aarch64-unknown-linux-android21/.keep
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/aarch64-unknown-linux-android21/libclang_rt.builtins.a
  clang/test/Driver/linux-per-target-runtime-dir.c

Index: clang/test/Driver/linux-per-target-runtime-dir.c
===
--- clang/test/Driver/linux-per-target-runtime-dir.c
+++ clang/test/Driver/linux-per-target-runtime-dir.c
@@ -25,3 +25,21 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-FILE-NAME-X8664 %s
 // CHECK-FILE-NAME-X8664: lib{{/|\\}}x86_64-unknown-linux-gnu{{/|\\}}libclang_rt.builtins.a
+
+// RUN: %clang -rtlib=compiler-rt -print-file-name=libclang_rt.builtins.a 2>&1 \
+// RUN: --target=aarch64-unknown-linux-android21 \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN:   | FileCheck --check-prefix=CHECK-FILE-NAME-ANDROID21 %s
+// CHECK-FILE-NAME-ANDROID21: lib{{/|\\}}aarch64-unknown-linux-android21{{/|\\}}libclang_rt.builtins.a
+
+// RUN: %clang -rtlib=compiler-rt -print-file-name=libclang_rt.builtins.a 2>&1 \
+// RUN: --target=aarch64-unknown-linux-android23 \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN:   | FileCheck --check-prefix=CHECK-FILE-NAME-ANDROID23 %s
+// CHECK-FILE-NAME-ANDROID23: lib{{/|\\}}aarch64-unknown-linux-android{{/|\\}}libclang_rt.builtins.a
+
+// RUN: %clang -rtlib=compiler-rt -print-file-name=libclang_rt.builtins.a 2>&1 \
+// RUN: --target=aarch64-unknown-linux-android \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN:   | FileCheck --check-prefix=CHECK-FILE-NAME-ANDROID %s
+// CHECK-FILE-NAME-ANDROID: lib{{/|\\}}aarch64-unknown-linux-android{{/|\\}}libclang_rt.builtins.a
Index: clang/lib/Driver/ToolChains/VEToolchain.cpp
===
--- clang/lib/Driver/ToolChains/VEToolchain.cpp
+++ clang/lib/Driver/ToolChains/VEToolchain.cpp
@@ -48,7 +48,8 @@
   //   ${BINPATH}/../lib/ve-unknown-linux-gnu, (== getStdlibPath)
   //   ${RESOURCEDIR}/lib/linux/ve, (== getArchSpecificLibPath)
   //   ${SYSROOT}/opt/nec/ve/lib,
-  getFilePaths().push_back(getStdlibPath());
+  for (auto  : getStdlibPaths())
+getFilePaths().push_back(std::move(Path));
   getFilePaths().push_back(getArchSpecificLibPath());
   getFilePaths().push_back(computeSysRoot() + "/opt/nec/ve/lib");
 }
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -191,9 +191,11 @@
 
   auto FilePaths = [&](const Multilib ) -> std::vector {
 std::vector FP;
-SmallString<128> P(getStdlibPath());
-llvm::sys::path::append(P, M.gccSuffix());
-FP.push_back(std::string(P.str()));
+for (const std::string  : getStdlibPaths()) {
+  SmallString<128> P(Path);
+  llvm::sys::path::append(P, M.gccSuffix());
+  FP.push_back(std::string(P.str()));
+}
 return FP;
   };
 
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -75,17 +75,16 @@
  const ArgList )
 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
   CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
-  std::string RuntimePath = getRuntimePath();
-  if (getVFS().exists(RuntimePath))
-getLibraryPaths().push_back(RuntimePath);
-
-  std::string StdlibPath = getStdlibPath();
-  if (getVFS().exists(StdlibPath))
-getFilePaths().push_back(StdlibPath);
+  auto addIfExists = [this](path_list , const std::string ) {
+if (getVFS().exists(Path))
+  List.push_back(Path);
+  };
 
-  std::string CandidateLibPath = getArchSpecificLibPath();
-  if (getVFS().exists(CandidateLibPath))
-getFilePaths().push_back(CandidateLibPath);
+  for (const auto  : getRuntimePaths())
+addIfExists(getLibraryPaths(), Path);
+  for (const auto  : getStdlibPaths())
+addIfExists(getFilePaths(), Path);
+  addIfExists(getFilePaths(), 

[PATCH] D56343: [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

2022-01-04 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added a comment.

If there are no new comments by the end of the week, I'm going to accept this 
revision and commit it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56343/new/

https://reviews.llvm.org/D56343

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


[PATCH] D116618: [clangd] Use the localSourceRange as the default claimed range for typelocs.

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This is neat, and I we're getting closer to the principled answer.
After staring at this patch for a while, and seeing what arrays, functions, and 
now parens have in common, I finally understand. The problem is *declarators*.

Declarators are inside-out: `((*x)[](double)` says that x is a pointer to an 
array to a function from double.
Whereas types that are decl-specifiers nest the other way: that would be 
written `pointer>>`, just like decls or stmts nest.

So for decl-specifier TypeLocs the usual getSourceRange should apply. (Modulo 
hacks like decltype() where the range is just wrong).

For typelocs that are part of the declarator, there are two approaches that 
seem principled:

- claim their full range, but in the opposite order (parents before children)
- claim only the specific tokens used, in which case order doesn't matter

These are basically equivalent. declarator types have a "before" and an "after" 
chunk (see TypePrinter). They can claim these by claiming their full range, but 
the "gap" was claimed earlier, or they can claim the two ends separately.
If we can make it work, claiming the full range is probably better because it 
will handle unexpected stray tokens in a more natural way. 
Either way we should be able to unify this with the DeclaratorDecl hack.

I'll have a play with this idea...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116618/new/

https://reviews.llvm.org/D116618

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


[PATCH] D116623: [clangd][WIP] Remove the earlySourceRange hack in SelectionTree.

2022-01-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This is an attempt to remove the existing earlySourceRange hack in favor
of the claimed range concept.

Not sure it is worth doing it, existing tests are passed except there is
one small regression about ConstructExpr.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116623

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -204,9 +204,9 @@
   {
   R"cpp(
 struct S { S(const char*); };
-S [[s ^= "foo"]];
+[[S s ^= "foo"]];
   )cpp",
-  "CXXConstructExpr",
+  "VarDecl",
   },
   {
   R"cpp(
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -690,16 +690,13 @@
   }
 
   // Pushes a node onto the ancestor stack. Pairs with pop().
-  // Performs early hit detection for some nodes (on the earlySourceRange).
   void push(DynTypedNode Node) {
-SourceRange Early = earlySourceRange(Node);
 dlog("{1}push: {0}", printNodeToString(Node, PrintPolicy), indent());
 Nodes.emplace_back();
 Nodes.back().ASTNode = std::move(Node);
 Nodes.back().Parent = Stack.top();
 Nodes.back().Selected = NoTokens;
 Stack.push(());
-claimRange(Early, Nodes.back().Selected);
   }
 
   // Pops a node off the ancestor stack, and finalizes it. Pairs with push().
@@ -721,34 +718,6 @@
 Stack.pop();
   }
 
-  // Returns the range of tokens that this node will claim directly, and
-  // is not available to the node's children.
-  // Usually empty, but sometimes children cover tokens but shouldn't own them.
-  SourceRange earlySourceRange(const DynTypedNode ) {
-if (const Decl *D = N.get()) {
-  // We want constructor name to be claimed by TypeLoc not the constructor
-  // itself. Similar for deduction guides, we rather want to select the
-  // underlying TypeLoc.
-  // FIXME: Unfortunately this doesn't work, even though 
RecursiveASTVisitor
-  // traverses the underlying TypeLoc inside DeclarationName, it is null 
for
-  // constructors.
-  if (isa(D) || isa(D))
-return SourceRange();
-  // This will capture Field, Function, MSProperty, NonTypeTemplateParm and
-  // VarDecls. We want the name in the declarator to be claimed by the decl
-  // and not by any children. For example:
-  // void [[foo]]();
-  // int (*[[s]])();
-  // struct X { int [[hash]] [32]; [[operator]] int();}
-  if (const auto *DD = llvm::dyn_cast(D))
-return DD->getLocation();
-} else if (const auto *CCI = N.get()) {
-  // : [[b_]](42)
-  return CCI->getMemberLocation();
-}
-return SourceRange();
-  }
-
   // Claim tokens for N, after processing its children.
   // By default this claims all unclaimed tokens in getSourceRange().
   // We override this if we want to claim fewer tokens (e.g. there are gaps).
@@ -776,6 +745,15 @@
 return;
   }
 
+  // getLocalSourceRange is the parens range for most 
FunctionProtoTypeLocs,
+  // but not true for a trailing-return-type function.
+  //
+  // auto foo() -> int {}
+  // XX   <- range we want to claim
+  // XXX  <- getLocalSourceRange
+  if (auto A = TL->getAs())
+return claimRange(A.getParensRange(), Result);
+
   // We use LocalSourceRange as a default claimed range for TypeLocs -- it
   // is better than getSourceRange (which returns a range covering itself
   // and its children), because we want to claim fewer tokens (multiple
@@ -789,6 +767,11 @@
   // Inner ATL must not claim its whole SourceRange, or it clobbers Outer.
   return claimRange(TL->getLocalSourceRange(), Result);
 }
+if (const auto *CCE = N.get())
+  return claimRange(CCE->getParenOrBraceRange(), Result);
+// Don't claim any tokens for ExprWithCleanups.
+if (const auto *CCE = N.get())
+  return;
 claimRange(getSourceRange(N), Result);
   }
 


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -204,9 +204,9 @@
   {
   R"cpp(
 struct S { S(const char*); };
-S [[s ^= "foo"]];
+[[S s 

[PATCH] D113146: [Sema] Fix the assertion in Sema::ActOnDependentMemberExpr

2022-01-04 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

Richard seems very busy. I just committed this based on Aaron's LGTM. Richard 
could still review this at any time.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D113146/new/

https://reviews.llvm.org/D113146

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


[PATCH] D113146: [Sema] Fix the assertion in Sema::ActOnDependentMemberExpr

2022-01-04 Thread Yuanfang Chen via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe902ffe6d756: [Sema] Fix the assertion in 
Sema::ActOnDependentMemberExpr (authored by ychen).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D113146/new/

https://reviews.llvm.org/D113146

Files:
  clang/lib/Sema/SemaExprMember.cpp
  clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp


Index: clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
===
--- clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
+++ clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
@@ -394,6 +394,18 @@
 template static int n; // expected-note {{here}}
   }
   int  = B::template n; // expected-error {{use of variable template 'n' 
requires template arguments}}
+
+  struct C {
+template  static T G;
+  };
+  template T C::G = T(6);
+
+  template  T F() {
+C c;
+return c.G;
+  }
+
+  int cf() { return F(); }
 }
 
 #ifndef PRECXX11
Index: clang/lib/Sema/SemaExprMember.cpp
===
--- clang/lib/Sema/SemaExprMember.cpp
+++ clang/lib/Sema/SemaExprMember.cpp
@@ -504,9 +504,12 @@
 }
   }
 
-  assert(BaseType->isDependentType() ||
- NameInfo.getName().isDependentName() ||
- isDependentScopeSpecifier(SS));
+  assert(BaseType->isDependentType() || NameInfo.getName().isDependentName() ||
+ isDependentScopeSpecifier(SS) ||
+ (TemplateArgs && llvm::any_of(TemplateArgs->arguments(),
+   [](const TemplateArgumentLoc ) {
+ return 
Arg.getArgument().isDependent();
+   })));
 
   // Get the type being accessed in BaseType.  If this is an arrow, the 
BaseExpr
   // must have pointer type, and the accessed type is the pointee.


Index: clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
===
--- clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
+++ clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
@@ -394,6 +394,18 @@
 template static int n; // expected-note {{here}}
   }
   int  = B::template n; // expected-error {{use of variable template 'n' requires template arguments}}
+
+  struct C {
+template  static T G;
+  };
+  template T C::G = T(6);
+
+  template  T F() {
+C c;
+return c.G;
+  }
+
+  int cf() { return F(); }
 }
 
 #ifndef PRECXX11
Index: clang/lib/Sema/SemaExprMember.cpp
===
--- clang/lib/Sema/SemaExprMember.cpp
+++ clang/lib/Sema/SemaExprMember.cpp
@@ -504,9 +504,12 @@
 }
   }
 
-  assert(BaseType->isDependentType() ||
- NameInfo.getName().isDependentName() ||
- isDependentScopeSpecifier(SS));
+  assert(BaseType->isDependentType() || NameInfo.getName().isDependentName() ||
+ isDependentScopeSpecifier(SS) ||
+ (TemplateArgs && llvm::any_of(TemplateArgs->arguments(),
+   [](const TemplateArgumentLoc ) {
+ return Arg.getArgument().isDependent();
+   })));
 
   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
   // must have pointer type, and the accessed type is the pointee.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e902ffe - [Sema] Fix the assertion in Sema::ActOnDependentMemberExpr

2022-01-04 Thread Yuanfang Chen via cfe-commits

Author: Yuanfang Chen
Date: 2022-01-04T13:08:12-08:00
New Revision: e902ffe6d7560f708b76edaa53d75edcb5d49a3f

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

LOG: [Sema] Fix the assertion in Sema::ActOnDependentMemberExpr

617007240cbfb97c introduced the use of ActOnDependentMemberExpr with
variable template specialization. The assertion inside
ActOnDependentMemberExpr should be adjusted accordingly.

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

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/lib/Sema/SemaExprMember.cpp
clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExprMember.cpp 
b/clang/lib/Sema/SemaExprMember.cpp
index 83006f9d804ab..f67ef030feb70 100644
--- a/clang/lib/Sema/SemaExprMember.cpp
+++ b/clang/lib/Sema/SemaExprMember.cpp
@@ -504,9 +504,12 @@ Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType 
BaseType,
 }
   }
 
-  assert(BaseType->isDependentType() ||
- NameInfo.getName().isDependentName() ||
- isDependentScopeSpecifier(SS));
+  assert(BaseType->isDependentType() || NameInfo.getName().isDependentName() ||
+ isDependentScopeSpecifier(SS) ||
+ (TemplateArgs && llvm::any_of(TemplateArgs->arguments(),
+   [](const TemplateArgumentLoc ) {
+ return 
Arg.getArgument().isDependent();
+   })));
 
   // Get the type being accessed in BaseType.  If this is an arrow, the 
BaseExpr
   // must have pointer type, and the accessed type is the pointee.

diff  --git a/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp 
b/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
index 1a24c66805690..af121a8b75d51 100644
--- a/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
+++ b/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
@@ -394,6 +394,18 @@ namespace dependent_static_var_template {
 template static int n; // expected-note {{here}}
   }
   int  = B::template n; // expected-error {{use of variable template 'n' 
requires template arguments}}
+
+  struct C {
+template  static T G;
+  };
+  template T C::G = T(6);
+
+  template  T F() {
+C c;
+return c.G;
+  }
+
+  int cf() { return F(); }
 }
 
 #ifndef PRECXX11



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


[PATCH] D76038: PR45000: Let Sema::SubstParmVarDecl handle default args of lambdas in initializers

2022-01-04 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

In D76038#3219500 , @zahiraam wrote:

> This change is generating this crash discussed here: 
> https://bugs.llvm.org/show_bug.cgi?id=49834

Now migrated to https://github.com/llvm/llvm-project/issues/49178.

> @aaronpuchert do you have any fix for it?

No, everything I know is in that bug report. I was hoping @rsmith would reply 
with an idea, but it's quite complicated.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76038/new/

https://reviews.llvm.org/D76038

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


[PATCH] D116417: [clang][ObjC] Add fix it for missing methods in impl

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
dgoldman marked an inline comment as done.
Closed by commit rGdd72ae3dcc68: [clang][ObjC] Add fix it for missing methods 
in impl (authored by dgoldman).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116417/new/

https://reviews.llvm.org/D116417

Files:
  clang/lib/Sema/SemaDeclObjC.cpp
  clang/test/FixIt/fixit-objc-missing-method-impl.m

Index: clang/test/FixIt/fixit-objc-missing-method-impl.m
===
--- /dev/null
+++ clang/test/FixIt/fixit-objc-missing-method-impl.m
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: cp %s %t
+// RUN: not %clang_cc1 -pedantic -Werror -fixit -x objective-c %t
+// RUN: %clang_cc1 -pedantic -Werror -x objective-c %t
+
+__attribute__((objc_root_class))
+@interface NSObject
+@end
+
+@interface Foo : NSObject
+- (void)fooey;  // expected-note{{method 'fooey' declared here}}
+@end
+
+@implementation Foo  // expected-warning{{method definition for 'fooey' not found}}
+@end
Index: clang/lib/Sema/SemaDeclObjC.cpp
===
--- clang/lib/Sema/SemaDeclObjC.cpp
+++ clang/lib/Sema/SemaDeclObjC.cpp
@@ -2212,9 +2212,8 @@
 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
 }
 
-static void WarnUndefinedMethod(Sema , SourceLocation ImpLoc,
-ObjCMethodDecl *method,
-bool ,
+static void WarnUndefinedMethod(Sema , ObjCImplDecl *Impl,
+ObjCMethodDecl *method, bool ,
 unsigned DiagID,
 NamedDecl *NeededFor = nullptr) {
   // No point warning no definition of method which is 'unavailable'.
@@ -2227,10 +2226,19 @@
   // separate warnings.  We will give that approach a try, as that
   // matches what we do with protocols.
   {
-const Sema::SemaDiagnosticBuilder  = S.Diag(ImpLoc, DiagID);
+const Sema::SemaDiagnosticBuilder  = S.Diag(Impl->getLocation(), DiagID);
 B << method;
 if (NeededFor)
   B << NeededFor;
+
+// Add an empty definition at the end of the @implementation.
+std::string FixItStr;
+llvm::raw_string_ostream Out(FixItStr);
+method->print(Out, Impl->getASTContext().getPrintingPolicy());
+Out << " {\n}\n\n";
+
+SourceLocation Loc = Impl->getAtEndRange().getBegin();
+B << FixItHint::CreateInsertion(Loc, FixItStr);
   }
 
   // Issue a note to the original declaration.
@@ -2679,14 +2687,10 @@
 
 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
 /// Declared in protocol, and those referenced by it.
-static void CheckProtocolMethodDefs(Sema ,
-SourceLocation ImpLoc,
-ObjCProtocolDecl *PDecl,
-bool& IncompleteImpl,
-const Sema::SelectorSet ,
-const Sema::SelectorSet ,
-ObjCContainerDecl *CDecl,
-LazyProtocolNameSet ) {
+static void CheckProtocolMethodDefs(
+Sema , ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool ,
+const Sema::SelectorSet , const Sema::SelectorSet ,
+ObjCContainerDecl *CDecl, LazyProtocolNameSet ) {
   ObjCCategoryDecl *C = dyn_cast(CDecl);
   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
: dyn_cast(CDecl);
@@ -2773,9 +2777,8 @@
   if (C || MethodInClass->isPropertyAccessor())
 continue;
 unsigned DIAG = diag::warn_unimplemented_protocol_method;
-if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
-  WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
-  PDecl);
+if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
+  WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
 }
   }
 }
@@ -2796,15 +2799,15 @@
 continue;
 
   unsigned DIAG = diag::warn_unimplemented_protocol_method;
-  if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
-WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
+  if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
+WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
   }
 }
   }
   // Check on this protocols's referenced protocols, recursively.
   for (auto *PI : PDecl->protocols())
-CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
-CDecl, ProtocolsExplictImpl);
+CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
+ProtocolsExplictImpl);
 }
 
 /// MatchAllMethodDeclarations - 

[clang] dd72ae3 - [clang][ObjC] Add fix it for missing methods in impl

2022-01-04 Thread David Goldman via cfe-commits

Author: David Goldman
Date: 2022-01-04T15:57:58-05:00
New Revision: dd72ae3dcc6895f95e1203b40aabcb069c76a0ab

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

LOG: [clang][ObjC] Add fix it for missing methods in impl

We suggest inserting the method with an empty body at the end
of the implementation decl.

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

Added: 
clang/test/FixIt/fixit-objc-missing-method-impl.m

Modified: 
clang/lib/Sema/SemaDeclObjC.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclObjC.cpp b/clang/lib/Sema/SemaDeclObjC.cpp
index d6e659e17069c..d4fefc3d18d8a 100644
--- a/clang/lib/Sema/SemaDeclObjC.cpp
+++ b/clang/lib/Sema/SemaDeclObjC.cpp
@@ -2212,9 +2212,8 @@ void 
Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
 }
 
-static void WarnUndefinedMethod(Sema , SourceLocation ImpLoc,
-ObjCMethodDecl *method,
-bool ,
+static void WarnUndefinedMethod(Sema , ObjCImplDecl *Impl,
+ObjCMethodDecl *method, bool ,
 unsigned DiagID,
 NamedDecl *NeededFor = nullptr) {
   // No point warning no definition of method which is 'unavailable'.
@@ -2227,10 +2226,19 @@ static void WarnUndefinedMethod(Sema , SourceLocation 
ImpLoc,
   // separate warnings.  We will give that approach a try, as that
   // matches what we do with protocols.
   {
-const Sema::SemaDiagnosticBuilder  = S.Diag(ImpLoc, DiagID);
+const Sema::SemaDiagnosticBuilder  = S.Diag(Impl->getLocation(), DiagID);
 B << method;
 if (NeededFor)
   B << NeededFor;
+
+// Add an empty definition at the end of the @implementation.
+std::string FixItStr;
+llvm::raw_string_ostream Out(FixItStr);
+method->print(Out, Impl->getASTContext().getPrintingPolicy());
+Out << " {\n}\n\n";
+
+SourceLocation Loc = Impl->getAtEndRange().getBegin();
+B << FixItHint::CreateInsertion(Loc, FixItStr);
   }
 
   // Issue a note to the original declaration.
@@ -2679,14 +2687,10 @@ static void findProtocolsWithExplicitImpls(const 
ObjCInterfaceDecl *Super,
 
 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
 /// Declared in protocol, and those referenced by it.
-static void CheckProtocolMethodDefs(Sema ,
-SourceLocation ImpLoc,
-ObjCProtocolDecl *PDecl,
-bool& IncompleteImpl,
-const Sema::SelectorSet ,
-const Sema::SelectorSet ,
-ObjCContainerDecl *CDecl,
-LazyProtocolNameSet ) 
{
+static void CheckProtocolMethodDefs(
+Sema , ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool ,
+const Sema::SelectorSet , const Sema::SelectorSet ,
+ObjCContainerDecl *CDecl, LazyProtocolNameSet ) {
   ObjCCategoryDecl *C = dyn_cast(CDecl);
   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
: dyn_cast(CDecl);
@@ -2773,9 +2777,8 @@ static void CheckProtocolMethodDefs(Sema ,
   if (C || MethodInClass->isPropertyAccessor())
 continue;
 unsigned DIAG = diag::warn_unimplemented_protocol_method;
-if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
-  WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
-  PDecl);
+if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
+  WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, 
PDecl);
 }
   }
 }
@@ -2796,15 +2799,15 @@ static void CheckProtocolMethodDefs(Sema ,
 continue;
 
   unsigned DIAG = diag::warn_unimplemented_protocol_method;
-  if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
-WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
+  if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
+WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
   }
 }
   }
   // Check on this protocols's referenced protocols, recursively.
   for (auto *PI : PDecl->protocols())
-CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
-CDecl, ProtocolsExplictImpl);
+CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
+ProtocolsExplictImpl);
 }
 
 /// MatchAllMethodDeclarations - Check methods declared in interface
@@ -2827,7 +2830,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet 
,
 if 

[PATCH] D116618: [clangd] Use the localSourceRange as the default claimed range for typelocs.

2022-01-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/unittests/SelectionTests.cpp:234
   )cpp",
-  "FunctionProtoTypeLoc",
+  "PointerTypeLoc",
   },

these two new behavior changes seem to be more appropriate.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116618/new/

https://reviews.llvm.org/D116618

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


[PATCH] D116618: [clangd] Use the localSourceRange as the default claimed range for typelocs.

2022-01-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

It also fixes a bug where SelectionTree doesn't select the right AST node on
`int (*Fun(OuterT^ype))(InnerType);`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116618

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -231,7 +231,7 @@
   R"cpp(
 [[void (^*S)(int)]] = nullptr;
   )cpp",
-  "FunctionProtoTypeLoc",
+  "PointerTypeLoc",
   },
   {
   R"cpp(
@@ -243,7 +243,7 @@
   R"cpp(
 [[void ^(*S)(int)]] = nullptr;
   )cpp",
-  "FunctionProtoTypeLoc",
+  "ParenTypeLoc",
   },
   {
   R"cpp(
@@ -326,6 +326,8 @@
   {"const int x = 1, y = 2; [[i^nt]] array[x][10][y];", "BuiltinTypeLoc"},
   {"void func(int x) { int v_array[^[[x]]][10]; }", "DeclRefExpr"},
 
+  {"int (*getFunc([[do^uble]]))(int);", "BuiltinTypeLoc"},
+
   // FIXME: the AST has no location info for qualifiers.
   {"const [[a^uto]] x = 42;", "AutoTypeLoc"},
   {"[[co^nst auto x = 42]];", "VarDecl"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -754,19 +754,40 @@
   // We override this if we want to claim fewer tokens (e.g. there are gaps).
   void claimTokensFor(const DynTypedNode , SelectionTree::Selection ) 
{
 if (const auto *TL = N.get()) {
-  // e.g. EltType Foo[OuterSize][InnerSize];
+  // We need the DecltypeTypeLoc hack in getSourceRange.
+  if (TL->getAs())
+return claimRange(getSourceRange(N), Result);
+
+  // E.g. a function which returns a function pointer.
+  // int (*Fun(OuterType))(InnerType);
+  // ~XXX FunctionProtoTypeLoc
+  // ~X~~ |- PointerTypeLoc: int (*)(InnerType)
+  // X~~~ |  `- ParenTypeLoc: int (InnerType)
+  // ~XXX | `-FunctionProtoTypeLoc: int 
(InnerType)
+  //   ~  `- ParmVarDecl: OuterType
+  // The ParenTypeLoc must not claim its local source range (marked as XXX
+  // above), or it clobbers the outer ParmVarDecl.
+  if ( auto PTL = TL->getAs()) {
+PTL.getLocalSourceRange().dump(SM);
+// Only claim the parentheses tokens, other tokens are handled by its
+// children or are expected unclaimed.
+claimRange(PTL.getLParenLoc(), Result);
+claimRange(PTL.getRParenLoc(), Result);
+return;
+  }
+
+  // We use LocalSourceRange as a default claimed range for TypeLocs -- it
+  // is better than getSourceRange (which returns a range covering itself
+  // and its children), because we want to claim fewer tokens (multiple
+  // discontiguous ranges) for some TypeLocs.
+  // E.g. EltType Foo[OuterSize][InnerSize];
   //  ~ ArrayTypeLoc (Outer)
   //  ~ |-ArrayTypeLoc (Inner)
   //  ~~~   | |-RecordType
   // ~  | `-Expr (InnerSize)
   //  ~ `-Expr (OuterSize)
   // Inner ATL must not claim its whole SourceRange, or it clobbers Outer.
-  if (TL->getAs()) {
-claimRange(TL->getLocalSourceRange(), Result);
-return;
-  }
-  // FIXME: maybe LocalSourceRange is a better default for TypeLocs.
-  // It doesn't seem to be usable for FunctionTypeLocs.
+  return claimRange(TL->getLocalSourceRange(), Result);
 }
 claimRange(getSourceRange(N), Result);
   }


Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -231,7 +231,7 @@
   R"cpp(
 [[void (^*S)(int)]] = nullptr;
   )cpp",
-  "FunctionProtoTypeLoc",
+  "PointerTypeLoc",
   },
   {
   R"cpp(
@@ -243,7 +243,7 @@
   R"cpp(
 [[void ^(*S)(int)]] = nullptr;
   )cpp",
-  "FunctionProtoTypeLoc",
+  "ParenTypeLoc",
   },
   {
   R"cpp(
@@ -326,6 +326,8 @@
   {"const int x = 1, y = 2; [[i^nt]] 

[PATCH] D116615: [Clang] Extract availability mapping from VersionMap for watchOS/tvOS

2022-01-04 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan created this revision.
Herald added a subscriber: dexonsmith.
egorzhdan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This change makes it possible to extract iOS-to-another-platform version 
mappings from `VersionMap` in the `SDKSettings.json` file in Darwin SDKs, for 
example, `iOS_watchOS` and `iOS_tvOS`.

This code was originally authored by Alex Lorenz.

rdar://81491680


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116615

Files:
  clang/lib/Basic/DarwinSDKInfo.cpp
  clang/unittests/Basic/DarwinSDKInfoTest.cpp

Index: clang/unittests/Basic/DarwinSDKInfoTest.cpp
===
--- clang/unittests/Basic/DarwinSDKInfoTest.cpp
+++ clang/unittests/Basic/DarwinSDKInfoTest.cpp
@@ -13,6 +13,67 @@
 using namespace llvm;
 using namespace clang;
 
+// Check the version mapping logic in DarwinSDKInfo.
+TEST(DarwinSDKInfo, VersionMapping) {
+  llvm::json::Object Obj({{"3.0", "1.0"}, {"3.1", "1.2"}});
+  Optional Mapping =
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj,
+VersionTuple());
+  EXPECT_TRUE(Mapping.hasValue());
+  EXPECT_EQ(Mapping->getMinimumValue(), VersionTuple(1));
+
+  // Exact mapping.
+  EXPECT_EQ(Mapping->map(VersionTuple(3), VersionTuple(0, 1), None),
+VersionTuple(1));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 0), VersionTuple(0, 1), None),
+VersionTuple(1));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 0, 0), VersionTuple(0, 1), None),
+VersionTuple(1));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 1), VersionTuple(0, 1), None),
+VersionTuple(1, 2));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 1, 0), VersionTuple(0, 1), None),
+VersionTuple(1, 2));
+
+  // Missing mapping - fallback to major.
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 0, 1), VersionTuple(0, 1), None),
+VersionTuple(1));
+
+  // Minimum
+  EXPECT_EQ(Mapping->map(VersionTuple(2), VersionTuple(0, 1), None),
+VersionTuple(0, 1));
+
+  // Maximum
+  EXPECT_EQ(
+  Mapping->map(VersionTuple(4), VersionTuple(0, 1), VersionTuple(100)),
+  VersionTuple(100));
+}
+
+// Check the version mapping logic in DarwinSDKInfo.
+TEST(DarwinSDKInfo, VersionMappingMissingKey) {
+  llvm::json::Object Obj({{"3.0", "1.0"}, {"5.0", "1.2"}});
+  Optional Mapping =
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj,
+VersionTuple());
+  EXPECT_TRUE(Mapping.hasValue());
+  EXPECT_EQ(
+  Mapping->map(VersionTuple(4), VersionTuple(0, 1), VersionTuple(100)),
+  None);
+}
+
+TEST(DarwinSDKInfo, VersionMappingParseEmpty) {
+  llvm::json::Object Obj({});
+  EXPECT_FALSE(
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple())
+  .hasValue());
+}
+
+TEST(DarwinSDKInfo, VersionMappingParseError) {
+  llvm::json::Object Obj({{"test", "1.2"}});
+  EXPECT_FALSE(
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple())
+  .hasValue());
+}
+
 TEST(DarwinSDKInfoTest, ParseAndTestMapping) {
   llvm::json::Object Obj;
   Obj["Version"] = "11.0";
Index: clang/lib/Basic/DarwinSDKInfo.cpp
===
--- clang/lib/Basic/DarwinSDKInfo.cpp
+++ clang/lib/Basic/DarwinSDKInfo.cpp
@@ -84,6 +84,25 @@
   llvm::DenseMap>
   VersionMappings;
   if (const auto *VM = Obj->getObject("VersionMap")) {
+// FIXME: Generalize this out beyond iOS-deriving targets.
+// Look for ios_ version mapping for targets that derive from ios.
+for (const auto  : *VM) {
+  auto Pair = StringRef(KV.getFirst()).split("_");
+  if (Pair.first.compare_insensitive("ios") == 0) {
+llvm::Triple TT(llvm::Twine("--") + Pair.second.lower());
+if (TT.getOS() != llvm::Triple::UnknownOS) {
+  auto Mapping = RelatedTargetVersionMapping::parseJSON(
+  *KV.getSecond().getAsObject(), *MaximumDeploymentVersion);
+  if (Mapping)
+VersionMappings[OSEnvPair(llvm::Triple::IOS,
+  llvm::Triple::UnknownEnvironment,
+  TT.getOS(),
+  llvm::Triple::UnknownEnvironment)
+.Value] = std::move(Mapping);
+}
+  }
+}
+
 if (const auto *Mapping = VM->getObject("macOS_iOSMac")) {
   auto VersionMap = RelatedTargetVersionMapping::parseJSON(
   *Mapping, *MaximumDeploymentVersion);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


RE: [clang] b8e03be - [PS4][DWARF] Explicitly set default DWARF version to 4

2022-01-04 Thread via cfe-commits
Follow-up to test this explicitly (I thought it was already!) in
https://github.com/llvm/llvm-project/commit/fa17c0e27ac5e874e0d0ce3be9146ee3f5a99016

Thanks for catching this!
--paulr

From: David Blaikie 
Sent: Monday, December 6, 2021 10:44 PM
To: Robinson, Paul ; Paul Robinson 

Cc: cfe-commits 
Subject: Re: [clang] b8e03be - [PS4][DWARF] Explicitly set default DWARF 
version to 4

Guess this is untestable right now, since it's overriding with the same value? 
Maybe worth adding an explicit test for the PS4 default - so that the test 
would fail /if/ the generic (non-PS4) default was changed (which we'll 
hopefully change in the near future)?

On Tue, Nov 30, 2021 at 8:59 AM Paul Robinson via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:

Author: Paul Robinson
Date: 2021-11-30T08:58:40-08:00
New Revision: b8e03be88dc87303f7401ea7b9906947ac67a6db

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

LOG: [PS4][DWARF] Explicitly set default DWARF version to 4

Added:


Modified:
clang/lib/Driver/ToolChains/PS4CPU.h

Removed:




diff  --git a/clang/lib/Driver/ToolChains/PS4CPU.h 
b/clang/lib/Driver/ToolChains/PS4CPU.h
index 82f9523f84fb8..4bedabaf267c0 100644
--- a/clang/lib/Driver/ToolChains/PS4CPU.h
+++ b/clang/lib/Driver/ToolChains/PS4CPU.h
@@ -80,6 +80,7 @@ class LLVM_LIBRARY_VISIBILITY PS4CPU : public Generic_ELF {
 return LangOptions::SSPStrong;
   }

+  unsigned GetDefaultDwarfVersion() const override { return 4; }
   llvm::DebuggerKind getDefaultDebuggerTuning() const override {
 return llvm::DebuggerKind::SCE;
   }



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


[clang] fa17c0e - [PS4] Verify the default DWARF version is 4.

2022-01-04 Thread Paul Robinson via cfe-commits

Author: Paul Robinson
Date: 2022-01-04T11:57:10-08:00
New Revision: fa17c0e27ac5e874e0d0ce3be9146ee3f5a99016

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

LOG: [PS4] Verify the default DWARF version is 4.

Follow-up to b8e03be. Even if Clang's generic default DWARF version
bumps up, PS4 will stay on v4.

Added: 


Modified: 
clang/test/Driver/debug-options.c

Removed: 




diff  --git a/clang/test/Driver/debug-options.c 
b/clang/test/Driver/debug-options.c
index 45a577dc7e7a2..22e05140f2618 100644
--- a/clang/test/Driver/debug-options.c
+++ b/clang/test/Driver/debug-options.c
@@ -279,7 +279,8 @@
 // NOG_PS4-NOT: "-dwarf-version=
 //
 // G_PS4: "-cc1"
-// G_PS4: "-dwarf-version=
+/// PS4 will stay on v4 even if the generic default version changes.
+// G_PS4: "-dwarf-version=4"
 // G_PS4: "-generate-arange-section"
 //
 // G_ERR: error: unknown argument:



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


[PATCH] D116377: [libTooling] Adds more support for constructing object access expressions.

2022-01-04 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 397356.
ymandel added a comment.

ignore implicit and add deprecations


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116377/new/

https://reviews.llvm.org/D116377

Files:
  clang/include/clang/Tooling/Transformer/SourceCodeBuilders.h
  clang/lib/Tooling/Transformer/SourceCodeBuilders.cpp
  clang/lib/Tooling/Transformer/Stencil.cpp
  clang/unittests/Tooling/SourceCodeBuildersTest.cpp

Index: clang/unittests/Tooling/SourceCodeBuildersTest.cpp
===
--- clang/unittests/Tooling/SourceCodeBuildersTest.cpp
+++ clang/unittests/Tooling/SourceCodeBuildersTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Tooling/Transformer/SourceCodeBuilders.h"
+#include "clang/AST/Type.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
@@ -24,8 +25,17 @@
 
 // Create a valid translation unit from a statement.
 static std::string wrapSnippet(StringRef StatementCode) {
-  return ("struct S { S(); S(int); int field; };\n"
+  return ("namespace std {\n"
+  "template  class unique_ptr {};\n"
+  "template  class shared_ptr {};\n"
+  "}\n"
+  "struct A { void super(); };\n"
+  "struct S : public A { S(); S(int); int Field; };\n"
   "S operator+(const S , const S );\n"
+  "struct Smart {\n"
+  "  S* operator->() const;\n"
+  "  S& operator*() const;\n"
+  "};\n"
   "auto test_snippet = []{" +
   StatementCode + "};")
   .str();
@@ -126,6 +136,69 @@
   testPredicateOnArg(mayEverNeedParens, "void f(S); f(3 + 5);", true);
 }
 
+TEST(SourceCodeBuildersTest, isSmartPointerTypeUniquePtr) {
+  std::string Snippet = "std::unique_ptr P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_TRUE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartPointerTypeSharedPtr) {
+  std::string Snippet = "std::shared_ptr P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_TRUE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartPointerTypeDuckType) {
+  std::string Snippet = "Smart P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_TRUE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartPointerTypeNormalTypeFalse) {
+  std::string Snippet = "int *P; P;";
+  auto StmtMatch = matchStmt(Snippet, expr(hasType(qualType().bind("ty";
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_FALSE(
+  isSmartPointerType(*StmtMatch->Result.Nodes.getNodeAs("ty"),
+ *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartDereferenceTrue) {
+  std::string Snippet = "Smart P; *P;";
+  auto StmtMatch = matchStmt(
+  Snippet, expr(cxxOperatorCallExpr(hasUnaryOperand(expr().bind("arg"
+   .bind("expr"));
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  const auto *Arg = StmtMatch->Result.Nodes.getNodeAs("arg");
+  EXPECT_EQ(Arg,
+isSmartDereference(*StmtMatch->Result.Nodes.getNodeAs("expr"),
+   *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
+TEST(SourceCodeBuildersTest, isSmartDereferenceFalse) {
+  std::string Snippet = "int *P; *P;";
+  auto StmtMatch = matchStmt(Snippet, expr().bind("expr"));
+  ASSERT_TRUE(StmtMatch) << "Snippet: " << Snippet;
+  EXPECT_EQ(nullptr,
+isSmartDereference(*StmtMatch->Result.Nodes.getNodeAs("expr"),
+   *StmtMatch->Result.Context))
+  << "Snippet: " << Snippet;
+}
+
 static void testBuilder(
 llvm::Optional (*Builder)(const Expr &, const ASTContext &),
 StringRef Snippet, StringRef Expected) {
@@ -136,6 +209,16 @@
   ValueIs(std::string(Expected)));
 }
 
+static void testBuilder(llvm::Optional (*Builder)(const Expr &,
+   ASTContext &),
+StringRef Snippet, StringRef Expected) {
+  auto StmtMatch = matchStmt(Snippet, expr().bind("expr"));
+  ASSERT_TRUE(StmtMatch);
+  

[PATCH] D116611: [clang][scandeps] Update Module Cache Path in Test

2022-01-04 Thread Sam Elliott via Phabricator via cfe-commits
lenary created this revision.
lenary added reviewers: rsmith, Bigcheese.
lenary requested review of this revision.
Herald added a project: clang.

This fixes the test introduced in D114206  so 
it no longer writes to the current working directory.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116611

Files:
  clang/test/ClangScanDeps/modulemap-via-vfs.m


Index: clang/test/ClangScanDeps/modulemap-via-vfs.m
===
--- clang/test/ClangScanDeps/modulemap-via-vfs.m
+++ clang/test/ClangScanDeps/modulemap-via-vfs.m
@@ -15,7 +15,7 @@
 [
 {
   "directory": "DIR",
-  "command": "clang DIR/main.m -Imodules/A -fmodules 
-fmodules-cache-path=module-cache -fimplicit-modules -fimplicit-module-maps 
-ivfsoverlay build/vfs.yaml",
+  "command": "clang DIR/main.m -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-ivfsoverlay build/vfs.yaml",
   "file": "DIR/main.m"
 }
 ]


Index: clang/test/ClangScanDeps/modulemap-via-vfs.m
===
--- clang/test/ClangScanDeps/modulemap-via-vfs.m
+++ clang/test/ClangScanDeps/modulemap-via-vfs.m
@@ -15,7 +15,7 @@
 [
 {
   "directory": "DIR",
-  "command": "clang DIR/main.m -Imodules/A -fmodules -fmodules-cache-path=module-cache -fimplicit-modules -fimplicit-module-maps -ivfsoverlay build/vfs.yaml",
+  "command": "clang DIR/main.m -Imodules/A -fmodules -fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps -ivfsoverlay build/vfs.yaml",
   "file": "DIR/main.m"
 }
 ]
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114206: [Clang][ScanDeps] Use the virtual path for module maps

2022-01-04 Thread Sam Elliott via Phabricator via cfe-commits
lenary added inline comments.



Comment at: clang/test/ClangScanDeps/modulemap-via-vfs.m:5-6
+// RUN: sed -e "s|DIR|%/t.dir|g" %t.dir/build/vfs.yaml.in > 
%t.dir/build/vfs.yaml
+// RUN: clang-scan-deps -compilation-database 
%t.dir/build/compile-commands.json -j 1 -format experimental-full \
+// RUN:   -mode preprocess-minimized-sources -generate-modules-path-args > 
%t.db
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t.db --module-name=A > 
%t.A.cc1.rsp

rsmith wrote:
> There seems to be a problem with this test: it's writing a module cache to 
> the current working directory instead of writing it into somewhere under 
> `%t`. Presumably this just requires adding a module cache path parameter?
I think the easiest fix is to change the `command` string in the json below, to 
update the passed `-fmodules-cache-path`. I'm working on a patch right now.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D114206/new/

https://reviews.llvm.org/D114206

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


[PATCH] D116155: [clang][AST][ASTImporter] Set record to complete during import of its members.

2022-01-04 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/AST/ASTImporter.cpp:2021
+  // fields imported) at that time without multiple AST import passes.
+  To->setCompleteDefinition(true);
   // Complete the definition even if error is returned.

So `DefinitionCompleterScopeExit` will run `To->setCompleteDefinition(false);`  
after this function exits but this will be in effect during the import the base 
classes. I don't see how the tests you added hit that code.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:7485
+static void foo(A x) {
+  (void)&"text"[x.idx];
+}

The member function body should be considered `complete-class context` so the 
correct thing to do would be have all the fields laid out by this point.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116155/new/

https://reviews.llvm.org/D116155

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


[PATCH] D116592: [clang-format] Missing space after cast in a macro

2022-01-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:1887
+  // parentheses, look past it as these might be chained casts.
+  if (LeftOfParens->is(tok::r_paren) && !LeftOfParens->is(TT_CastRParen)) {
 if (!LeftOfParens->MatchingParen ||

owenpan wrote:
> Nit.
of course my bad.. will make that change


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116592/new/

https://reviews.llvm.org/D116592

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


[PATCH] D116583: Change the default optimisation level of PTXAS from -O0 to -O3. This makes the optimisation levels of PTXAS and the ptxjitcompiler equal (ptxjitcompiler defaults to -O3).

2022-01-04 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Cuda.cpp:433
   } else {
-// If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
-// to no optimizations, but ptxas's default is -O3.
-CmdArgs.push_back("-O0");
+// If no -O was passed, pass -O3 to ptxas -- this makes ptxas's
+// optimization level the same as the ptxjitcompiler.

I think this would be contrary to the expectation that lack of `-O` in clang 
means - `do not optimize` and it generally implies the whole compilation chain, 
including assembler. Matching whatever nvidia tools do is an insufficient 
reason for breaking this assumption, IMO. 

If you do want do run optimized ptxas on unoptimized PTX, you can use 
`-Xcuda-ptxas -O3`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116583/new/

https://reviews.llvm.org/D116583

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


[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Alright, the implementation looks good.

I think just a question of what to do when firing on @implementation. I'd 
suggest one of:

- generating the interface too, you have almost allthe code
- not supporting @implementation yet

We can also keep the current behavior if you feel strongly about it, but I 
guess it will confuse people.




Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:265
+  // Insert before the first non-init instance method.
+  std::vector Anchors = {
+  {[](const Decl *D) {

If there are no non-init instance methods this will insert at the very bottom 
of the `@implementation`. You can add a second anchor to cover this case.

A policy that might make sense here is: 
  {{IsInitMethod, Below}, {Anything, Above}}
But up to you



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:285
+
+  SmallVector Params;
+  initParams(N, Params);

dgoldman wrote:
> sammccall wrote:
> > nit: why isn't this a return value?
> IIUC this (having the impl vector be an out param) seems to be the convention 
> - `SmallVectorImpl(const SmallVectorImpl &) = delete;`, but I can change the 
> return type to instead be SmallVector, WDYT?
Please do.

There are a bunch of reasons that vector out-params are sometimes used in LLVM:
 - caller rather than callee should choose the SmallVector size
 - repeated calls to append to an existing vector
 - return value is something else
 - some old pre-C++11 code

but I think none apply here



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:290
+
+  bool GenerateImpl = isa(Container);
+  llvm::SmallString<256> Text(std::string(LocPadding.PadStart, '\n'));

dgoldman wrote:
> sammccall wrote:
> > Wait, so if the user triggers the action on @interface then they'll get a 
> > decl with no impl, and if they trigger on @implementation they'll get the 
> > opposite?
> > 
> > Seems like we should at least try to generate both, no? (May not be 
> > possible if we're triggering on @interface and index lookup fails, but 
> > still...)
> Yeah, I decided to avoid this due to the complexity for a v1, could look into 
> adding it in a follow up. For sourcekit-lsp, it would only work if you've 
> opened the impl first (since it will only have the dynamic index available). 
> Is there anything I could look at which does something similar?
This seems like it's going to be a surprising limitation. You can mark it the 
tweak as "hidden" if you don't want to expose it to users yet.

Is there much complexity in generating both if targeting the @implementation? 
It seems you've already got both codepaths and just need to run both. If that's 
too complicated, it doesn't really seem like a good idea to support this on 
implementations, generating a definition for a member that doesn't exist is 
confusing.

(I'd suggest changing the description to "declare" memberwise initializer 
whenever you're not generating the definition.)

> For sourcekit-lsp, it would only work if you've opened the impl first

The general approach is to find the target file and then pseudoparse the bits 
you need, as you won't have an AST in any case. So it will still work without 
index if the file can be found using filename heuristics.

> Is there anything I could look at which does something similar?

DefineOutline does something similar: it triggers on a declaration and edits 
the declaration and inserts a definition.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116385/new/

https://reviews.llvm.org/D116385

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


[PATCH] D116592: [clang-format] Missing space after cast in a macro

2022-01-04 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

LGTM except for the nit.




Comment at: clang/lib/Format/TokenAnnotator.cpp:1887
+  // parentheses, look past it as these might be chained casts.
+  if (LeftOfParens->is(tok::r_paren) && !LeftOfParens->is(TT_CastRParen)) {
 if (!LeftOfParens->MatchingParen ||

Nit.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116592/new/

https://reviews.llvm.org/D116592

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


[PATCH] D116203: [clang] adds unary type transformations as compiler built-ins

2022-01-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

The summary for the patch explains what's being added, but there's really no 
information as to why it's being added. Why do we need these builtins?




Comment at: clang/include/clang/AST/Type.h:743
 
+  bool isReferenceable() const;
+

Doc comments would be handy here because this is a pretty recent term of art.



Comment at: clang/include/clang/AST/Type.h:6480
+  //   type that is either an object type, a function type that does not have
+  //   cv-qualifiers or a ref-qualifier, or a reference type
+  const Type  = **this;





Comment at: clang/include/clang/AST/Type.h:6481
+  //   cv-qualifiers or a ref-qualifier, or a reference type
+  const Type  = **this;
+  if (Self.isObjectType() || Self.isReferenceType())

This is unsafe -- the `Type *` can be null if the `QualType` is invalid.



Comment at: clang/include/clang/AST/Type.h:6488
+  const auto *F = Self.getAs();
+  return F == nullptr ||
+ (F->getMethodQuals().empty() && F->getRefQualifier() == RQ_None);

A function without a prototype is referenceable? (This is more of a "should 
this predicate do anything in C?" kind of question, I suppose.)



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8595
+def err_make_signed_integral_only : Error<
+  "'%select{make_unsigned|make_signed}0' is only compatible with non-bool 
integers and enum types, but was given %1">;
 def ext_typecheck_cond_incompatible_pointers : ExtWarn<

This can be reformatted, I believe, but did you look around to see if an 
existing diagnostic would suffice?



Comment at: clang/lib/Sema/DeclSpec.cpp:597
   case DeclSpec::TST_decltype_auto: return "decltype(auto)";
+  // clang-format off
   case DeclSpec::TST_underlyingType: return "__underlying_type";

We don't typically add clang-format markings to the source files. I think this 
should be removed (it disables the formatting for the remainder of the file).



Comment at: clang/lib/Sema/SemaType.cpp:1265
+TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
+  switch (SwitchTST) { // clang-format off
+  case TST_add_const:return UnaryTransformType::AddConst;

Same comments here about the clang-format markup.



Comment at: clang/lib/Sema/SemaType.cpp:1694
 if (Result.isNull()) {
-  Result = Context.IntTy;
+  if (DS.getTypeSpecType() == DeclSpec::TST_underlyingType)
+Result = Context.IntTy;

The point to this was for error recovery; can we recover enough type 
information from the non-underlying type cases to recover similarly?



Comment at: clang/lib/Sema/SemaType.cpp:6023
 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
-  // FIXME: This holds only because we only have one unary transform.
-  assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
+  // Make sure it is a unary transform type
+  assert(DS.getTypeSpecType() >= DeclSpec::TST_underlyingType &&





Comment at: clang/lib/Sema/SemaType.cpp:9121
+SourceLocation Loc) {
+  if (!BaseType->isPointerType())
+return Context.getUnaryTransformType(BaseType, BaseType, UKind);

Should we care about ObjC pointers (which are a bit special)?



Comment at: clang/lib/Sema/SemaType.cpp:9136
+  Qualifiers Quals = Underlying.getQualifiers();
+  Quals.removeCVRQualifiers();
+  return Context.getUnaryTransformType(

What about things like type attributes (are those lost during decay)?



Comment at: clang/test/SemaCXX/type-traits.cpp:3447
+{ int a[T(__is_same(add_cv_t, const volatile M))]; }
+{ int a[T(__is_same(add_lvalue_reference_t, M))]; }
+{ int a[T(__is_same(add_pointer_t, M))]; }

Shouldn't this be the same as `M&`?

Actually, something funky is going on that I've not looked into very far. When 
I try the test out and use `M&` instead of `M` here: 
https://godbolt.org/z/rx5bcsfqe, so we should be sure we're instantiating the 
tests we expect to instantiate.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116203/new/

https://reviews.llvm.org/D116203

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


[PATCH] D116417: [clang][ObjC] Add fix it for missing methods in impl

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman marked an inline comment as done.
dgoldman added inline comments.



Comment at: clang/lib/Sema/SemaDeclObjC.cpp:2241
+method->print(Out, Policy);
+Str.append(" {\n\n}\n\n");
+

sammccall wrote:
> sammccall wrote:
> > nit: mixing string & output stream modifications is a bit confusing
> I think this should probably only have one inside and one at the end.
> 
> Fixits aren't really in the business of formatting the code to be further 
> modified.
> I can't find examples of fixits inserting blank lines that aren't necessary, 
> apart from at the end of decls.
> 
> One newline between empty braces seems to be LLVM's style for objc. (For C++ 
> it's zero newlines)
I changed it to be one newline between the braces but 2 before the @end so you 
get

```
- (void)something {
}

@end
```

since I think that's more common


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116417/new/

https://reviews.llvm.org/D116417

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


[PATCH] D116417: [clang][ObjC] Add fix it for missing methods in impl

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 397336.
dgoldman marked 4 inline comments as done.
dgoldman added a comment.

Fixes for review


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116417/new/

https://reviews.llvm.org/D116417

Files:
  clang/lib/Sema/SemaDeclObjC.cpp
  clang/test/FixIt/fixit-objc-missing-method-impl.m

Index: clang/test/FixIt/fixit-objc-missing-method-impl.m
===
--- /dev/null
+++ clang/test/FixIt/fixit-objc-missing-method-impl.m
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: cp %s %t
+// RUN: not %clang_cc1 -pedantic -Werror -fixit -x objective-c %t
+// RUN: %clang_cc1 -pedantic -Werror -x objective-c %t
+
+__attribute__((objc_root_class))
+@interface NSObject
+@end
+
+@interface Foo : NSObject
+- (void)fooey;  // expected-note{{method 'fooey' declared here}}
+@end
+
+@implementation Foo  // expected-warning{{method definition for 'fooey' not found}}
+@end
Index: clang/lib/Sema/SemaDeclObjC.cpp
===
--- clang/lib/Sema/SemaDeclObjC.cpp
+++ clang/lib/Sema/SemaDeclObjC.cpp
@@ -2212,9 +2212,8 @@
 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
 }
 
-static void WarnUndefinedMethod(Sema , SourceLocation ImpLoc,
-ObjCMethodDecl *method,
-bool ,
+static void WarnUndefinedMethod(Sema , ObjCImplDecl *Impl,
+ObjCMethodDecl *method, bool ,
 unsigned DiagID,
 NamedDecl *NeededFor = nullptr) {
   // No point warning no definition of method which is 'unavailable'.
@@ -2227,10 +2226,19 @@
   // separate warnings.  We will give that approach a try, as that
   // matches what we do with protocols.
   {
-const Sema::SemaDiagnosticBuilder  = S.Diag(ImpLoc, DiagID);
+const Sema::SemaDiagnosticBuilder  = S.Diag(Impl->getLocation(), DiagID);
 B << method;
 if (NeededFor)
   B << NeededFor;
+
+// Add an empty definition at the end of the @implementation.
+std::string FixItStr;
+llvm::raw_string_ostream Out(FixItStr);
+method->print(Out, Impl->getASTContext().getPrintingPolicy());
+Out << " {\n}\n\n";
+
+SourceLocation Loc = Impl->getAtEndRange().getBegin();
+B << FixItHint::CreateInsertion(Loc, FixItStr);
   }
 
   // Issue a note to the original declaration.
@@ -2679,14 +2687,10 @@
 
 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
 /// Declared in protocol, and those referenced by it.
-static void CheckProtocolMethodDefs(Sema ,
-SourceLocation ImpLoc,
-ObjCProtocolDecl *PDecl,
-bool& IncompleteImpl,
-const Sema::SelectorSet ,
-const Sema::SelectorSet ,
-ObjCContainerDecl *CDecl,
-LazyProtocolNameSet ) {
+static void CheckProtocolMethodDefs(
+Sema , ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool ,
+const Sema::SelectorSet , const Sema::SelectorSet ,
+ObjCContainerDecl *CDecl, LazyProtocolNameSet ) {
   ObjCCategoryDecl *C = dyn_cast(CDecl);
   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
: dyn_cast(CDecl);
@@ -2773,9 +2777,8 @@
   if (C || MethodInClass->isPropertyAccessor())
 continue;
 unsigned DIAG = diag::warn_unimplemented_protocol_method;
-if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
-  WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
-  PDecl);
+if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
+  WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
 }
   }
 }
@@ -2796,15 +2799,15 @@
 continue;
 
   unsigned DIAG = diag::warn_unimplemented_protocol_method;
-  if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
-WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
+  if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
+WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
   }
 }
   }
   // Check on this protocols's referenced protocols, recursively.
   for (auto *PI : PDecl->protocols())
-CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
-CDecl, ProtocolsExplictImpl);
+CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
+ProtocolsExplictImpl);
 }
 
 /// MatchAllMethodDeclarations - Check methods declared in interface
@@ -2827,7 +2830,7 @@
 if (!I->isPropertyAccessor() &&
 !InsMap.count(I->getSelector())) {
   if 

[clang] e1e74f6 - -Wmissing-prototypes: Don't warn in named namespaces nested in anonymous namespaces

2022-01-04 Thread David Blaikie via cfe-commits

Author: David Blaikie
Date: 2022-01-04T10:08:23-08:00
New Revision: e1e74f6cd6ce41ce8303a5a91f29736808fccc36

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

LOG: -Wmissing-prototypes: Don't warn in named namespaces nested in anonymous 
namespaces

Added: 


Modified: 
clang/lib/AST/Decl.cpp
clang/test/SemaCXX/warn-missing-prototypes.cpp

Removed: 




diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index e63560f1b6fea..3ef08cab96750 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -3251,7 +3251,6 @@ bool FunctionDecl::isGlobal() const {
 if (const auto *Namespace = cast(DC)) {
   if (!Namespace->getDeclName())
 return false;
-  break;
 }
   }
 

diff  --git a/clang/test/SemaCXX/warn-missing-prototypes.cpp 
b/clang/test/SemaCXX/warn-missing-prototypes.cpp
index bb71aa8b142d1..e8637e5a90eab 100644
--- a/clang/test/SemaCXX/warn-missing-prototypes.cpp
+++ b/clang/test/SemaCXX/warn-missing-prototypes.cpp
@@ -13,6 +13,10 @@ namespace NS {
 namespace {
   // Don't warn about functions in anonymous namespaces.
   void f() { }
+  // Even if they're in nested namespaces within an anonymous namespace.
+  namespace NS {
+void f() { }
+  }
 }
 
 struct A {



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


[PATCH] D113049: [AIX] Disable tests that fail because of no 64-bit XCOFF object file support

2022-01-04 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan added inline comments.



Comment at: clang/test/ASTMerge/codegen-body/test.c:1
+// UNSUPPORTED: powerpc64-ibm-aix
 // RUN: %clang_cc1 -emit-pch -o %t.1.ast %S/Inputs/body1.c

shchenz wrote:
> Jake-Egan wrote:
> > shchenz wrote:
> > > Do we still need this? -emit-obj is already excluded?
> > Excluding this test causes regressions because LIT can't find any tests at 
> > `/codegen-body` directory:
> > ```
> > Clang :: utils/update_cc_test_checks/global-hex-value-regex.test
> > Clang :: utils/update_cc_test_checks/global-value-regex.test
> > ```
> > I figure it's easier to mark this test unsupported. 
> Is it possible to add `expected-no-diagnostics` for any of the above two RUN 
> lines? So we will have a test point and be able to exclude this case?
Unfortunately adding `expected-no-diagnostics` fix the issue. The existing 
`expected-no-diagnostics` is already applied to all the RUN lines.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D113049/new/

https://reviews.llvm.org/D113049

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


[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman marked an inline comment as done.
dgoldman added inline comments.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:91
+
+struct LocationWithPadding {
+  SourceLocation Loc;

sammccall wrote:
> We try not to spend complexity on formatting beyond what clang-format cares 
> about. 
> 
> If you're inserting before a member (or @end), always inserting 2 newlines 
> seems close enough? (clang-format will strip consecutive blank lines)
Just went with that for now, can revisit later. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116385/new/

https://reviews.llvm.org/D116385

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


[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 397329.
dgoldman marked 3 inline comments as done.
dgoldman added a comment.

Rebase + use new helpers


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116385/new/

https://reviews.llvm.org/D116385

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
@@ -0,0 +1,151 @@
+//===-- ObjCMemberwiseInitializerTests.cpp --*- 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: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(ObjCMemberwiseInitializer);
+
+TEST_F(ObjCMemberwiseInitializerTest, TestAvailability) {
+  FileName = "TestTU.m";
+
+  // Ensure the action can't be triggered since arc is disabled.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+
+  ExtraArgs.push_back("-fobjc-arc");
+
+  // Ensure the action can be initiated on the interface and implementation,
+  // but not on the forward declaration.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation F^oo
+@end
+  )cpp");
+  EXPECT_UNAVAILABLE("@class Fo^o;");
+
+  // Ensure that the action can be triggered on ivars and properties,
+  // including selecting both.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id fi^eld;
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@property(nonatomic) id pr^op;
+@end
+  )cpp");
+
+  // Ensure that the action can't be triggered on property synthesis
+  // and methods.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id prop;
+@end
+
+@implementation Foo
+@dynamic pr^op;
+@end
+  )cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation Foo
+- (void)fo^o {}
+@end
+  )cpp");
+}
+
+TEST_F(ObjCMemberwiseInitializerTest, Test) {
+  FileName = "TestTU.m";
+  ExtraArgs.push_back("-fobjc-arc");
+
+  const char *Input = R"cpp(
+@interface Foo {
+  id [[_field;
+}
+@property(nonatomic) id prop]];
+@property(nonatomic) id notSelected;
+@end)cpp";
+  const char *Output = R"cpp(
+@interface Foo {
+  id _field;
+}
+@property(nonatomic) id prop;
+@property(nonatomic) id notSelected;
+- (instancetype)initWithField:(id)field prop:(id)prop;
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+
+  Input = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation F^oo
+
+- (instancetype)init {
+  return self;
+}
+
+@end)cpp";
+  Output = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation Foo
+
+- (instancetype)init {
+  return self;
+}
+
+- (instancetype)initWithSomePrettyLongPropertyName:(nullable id)somePrettyLongPropertyName someReallyLongPropertyName:(nonnull id)someReallyLongPropertyName {
+  self = [super init];
+  if (self) {
+_somePrettyLongPropertyName = somePrettyLongPropertyName;
+_someReallyLongPropertyName = someReallyLongPropertyName;
+  }
+  return self;
+}
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/clangd/unittests/CMakeLists.txt
===
--- clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -118,6 +118,7 @@
   tweaks/ExtractFunctionTests.cpp
   tweaks/ExtractVariableTests.cpp
   tweaks/ObjCLocalizeStringLiteralTests.cpp
+  tweaks/ObjCMemberwiseInitializerTests.cpp
   tweaks/PopulateSwitchTests.cpp
   tweaks/RawStringLiteralTests.cpp
   tweaks/RemoveUsingNamespaceTests.cpp
Index: clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
===
--- /dev/null
+++ 

[PATCH] D115670: Implement some constexpr vector unary operators, fix boolean-ops

2022-01-04 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Should be fixed here: 2edc21e8566be8fa9b20e0bb71a83af90ec9aa97 


Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115670/new/

https://reviews.llvm.org/D115670

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


[clang] 2edc21e - Fix altivec regression caused by D115670 in Vec Const Eval

2022-01-04 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-01-04T09:53:26-08:00
New Revision: 2edc21e8566be8fa9b20e0bb71a83af90ec9aa97

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

LOG: Fix altivec regression caused by D115670 in Vec Const Eval

The Vector Constant Evaluator assumes that all the types of its
sub-expressions are going to be Vector APValues, which holds for most
situations.  However, in the 1 examples of Altivec C compilation of
operator ++ (not allowed for other vector types), the result is an
LValue.

Since the operator isn't supported for constant evaluation anyway, this
patch just fails-out of constant eval if we are in a situation where the
operand to the unary operator causes an LValue.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/Sema/altivec-init.c

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3bf205d8cb064..9412aba42dfb7 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -10434,6 +10434,15 @@ bool VectorExprEvaluator::VisitUnaryOperator(const 
UnaryOperator *E) {
   if (!Evaluate(SubExprValue, Info, SubExpr))
 return false;
 
+  // FIXME: This vector evaluator someday needs to be changed to be LValue
+  // aware/keep LValue information around, rather than dealing with just vector
+  // types directly. Until then, we cannot handle cases where the operand to
+  // these unary operators is an LValue. The only case I've been able to see
+  // cause this is operator++ assigning to a member expression (only valid in
+  // altivec compilations) in C mode, so this shouldn't limit us too much.
+  if (SubExprValue.isLValue())
+return false;
+
   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
  "Vector length doesn't match type?");
 

diff  --git a/clang/test/Sema/altivec-init.c b/clang/test/Sema/altivec-init.c
index 1c20450a6d015..ee38e70706714 100644
--- a/clang/test/Sema/altivec-init.c
+++ b/clang/test/Sema/altivec-init.c
@@ -45,3 +45,16 @@ void test()
   int res = vGCC > vAltiVec;
   vAltiVec = 0 ? vGCC : vGCC;
 }
+
+typedef struct VecMem {
+  vector signed vec;
+} VecMem;
+
+// The following should not assert.  See qiongsiwu1's comment here: 
+// https://reviews.llvm.org/D115670
+void test2() {
+  vector signed local_vec = {1, 2, 3, 4};
+  VecMem VM;
+  VM.vec = ++local_vec;
+}
+



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


[PATCH] D116221: [AArch64][ARM][Clang] Unaligned Access Warning Added

2022-01-04 Thread Sam Elliott via Phabricator via cfe-commits
lenary accepted this revision.
lenary added a comment.

LGTM! Thanks for your hard work on this!

I think you've addressed @pbarrio's comments on this, and I'm not sure when 
he's back, so wait 48h before landing this, in case there are further comments.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116221/new/

https://reviews.llvm.org/D116221

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


RE: [clang] 229c95a - [CodeCompletion] Signature help for aggregate initialization.

2022-01-04 Thread via cfe-commits
Yeah, our automation appears to have tripped up on the weird character in the 
name (which is why I noticed this in the first place). Easy enough to handle 
manually.
Thanks,
--paulr

From: Sam McCall 
Sent: Tuesday, January 4, 2022 11:47 AM
To: Robinson, Paul 
Cc: cfe-commits 
Subject: Re: [clang] 229c95a - [CodeCompletion] Signature help for aggregate 
initialization.

On Tue, Jan 4, 2022 at 5:39 PM 
mailto:paul.robin...@sony.com>> wrote:
This commit appears to add a file "tl" which I suspect wasn't intended?
--paulr

Yes, I removed it in 10bb837feb22ad70dc4acc3d2cdb5be7f45d1c21.
(A command-line mistake compounded by a careless git commit --amend -a)

The filename also has a nonprintable character after "tl", which might cause 
problems for some tools, though I hope not.

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


[PATCH] D116596: [clang][dataflow] Add transfer functions for assignment

2022-01-04 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:34
+/// storage locations or values.
+enum class SkipPast {
+  /// No indirections should be skipped past.

I am just wondering if this is the right level of abstraction. Maybe users do 
think of this in terms of skipping references? 
Or would they think in terms of value categories? E.g., having `getLValue` vs 
`getRValue`. I think we can leave this as is for now, I just like the idea of 
exploring alternatives.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:95
+StorageLocation ::createStorageLocation(const Expr ) {
+  // Evaluated expressions are always assigned the same storage locations to
+  // ensure that the environment stabilizes across loop iterations. Storage

What is the model for expressions that evaluate to different locations in every 
loop iterations, e.g.:
```
for(int *p = array; p != array + size; ++p)
  *p; // The dereference expression
```

Here, having `*p` always evaluate to the same location is not correct, we'd 
probably need a way to widen this. 



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:46
+
+  Env.setValue(*LHSLoc, *RHSVal);
+}

I think you probably also want to set the correct location for the whole 
expression. Or is that handled somewhere else?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116596/new/

https://reviews.llvm.org/D116596

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


[PATCH] D116221: [AArch64][ARM][Clang] Unaligned Access Warning Added

2022-01-04 Thread Mubashar Ahmad via Phabricator via cfe-commits
mubashar_ updated this revision to Diff 397322.
mubashar_ marked 2 inline comments as done.
mubashar_ added a comment.

Enabled warning whenever +strict-align is present.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116221/new/

https://reviews.llvm.org/D116221

Files:
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/lib/Driver/ToolChains/Arch/AArch64.h
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Sema/test-wunaligned-access.c
  clang/test/Sema/test-wunaligned-access.cpp

Index: clang/test/Sema/test-wunaligned-access.cpp
===
--- /dev/null
+++ clang/test/Sema/test-wunaligned-access.cpp
@@ -0,0 +1,285 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only -Wunaligned-access
+
+// Packed-Unpacked Tests (No Pragma)
+
+struct T1 {
+  char a;
+  int b;
+};
+
+struct __attribute__((packed)) U1 // Causes warning
+{
+  char a;
+  T1 b; // expected-warning {{field b within its parent 'U1' has an alignment greater than its parent this may be caused by 'U1' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+struct __attribute__((packed)) U2 // No warning
+{
+  char a;
+  T1 b __attribute__((aligned(4)));
+  int c;
+};
+
+struct __attribute__((packed)) U3 // No warning
+{
+  char a;
+  char b;
+  short c;
+  T1 d;
+};
+
+struct __attribute__((packed)) U4 // No warning
+{
+  T1 a;
+  int b;
+};
+
+struct __attribute__((aligned(4), packed)) U5 // Causes warning
+{
+  char a;
+  T1 b; // expected-warning {{field b within its parent 'U5' has an alignment greater than its parent this may be caused by 'U5' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+struct __attribute__((aligned(4), packed)) U6 // No warning
+{
+  char a;
+  char b;
+  short c;
+  T1 d;
+};
+
+// Packed-Unpacked Tests with Pragma
+
+#pragma pack(push, 1)
+
+struct __attribute__((packed)) U7 // Causes warning
+{
+  char a;
+  T1 b; // expected-warning {{field b within its parent 'U7' has an alignment greater than its parent this may be caused by 'U7' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+struct __attribute__((packed)) U8 {
+  char a;
+  T1 b __attribute__((aligned(4))); // expected-warning {{field b within its parent 'U8' has an alignment greater than its parent this may be caused by 'U8' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+struct __attribute__((aligned(4))) U9 {
+  char a;
+  T1 b; // expected-warning {{field b within its parent 'U9' has an alignment greater than its parent this may be caused by 'U9' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+struct U10 {
+  char a;
+  T1 b; // expected-warning {{field b within its parent 'U10' has an alignment greater than its parent this may be caused by 'U10' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+#pragma pack(pop)
+
+// Packed-Packed Tests
+
+struct __attribute__((packed)) T2 {
+  char a;
+  int b;
+};
+
+struct __attribute__((packed)) U11 {
+  char a;
+  T2 b;
+  int c;
+};
+
+#pragma pack(push, 1)
+struct U12 // No warning
+{
+  char a;
+  T2 b;
+  int c;
+};
+#pragma pack(pop)
+
+// Unpacked-Packed Tests
+
+struct U13 // No warning
+{
+  char a;
+  T2 b;
+  int c;
+};
+
+struct U14 // No warning
+{
+  char a;
+  T2 b __attribute__((aligned(4)));
+  int c;
+};
+
+// Unpacked-Unpacked Test
+
+struct T3 {
+  char a;
+  int b;
+};
+
+struct U15 // No warning
+{
+  char a;
+  T3 b;
+  int c;
+};
+
+// Packed-Packed-Unpacked Test (No pragma)
+
+struct __attribute__((packed)) A1 {
+  char a;
+  T1 b; // expected-warning {{field b within its parent 'A1' has an alignment greater than its parent this may be caused by 'A1' being packed and can lead to unaligned accesses}}
+};
+
+struct __attribute__((packed)) U16 // No warning
+{
+  char a;
+  A1 b;
+  int c;
+};
+
+struct __attribute__((packed)) A2 // No warning
+{
+  char a;
+  T1 b __attribute__((aligned(4)));
+};
+
+struct __attribute__((packed)) U17 // Caused warning
+{
+  char a;
+  A2 b; // expected-warning {{field b within its parent 'U17' has an alignment greater than its parent this may be caused by 'U17' being packed and can lead to unaligned accesses}}
+  int c;
+};
+
+// Packed-Unpacked-Packed tests
+
+struct A3 {
+  char a;
+  T2 b;
+};
+
+struct __attribute__((packed)) U18 {
+  char a;
+  A3 b;
+  int c;
+};
+
+struct A4 {
+  char a;
+  T2 b;
+  int c;
+};
+
+#pragma pack(push, 1)
+struct U19 // Caused warning
+{
+  char a;
+  A4 b; // expected-warning {{field b within its parent 'U19' has an alignment greater than its parent this may be caused by 'U19' being packed and can lead to unaligned accesses}}
+  int c;
+};
+#pragma pack(pop)
+
+// Packed-Unpacked-Unpacked tests
+
+struct A5 {
+  char a;
+  T1 b;
+};
+
+struct __attribute__((packed)) U20 // Caused 

[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman marked 3 inline comments as not done.
dgoldman added inline comments.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:113
+if (MD->getMethodFamily() == OMF_init) {
+  Loc = effectiveEndLoc(MD, SM).getLocWithOffset(1);
+} else if (Loc.isValid()) {

sammccall wrote:
> This algorithm doesn't make much sense to me. 
> You want to insert before the first non-init instance method, falling back to 
> the end.
> So why do you need to do more than search for the first non-init instance 
> method, and find the location before it? In particular why are we looking at 
> init methods and locations after them?
Yeah, I think that makes more sense, changed.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:199
+
+  // We support the following selected decls:
+  // - ObjCInterfaceDecl/ObjCImplementationDecl only - generate for all

sammccall wrote:
> I understand the desire to select the particular fields, but given the 
> limitation of the interaction I wonder whether these cases are useful & 
> discoverable enough to be worth the complexity.
> 
> - how often is an initializer that sets one variable of many useful?
> - out of the times when a subset of variables should be initialized, how 
> often are they contiguous in the code?
> 
> I think it would likely be better to start with initializing all members...
I didn't realize that VS Code only lets you select a range, not selecting 
multiple points (e.g. multiple cursors). I still think this could be useful and 
it isn't that hard to support, although yes, ideally we could do something like 
IntelliJ where it presents you a UI to select fields. The main use case of this 
atm is for simple model objects, and for those I think it could be useful to 
make some params optional although the contiguous limitation is definitely 
restrictive.

FWIW I don't think code actions in general are particularly discoverable.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:285
+
+  SmallVector Params;
+  initParams(N, Params);

sammccall wrote:
> nit: why isn't this a return value?
IIUC this (having the impl vector be an out param) seems to be the convention - 
`SmallVectorImpl(const SmallVectorImpl &) = delete;`, but I can change the 
return type to instead be SmallVector, WDYT?



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:290
+
+  bool GenerateImpl = isa(Container);
+  llvm::SmallString<256> Text(std::string(LocPadding.PadStart, '\n'));

sammccall wrote:
> Wait, so if the user triggers the action on @interface then they'll get a 
> decl with no impl, and if they trigger on @implementation they'll get the 
> opposite?
> 
> Seems like we should at least try to generate both, no? (May not be possible 
> if we're triggering on @interface and index lookup fails, but still...)
Yeah, I decided to avoid this due to the complexity for a v1, could look into 
adding it in a follow up. For sourcekit-lsp, it would only work if you've 
opened the impl first (since it will only have the dynamic index available). Is 
there anything I could look at which does something similar?



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp:291
+  bool GenerateImpl = isa(Container);
+  llvm::SmallString<256> Text(std::string(LocPadding.PadStart, '\n'));
+

sammccall wrote:
> For building strings like this with formatting, we usually use 
> raw_string_ostream and `formatv`.
> This would make the stuff starting at 303 easier to read
Yep that helps quite a bit


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116385/new/

https://reviews.llvm.org/D116385

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


[PATCH] D116385: [clangd] Code action for creating an ObjC initializer

2022-01-04 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 397321.
dgoldman marked 11 inline comments as done.
dgoldman added a comment.

Some review fixes, still need to rebase for new changes


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116385/new/

https://reviews.llvm.org/D116385

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/tweaks/ObjCMemberwiseInitializerTests.cpp
@@ -0,0 +1,152 @@
+//===-- ObjCMemberwiseInitializerTests.cpp --*- 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: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(ObjCMemberwiseInitializer);
+
+TEST_F(ObjCMemberwiseInitializerTest, TestAvailability) {
+  FileName = "TestTU.m";
+
+  // Ensure the action can't be triggered since arc is disabled.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+
+  ExtraArgs.push_back("-fobjc-arc");
+
+  // Ensure the action can be initiated on the interface and implementation,
+  // but not on the forward declaration.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Fo^o
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation F^oo
+@end
+  )cpp");
+  EXPECT_UNAVAILABLE("@class Fo^o;");
+
+  // Ensure that the action can be triggered on ivars and properties,
+  // including selecting both.
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id fi^eld;
+@end
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp(
+@interface Foo {
+  id _fi^eld;
+}
+@property(nonatomic) id pr^op;
+@end
+  )cpp");
+
+  // Ensure that the action can't be triggered on property synthesis
+  // and methods.
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@property(nonatomic) id prop;
+@end
+
+@implementation Foo
+@dynamic pr^op;
+@end
+  )cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+@interface Foo
+@end
+
+@implementation Foo
+- (void)fo^o {}
+@end
+  )cpp");
+}
+
+TEST_F(ObjCMemberwiseInitializerTest, Test) {
+  FileName = "TestTU.m";
+  ExtraArgs.push_back("-fobjc-arc");
+
+  const char *Input = R"cpp(
+@interface Foo {
+  id [[_field;
+}
+@property(nonatomic) id prop]];
+@property(nonatomic) id notSelected;
+@end)cpp";
+  const char *Output = R"cpp(
+@interface Foo {
+  id _field;
+}
+@property(nonatomic) id prop;
+@property(nonatomic) id notSelected;
+
+- (instancetype)initWithField:(id)field prop:(id)prop;
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+
+  Input = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation F^oo
+
+- (instancetype)init {
+  return self;
+}
+
+@end)cpp";
+  Output = R"cpp(
+@interface Foo
+@property(nonatomic, nullable) id somePrettyLongPropertyName;
+@property(nonatomic, nonnull) id someReallyLongPropertyName;
+@end
+
+@implementation Foo
+
+- (instancetype)init {
+  return self;
+}
+
+- (instancetype)initWithSomePrettyLongPropertyName:(nullable id)somePrettyLongPropertyName someReallyLongPropertyName:(nonnull id)someReallyLongPropertyName {
+  self = [super init];
+  if (self) {
+_somePrettyLongPropertyName = somePrettyLongPropertyName;
+_someReallyLongPropertyName = someReallyLongPropertyName;
+  }
+  return self;
+}
+
+@end)cpp";
+  EXPECT_EQ(apply(Input), Output);
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/clangd/unittests/CMakeLists.txt
===
--- clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -117,6 +117,7 @@
   tweaks/ExtractFunctionTests.cpp
   tweaks/ExtractVariableTests.cpp
   tweaks/ObjCLocalizeStringLiteralTests.cpp
+  tweaks/ObjCMemberwiseInitializerTests.cpp
   tweaks/PopulateSwitchTests.cpp
   tweaks/RawStringLiteralTests.cpp
   tweaks/RemoveUsingNamespaceTests.cpp
Index: clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp

[PATCH] D116577: [clang-tidy] Added "boost-use-range-based-for-loop" check

2022-01-04 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/boost/CMakeLists.txt:8
   BoostTidyModule.cpp
+  UseRangeBasedForLoopCheck.cpp
   UseToStringCheck.cpp

I am wondering if this check is better placed in the modernize module?
Maybe as an enhancement to the existing `modernize-loop-convert`?



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.cpp:17
+#include 
+
+namespace clang {

`#include ` for `std::make_unique<>`



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.cpp:39
+const MacroArgs *Args) override {
+IdentifierInfo *NameIdentifierInfo = MacroNameToken.getIdentifierInfo();
+if (!NameIdentifierInfo)

Can this be `const IdentifierInfo *`?



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.cpp:64
+
+Diag << FixItHint::CreateReplacement(
+CharSourceRange::getCharRange(MacroNameToken.getLocation(),

Can't you just chain this with the previous statement?

So

```
Check->diag(...)
<< MacroName
<< FixItHint::CreateReplacement(...);
```



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/boost-use-range-based-for-loop.rst:30
+-
+* Client code that use ``BOOST_FOREACH`` with "``std::pair`` of iterators" or 
with "Null-terminated strings (``char`` and ``wchar_t``)" or some other 
sequence types (everything that is not declared in the list "convertible 
correctly" above) will produce broken code (compilation error).
+

Eugene.Zelenko wrote:
> Please separate with newline and follow 80 character limit. Also closing 
> quote for `Null-terminated strings` is missing.
It would be better to detect known failure cases in the matcher and not issue a 
fixit but perhaps issue a diagnostic.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/boost-use-range-based-for-loop.rst:47
+
+* First argument of the ``BOOST_FOREACH`` macro must be only new identifier 
definition, all other will produce a compilation error after migration.
+

Can't you detect this in the matcher and not issue a fixit in that case?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/boost-use-range-based-for-loop.cpp:9
+#define BOOST_FOREACH(VAR, COL) while(true)
+#define BOOST_REVERSE_FOREACH(VAR, COL) while(true)
+

Why define this (and `foreach_r_`) if you don't have any tests around it?

Do you intend to support a conversion for the reverse iteration?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116577/new/

https://reviews.llvm.org/D116577

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


[PATCH] D115003: [funcattrs] Infer writeonly argument attribute [part 2]

2022-01-04 Thread Philip Reames via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0b09313cd533: [funcattrs] Infer writeonly argument attribute 
[part 2] (authored by reames).

Changed prior to commit:
  https://reviews.llvm.org/D115003?vs=397124=397319#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115003/new/

https://reviews.llvm.org/D115003

Files:
  clang/test/CodeGen/arm-vfp16-arguments.c
  clang/test/CodeGenCXX/wasm-args-returns.cpp
  clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
  llvm/lib/Transforms/IPO/FunctionAttrs.cpp
  llvm/test/Analysis/TypeBasedAliasAnalysis/functionattrs.ll
  llvm/test/Other/cgscc-devirt-iteration.ll
  llvm/test/Transforms/FunctionAttrs/norecurse.ll
  llvm/test/Transforms/FunctionAttrs/writeonly.ll

Index: llvm/test/Transforms/FunctionAttrs/writeonly.ll
===
--- llvm/test/Transforms/FunctionAttrs/writeonly.ll
+++ llvm/test/Transforms/FunctionAttrs/writeonly.ll
@@ -78,15 +78,23 @@
 
 declare void @direct2_callee(i8* %p) writeonly
 
+; writeonly w/o nocapture is not enough
 ; CHECK: define void @direct2(i8* %p)
 define void @direct2(i8* %p) {
   call void @direct2_callee(i8* %p)
+  ; read back from global, read through pointer...
   ret void
 }
 
-declare void @direct3_callee(i8* writeonly %p)
+; CHECK: define void @direct2b(i8* nocapture writeonly %p)
+define void @direct2b(i8* %p) {
+  call void @direct2_callee(i8* nocapture %p)
+  ret void
+}
+
+declare void @direct3_callee(i8* nocapture writeonly %p)
 
-; CHECK: define void @direct3(i8* %p)
+; CHECK: define void @direct3(i8* nocapture writeonly %p)
 define void @direct3(i8* %p) {
   call void @direct3_callee(i8* %p)
   ret void
@@ -98,15 +106,15 @@
   ret void
 }
 
-; CHECK: define void @fptr_test2(i8* %p, void (i8*)* nocapture readonly %f)
+; CHECK: define void @fptr_test2(i8* nocapture writeonly %p, void (i8*)* nocapture readonly %f)
 define void @fptr_test2(i8* %p, void (i8*)* %f) {
-  call void %f(i8* writeonly %p)
+  call void %f(i8* nocapture writeonly %p)
   ret void
 }
 
-; CHECK: define void @fptr_test3(i8* %p, void (i8*)* nocapture readonly %f)
+; CHECK: define void @fptr_test3(i8* nocapture writeonly %p, void (i8*)* nocapture readonly %f)
 define void @fptr_test3(i8* %p, void (i8*)* %f) {
-  call void %f(i8* %p) writeonly
+  call void %f(i8* nocapture %p) writeonly
   ret void
 }
 
Index: llvm/test/Transforms/FunctionAttrs/norecurse.ll
===
--- llvm/test/Transforms/FunctionAttrs/norecurse.ll
+++ llvm/test/Transforms/FunctionAttrs/norecurse.ll
@@ -50,7 +50,7 @@
 ; CHECK: Function Attrs
 ; CHECK-SAME: nounwind
 ; CHECK-NOT: norecurse
-; CHECK-NEXT: define void @intrinsic(i8* nocapture %dest, i8* nocapture readonly %src, i32 %len)
+; CHECK-NEXT: define void @intrinsic(i8* nocapture writeonly %dest, i8* nocapture readonly %src, i32 %len)
 define void @intrinsic(i8* %dest, i8* %src, i32 %len) {
   call void @llvm.memcpy.p0i8.p0i8.i32(i8* %dest, i8* %src, i32 %len, i1 false)
   ret void
Index: llvm/test/Other/cgscc-devirt-iteration.ll
===
--- llvm/test/Other/cgscc-devirt-iteration.ll
+++ llvm/test/Other/cgscc-devirt-iteration.ll
@@ -112,7 +112,7 @@
 ; CHECK-NOT: read
 ; CHECK-SAME: noinline
 ; BEFORE-LABEL: define void @test3(i8* %src, i8* %dest, i64 %size)
-; AFTER-LABEL: define void @test3(i8* nocapture readonly %src, i8* nocapture %dest, i64 %size)
+; AFTER-LABEL: define void @test3(i8* nocapture readonly %src, i8* nocapture writeonly %dest, i64 %size)
   %fptr = alloca i8* (i8*, i8*, i64)*
   store i8* (i8*, i8*, i64)* @memcpy, i8* (i8*, i8*, i64)** %fptr
   %f = load i8* (i8*, i8*, i64)*, i8* (i8*, i8*, i64)** %fptr
Index: llvm/test/Analysis/TypeBasedAliasAnalysis/functionattrs.ll
===
--- llvm/test/Analysis/TypeBasedAliasAnalysis/functionattrs.ll
+++ llvm/test/Analysis/TypeBasedAliasAnalysis/functionattrs.ll
@@ -49,7 +49,7 @@
   ret void
 }
 
-; CHECK: define void @test2_no(i8* nocapture %p, i8* nocapture readonly %q, i64 %n) #5 {
+; CHECK: define void @test2_no(i8* nocapture writeonly %p, i8* nocapture readonly %q, i64 %n) #5 {
 define void @test2_no(i8* %p, i8* %q, i64 %n) nounwind {
   call void @llvm.memcpy.p0i8.p0i8.i64(i8* %p, i8* %q, i64 %n, i1 false), !tbaa !2
   ret void
Index: llvm/lib/Transforms/IPO/FunctionAttrs.cpp
===
--- llvm/lib/Transforms/IPO/FunctionAttrs.cpp
+++ llvm/lib/Transforms/IPO/FunctionAttrs.cpp
@@ -720,10 +720,16 @@
 
   // The accessors used on call site here do the right thing for calls and
   // invokes with operand bundles.
-  if (!CB.onlyReadsMemory() && !CB.onlyReadsMemory(UseIndex))
-return Attribute::None;
-  if 

[clang] 0b09313 - [funcattrs] Infer writeonly argument attribute [part 2]

2022-01-04 Thread Philip Reames via cfe-commits

Author: Philip Reames
Date: 2022-01-04T09:07:54-08:00
New Revision: 0b09313cd53316eacbdc5e98d4ef00bef2c41d02

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

LOG: [funcattrs] Infer writeonly argument attribute [part 2]

This builds on the code from D114963, and extends it to handle calls both 
direct and indirect. With the revised code structure (from series of previously 
landed NFCs), this is pretty straight forward.

One thing to note is that we can not infer writeonly for arguments which might 
be captured. If the pointer can be read back by the caller, and then read 
through, we have no way to track that. This is the same restriction we have for 
readonly, except that we get no mileage out of the "callee can be readonly" 
exception since a writeonly param on a readonly function is either a) readnone 
or b) UB. This means we can't actually infer much unless nocapture has already 
been inferred.

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

Added: 


Modified: 
clang/test/CodeGen/arm-vfp16-arguments.c
clang/test/CodeGenCXX/wasm-args-returns.cpp
clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
llvm/lib/Transforms/IPO/FunctionAttrs.cpp
llvm/test/Analysis/TypeBasedAliasAnalysis/functionattrs.ll
llvm/test/Other/cgscc-devirt-iteration.ll
llvm/test/Transforms/FunctionAttrs/norecurse.ll
llvm/test/Transforms/FunctionAttrs/writeonly.ll

Removed: 




diff  --git a/clang/test/CodeGen/arm-vfp16-arguments.c 
b/clang/test/CodeGen/arm-vfp16-arguments.c
index e11ec1508bbf..0ad099092a9a 100644
--- a/clang/test/CodeGen/arm-vfp16-arguments.c
+++ b/clang/test/CodeGen/arm-vfp16-arguments.c
@@ -71,6 +71,6 @@ void test_hfa(hfa_t a) {}
 
 hfa_t ghfa;
 hfa_t test_ret_hfa(void) { return ghfa; }
-// CHECK-SOFT: define{{.*}} void @test_ret_hfa(%struct.hfa_t* noalias 
nocapture sret(%struct.hfa_t) align 8 %agg.result)
+// CHECK-SOFT: define{{.*}} void @test_ret_hfa(%struct.hfa_t* noalias 
nocapture writeonly sret(%struct.hfa_t) align 8 %agg.result)
 // CHECK-HARD: define{{.*}} arm_aapcs_vfpcc [2 x <2 x i32>] @test_ret_hfa()
 // CHECK-FULL: define{{.*}} arm_aapcs_vfpcc %struct.hfa_t @test_ret_hfa()

diff  --git a/clang/test/CodeGenCXX/wasm-args-returns.cpp 
b/clang/test/CodeGenCXX/wasm-args-returns.cpp
index c05bb44c05a3..d71bb28eabcc 100644
--- a/clang/test/CodeGenCXX/wasm-args-returns.cpp
+++ b/clang/test/CodeGenCXX/wasm-args-returns.cpp
@@ -30,7 +30,7 @@ struct two_fields {
   double d, e;
 };
 test(two_fields);
-// CHECK: define void @_Z7forward10two_fields(%struct.two_fields* noalias 
nocapture sret(%struct.two_fields) align 8 %{{.*}}, %struct.two_fields* 
nocapture readonly byval(%struct.two_fields) align 8 %{{.*}})
+// CHECK: define void @_Z7forward10two_fields(%struct.two_fields* noalias 
nocapture writeonly sret(%struct.two_fields) align 8 %{{.*}}, 
%struct.two_fields* nocapture readonly byval(%struct.two_fields) align 8 
%{{.*}})
 //
 // CHECK: define void @_Z15test_two_fieldsv()
 // CHECK: %[[tmp:.*]] = alloca %struct.two_fields, align 8

diff  --git a/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl 
b/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
index 17333cc80e14..350bb3c69366 100644
--- a/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
+++ b/clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
@@ -403,14 +403,14 @@ struct_arr16 func_ret_struct_arr16()
   return s;
 }
 
-// CHECK: define{{.*}} void @func_ret_struct_arr32(%struct.struct_arr32 
addrspace(5)* noalias nocapture sret(%struct.struct_arr32) align 4 %agg.result)
+// CHECK: define{{.*}} void @func_ret_struct_arr32(%struct.struct_arr32 
addrspace(5)* noalias nocapture writeonly sret(%struct.struct_arr32) align 4 
%agg.result)
 struct_arr32 func_ret_struct_arr32()
 {
   struct_arr32 s = { 0 };
   return s;
 }
 
-// CHECK: define{{.*}} void @func_ret_struct_arr33(%struct.struct_arr33 
addrspace(5)* noalias nocapture sret(%struct.struct_arr33) align 4 %agg.result)
+// CHECK: define{{.*}} void @func_ret_struct_arr33(%struct.struct_arr33 
addrspace(5)* noalias nocapture writeonly sret(%struct.struct_arr33) align 4 
%agg.result)
 struct_arr33 func_ret_struct_arr33()
 {
   struct_arr33 s = { 0 };
@@ -468,7 +468,7 @@ double_nested_struct func_double_nested_struct_ret(int4 
arg0, int arg1) {
 // CHECK: define{{.*}} void @func_large_struct_padding_arg_direct(i8 
%arg.coerce0, i32 %arg.coerce1, i8 %arg.coerce2, i32 %arg.coerce3, i8 
%arg.coerce4, i8 %arg.coerce5, i16 %arg.coerce6, i16 %arg.coerce7, [3 x i8] 
%arg.coerce8, i64 %arg.coerce9, i32 %arg.coerce10, i8 %arg.coerce11, i32 
%arg.coerce12, i16 %arg.coerce13, i8 %arg.coerce14)
 void func_large_struct_padding_arg_direct(large_struct_padding arg) { }
 
-// CHECK: define{{.*}} void 

[PATCH] D115003: [funcattrs] Infer writeonly argument attribute [part 2]

2022-01-04 Thread Philip Reames via Phabricator via cfe-commits
reames added inline comments.



Comment at: llvm/lib/Transforms/IPO/FunctionAttrs.cpp:728
+  } else if (CB.hasFnAttr(Attribute::WriteOnly) ||
+ CB.dataOperandHasImpliedAttr(UseIndex, Attribute::WriteOnly)) 
{
+IsWrite = true;

nikic wrote:
> This could be written as `CB.doesNotReadMemory() || 
> CB.doesNotReadMemory(UseIndex)` for symmetry with the other cases. Though 
> personally I find the naming of these methods really unfortunate (they should 
> probably be called `onlyWritesMemory()`) so maybe the explicit form is better.
I'm leaving this as is, but I agree we could use some naming cleanup here.  (I 
may even do it since this is the second time I've hit this.)

Though to highlight "does not read memory" and "WriteOnly" are not quite the 
same.  The former allows readnone which is correct, but surprising here.  
Personally, I hate subtle semantic surprises and am increasing of the view that 
we should check the attributes we mean.  (At least in inference code.)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115003/new/

https://reviews.llvm.org/D115003

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


Re: [clang] 229c95a - [CodeCompletion] Signature help for aggregate initialization.

2022-01-04 Thread Sam McCall via cfe-commits
On Tue, Jan 4, 2022 at 5:39 PM  wrote:

> This commit appears to add a file "tl" which I suspect wasn't intended?
> --paulr
>

Yes, I removed it in 10bb837feb22ad70dc4acc3d2cdb5be7f45d1c21.
(A command-line mistake compounded by a careless git commit --amend -a)

The filename also has a nonprintable character after "tl", which might
cause problems for some tools, though I hope not.

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


[PATCH] D116417: [clang][ObjC] Add fix it for missing methods in impl

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thanks, this looks good!




Comment at: clang/lib/Sema/SemaDeclObjC.cpp:2237
+// a better place to put it.
+std::string Str;
+llvm::raw_string_ostream Out(Str);

Str -> FixitStr

The comment is IMO too verbose, maybe just "// Add an empty definition at the 
end of @implementation".
(The future idea doesn't seem either specific or critical)



Comment at: clang/lib/Sema/SemaDeclObjC.cpp:2239
+llvm::raw_string_ostream Out(Str);
+PrintingPolicy Policy(Impl->getASTContext().getPrintingPolicy());
+method->print(Out, Policy);

No need to copy the policy, just refer to it directly?



Comment at: clang/lib/Sema/SemaDeclObjC.cpp:2241
+method->print(Out, Policy);
+Str.append(" {\n\n}\n\n");
+

nit: mixing string & output stream modifications is a bit confusing



Comment at: clang/lib/Sema/SemaDeclObjC.cpp:2241
+method->print(Out, Policy);
+Str.append(" {\n\n}\n\n");
+

sammccall wrote:
> nit: mixing string & output stream modifications is a bit confusing
I think this should probably only have one inside and one at the end.

Fixits aren't really in the business of formatting the code to be further 
modified.
I can't find examples of fixits inserting blank lines that aren't necessary, 
apart from at the end of decls.

One newline between empty braces seems to be LLVM's style for objc. (For C++ 
it's zero newlines)



Comment at: clang/test/FixIt/fixit-objc-missing-method-impl.m:1
+// RUN: cp %s %t
+// RUN: not %clang_cc1 -pedantic -Werror -fixit -x objective-c %t

Can you also include a -verify run to show the error being fixed? This seems to 
be common in other tests, and it makes it much easier to understand what's 
being tested.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116417/new/

https://reviews.llvm.org/D116417

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


[PATCH] D115798: Provide SmallAttrBuilder as a lightweight alternative to AttrBuilder

2022-01-04 Thread serge via Phabricator via cfe-commits
serge-sans-paille abandoned this revision.
serge-sans-paille added a comment.

Obsoleted by https://reviews.llvm.org/D116599


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115798/new/

https://reviews.llvm.org/D115798

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


[PATCH] D116283: [clang-format] Add an option to add a space between operator overloading and opening parentheses

2022-01-04 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGda6b0d0b768e: [clang-format] Add an option to add a space 
between operator overloading and… (authored by rajatbajpai, committed by 
curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D116283?vs=397112=397312#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116283/new/

https://reviews.llvm.org/D116283

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14536,6 +14536,24 @@
   // verifyFormat("X A::operator++ (T);", SomeSpace2);
   verifyFormat("int x = int (y);", SomeSpace2);
   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
+
+  FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
+  SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
+  .AfterOverloadedOperator = true;
+
+  verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
+  verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
+  verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
+  verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
+
+  SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
+  .AfterOverloadedOperator = false;
+
+  verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
+  verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
+  verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
+  verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
 }
 
 TEST_F(FormatTest, SpaceAfterLogicalNot) {
@@ -18771,6 +18789,15 @@
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
+  AfterFunctionDeclarationName);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
+  AfterFunctionDefinitionName);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
+  CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
 }
 
 #undef CHECK_PARSE_BOOL
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2923,9 +2923,15 @@
 }
 
 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken ) const {
-  return Style.SpaceBeforeParens == FormatStyle::SBPO_Always ||
- (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
-  Right.ParameterCount > 0);
+  if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
+return true;
+  if (Right.is(TT_OverloadedOperatorLParen) &&
+  Style.SpaceBeforeParensOptions.AfterOverloadedOperator)
+return true;
+  if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
+  Right.ParameterCount > 0)
+return true;
+  return false;
 }
 
 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine ,
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -868,6 +868,7 @@
 IO.mapOptional("AfterFunctionDeclarationName",
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
+IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
 IO.mapOptional("BeforeNonEmptyParentheses",
Spacing.BeforeNonEmptyParentheses);
   }
Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -3429,6 +3429,14 @@
 ///   
 /// \endcode
 bool AfterIfMacros;
+/// If ``true``, put a space between operator overloading and opening
+/// parentheses.
+/// \code
+///true:  false:
+///void operator++ (int a);vs.void operator++(int a);
+///object.operator++ (10);object.operator++(10);

[clang] da6b0d0 - [clang-format] Add an option to add a space between operator overloading and opening parentheses

2022-01-04 Thread Marek Kurdej via cfe-commits

Author: Rajat Bajpai
Date: 2022-01-04T17:23:23+01:00
New Revision: da6b0d0b768e3ecb1af2fd9df2d98510f7aff45c

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

LOG: [clang-format] Add an option to add a space between operator overloading 
and opening parentheses

This change adds an option AfterOverloadedOperator in SpaceBeforeParensOptions 
to add a space between overloaded operator and opening parentheses in 
clang-format.

Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4f3a9eb9f4a61..5a52916acc559 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3818,6 +3818,15 @@ the configuration (without a prefix: ``Auto``).
IF (...)vs.IF(...)
   
 
+  * ``bool AfterOverloadedOperator`` If ``true``, put a space between operator 
overloading and opening
+parentheses.
+
+.. code-block:: c++
+
+   true:  false:
+   void operator++ (int a);vs.void operator++(int a);
+   object.operator++ (10);object.operator++(10);
+
   * ``bool BeforeNonEmptyParentheses`` If ``true``, put a space before opening 
parentheses only if the
 parentheses are not empty.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2f48b1424d094..7e24d06567fc3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -311,6 +311,9 @@ clang-format
 
 - Improved C++20 Modules and Coroutines support.
 
+- Option ``AfterOverloadedOperator`` has been added in 
``SpaceBeforeParensOptions``
+  to allow space between overloaded operator and opening parentheses.
+
 libclang
 
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 24c245642e6ab..d3113a5fdba41 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3429,6 +3429,14 @@ struct FormatStyle {
 ///   
 /// \endcode
 bool AfterIfMacros;
+/// If ``true``, put a space between operator overloading and opening
+/// parentheses.
+/// \code
+///true:  false:
+///void operator++ (int a);vs.void operator++(int a);
+///object.operator++ (10);object.operator++(10);
+/// \endcode
+bool AfterOverloadedOperator;
 /// If ``true``, put a space before opening parentheses only if the
 /// parentheses are not empty.
 /// \code
@@ -3442,7 +3450,7 @@ struct FormatStyle {
 : AfterControlStatements(false), AfterForeachMacros(false),
   AfterFunctionDeclarationName(false),
   AfterFunctionDefinitionName(false), AfterIfMacros(false),
-  BeforeNonEmptyParentheses(false) {}
+  AfterOverloadedOperator(false), BeforeNonEmptyParentheses(false) {}
 
 bool operator==(const SpaceBeforeParensCustom ) const {
   return AfterControlStatements == Other.AfterControlStatements &&
@@ -3451,6 +3459,7 @@ struct FormatStyle {
  Other.AfterFunctionDeclarationName &&
  AfterFunctionDefinitionName == Other.AfterFunctionDefinitionName 
&&
  AfterIfMacros == Other.AfterIfMacros &&
+ AfterOverloadedOperator == Other.AfterOverloadedOperator &&
  BeforeNonEmptyParentheses == Other.BeforeNonEmptyParentheses;
 }
   };

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 11c190ebfba70..a4ce8a20a940b 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -868,6 +868,7 @@ template <> struct 
MappingTraits {
 IO.mapOptional("AfterFunctionDeclarationName",
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
+IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
 IO.mapOptional("BeforeNonEmptyParentheses",
Spacing.BeforeNonEmptyParentheses);
   }

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a161ee87e6b52..5b3a450e31f22 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2923,9 +2923,15 @@ unsigned TokenAnnotator::splitPenalty(const 
AnnotatedLine ,
 }
 
 

[PATCH] D116414: [AST] Produce ReturnStmt containing RecoveryExpr when type is wrong

2022-01-04 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sammccall marked 2 inline comments as done.
Closed by commit rG71059f26d313: [AST] Produce ReturnStmt containing 
RecoveryExpr when type is wrong (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D116414?vs=396680=397305#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116414/new/

https://reviews.llvm.org/D116414

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaStmt.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Index: clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
===
--- clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -74,3 +74,6 @@
 constexpr void test11() {
   for (X& e : array) {}
 }
+
+constexpr int test12() { return "wrong"; } // expected-error {{cannot initialize return object of type 'int'}}
+constexpr int force12 = test12();  // expected-error {{must be initialized by a constant}}
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -876,14 +876,12 @@
 namespace Lifetime {
   constexpr int (int &) { return r; }
   // cxx2b-error@-1 {{non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'}}
-  // cxx2b-error@-2 {{no return statement in constexpr function}} See PR40598
   constexpr int f() {
 int  = get(123);
 return r;
-// cxx2b-note@-1 {{use of reference outside its lifetime is not allowed in a constant expression}}
-// cxx14_20-note@-2 {{read of object outside its lifetime}}
+// cxx14_20-note@-1 {{read of object outside its lifetime}}
   }
-  static_assert(f() == 123, ""); // expected-error {{constant expression}} expected-note {{in call}}
+  static_assert(f() == 123, ""); // expected-error {{constant expression}} cxx14_20-note {{in call}}
 
   constexpr int g() {
 int *p = 0;
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1939,20 +1939,16 @@
 
   constexpr int (int &) { return n; }
   // cxx2b-error@-1 {{non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'}}
-  // cxx2b-error@-2 {{no return statement in constexpr function}} See PR40598
   constexpr int &_rv(int &) { return static_cast(n); }
   struct S {
 int &
 int 
 int t;
-constexpr S() : r(get_rv(0)), s(get(0)), t(r) {} // expected-note {{read of object outside its lifetime}}
-constexpr S(int) : r(get_rv(0)), s(get(0)), t(s) {}
-// cxx2b-warning@-1 {{reference 's' is not yet bound to a value when used here}}
-// cxx2b-note@-2{{read of uninitialized object is not allowed in a constant expression}}
-// cxx11_20-note@-3 {{read of object outside its lifetime}}
+constexpr S() : r(get_rv(0)), s(get(0)), t(r) {} // cxx11_20-note {{read of object outside its lifetime}}
+constexpr S(int) : r(get_rv(0)), s(get(0)), t(s) {} // cxx11_20-note {{read of object outside its lifetime}}
   };
-  constexpr int k1 = S().t; // expected-error {{constant expression}} expected-note {{in call}}
-  constexpr int k2 = S(0).t; // expected-error {{constant expression}} expected-note {{in call}}
+  constexpr int k1 = S().t; // expected-error {{constant expression}} cxx11_20-note {{in call}}
+  constexpr int k2 = S(0).t; // expected-error {{constant expression}} cxx11_20-note {{in call}}
 
   struct Q {
 int n = 0;
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -351,3 +351,43 @@
 // CHECK-NEXT: |   `-RecoveryExpr {{.*}} ''
   };
 }
+
+float *brokenReturn() {
+  // CHECK:  FunctionDecl {{.*}} brokenReturn
+  return 42;
+  // CHECK:  ReturnStmt
+  // CHECK-NEXT: `-RecoveryExpr {{.*}} 'float *'
+  // CHECK-NEXT:   `-IntegerLiteral {{.*}} 'int' 42
+}
+
+// Return deduction treats the first, second *and* third differently!
+auto *brokenDeducedReturn(int *x, float *y, double *z) {
+  // CHECK:  FunctionDecl {{.*}} invalid brokenDeducedReturn
+  if (x) return x;
+  // CHECK:  ReturnStmt
+  // CHECK-NEXT: `-ImplicitCastExpr {{.*}} 
+  // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'x' 'int *'
+  if (y) return y;
+  // CHECK:  ReturnStmt
+  // CHECK-NEXT: `-RecoveryExpr {{.*}} 'int *'
+  // CHECK-NEXT:   

[clang] 71059f2 - [AST] Produce ReturnStmt containing RecoveryExpr when type is wrong

2022-01-04 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-04T17:07:55+01:00
New Revision: 71059f26d31398d109be057e35bb8c5960d8aaf6

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

LOG: [AST] Produce ReturnStmt containing RecoveryExpr when type is wrong

Previously we just drop the ReturnStmt and its argument from the AST,
which blocks analysis of broken code.

Fixes https://github.com/llvm/llvm-project/issues/39944

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaStmt.cpp
clang/test/AST/ast-dump-recovery.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1b3944b35cb41..9521b24e44a79 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4861,7 +4861,8 @@ class Sema final {
 
   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  Scope *CurScope);
-  StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
+  StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
+ bool AllowRecovery = false);
   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  NamedReturnInfo ,
  bool SupressSimplerImplicitMoves);

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 1d90759f24069..d18f89d60d787 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3878,7 +3878,8 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr 
*RetValExp,
   RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true);
   if (RetVal.isInvalid())
 return StmtError();
-  StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
+  StmtResult R =
+  BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true);
   if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
 return R;
 
@@ -3908,7 +3909,8 @@ static bool CheckSimplerImplicitMovesMSVCWorkaround(const 
Sema ,
   return false;
 }
 
-StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
+StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
+ bool AllowRecovery) {
   // Check for unexpanded parameter packs.
   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
 return StmtError();
@@ -3985,11 +3987,25 @@ StmtResult Sema::BuildReturnStmt(SourceLocation 
ReturnLoc, Expr *RetValExp) {
   // If we've already decided this function is invalid, e.g. because
   // we saw a `return` whose expression had an error, don't keep
   // trying to deduce its return type.
-  if (FD->isInvalidDecl())
-return StmtError();
-  if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
+  // (Some return values may be needlessly wrapped in RecoveryExpr).
+  if (FD->isInvalidDecl() ||
+  DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
 FD->setInvalidDecl();
-return StmtError();
+if (!AllowRecovery)
+  return StmtError();
+// The deduction failure is diagnosed and marked, try to recover.
+if (RetValExp) {
+  // Wrap return value with a recovery expression of the previous type.
+  // If no deduction yet, use DependentTy.
+  auto Recovery = CreateRecoveryExpr(
+  RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp,
+  AT->isDeduced() ? FnRetType : QualType());
+  if (Recovery.isInvalid())
+return StmtError();
+  RetValExp = Recovery.get();
+} else {
+  // Nothing to do: a ReturnStmt with no value is fine recovery.
+}
   } else {
 FnRetType = FD->getReturnType();
   }
@@ -4002,7 +4018,7 @@ StmtResult Sema::BuildReturnStmt(SourceLocation 
ReturnLoc, Expr *RetValExp) {
   ReturnStmt *Result = nullptr;
   if (FnRetType->isVoidType()) {
 if (RetValExp) {
-  if (isa(RetValExp)) {
+  if (auto *ILE = dyn_cast(RetValExp)) {
 // We simply never allow init lists as the return value of void
 // functions. This is compatible because this was never allowed before,
 // so there's no legacy code to deal with.
@@ -4018,8 +4034,12 @@ StmtResult Sema::BuildReturnStmt(SourceLocation 
ReturnLoc, Expr *RetValExp) {
 Diag(ReturnLoc, diag::err_return_init_list)
 << CurDecl << FunctionKind << RetValExp->getSourceRange();
 
-// 

[PATCH] D116488: Add a misc-unused-parameters.CommentOutUnusedParameters to clang-tidy

2022-01-04 Thread Jacques Pienaar via Phabricator via cfe-commits
jpienaar accepted this revision.
jpienaar added a comment.
This revision is now accepted and ready to land.

Looks reasonable as an option/this is another way to make it explicit that 
param is unused.




Comment at: 
clang-tools-extra/docs/clang-tidy/checks/misc-unused-parameters.rst:48
+
+.. option:: misc-unused-parameters.CommentOutUnusedParameters
+

Could we flip this? ElideUnusedParameterNames with default value false: eliding 
drops local information and I'd rather that be explicit in the name. CommentOut 
is still the default with the current naming, but it feels more optional for 
some reason to me. WDYT?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116488/new/

https://reviews.llvm.org/D116488

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


[PATCH] D115670: Implement some constexpr vector unary operators, fix boolean-ops

2022-01-04 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Hi!
Sorry for the delay, I just got back from my christmas break.  I'll take a look 
later today/this week.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D115670/new/

https://reviews.llvm.org/D115670

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


[PATCH] D116599: Simplify AttrBuilder storage for target dependent attributes

2022-01-04 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

I'm generally on board with this change. After D116110 
, the `AttrBuilder` is only used in 
situations where we actually expect all the added attributes to be converted to 
`Attribute`s in any case, so we don't lose anything by storing them directly in 
that form. At the same time, we don't need to do expensive conversions from 
`Attribute` to internal `AttrBuilder` representation and back to `Attribute` 
(involving FoldingSet lookups) when `AttrBuilder` is constructed from an 
existing `AttributeList`/`AttributeSet`. This is common, because the general 
approach to attribute modification is "dump everything into AttrBuilder, add 
new attributes, convert back to AttributeSet".

The main externality here is that AttrBuilder now requires an LLVMContext, but 
it doesn't look like obtaining one is a problem for any existing usage. I do 
think it would be good to land the `LLVMContext` constructor argument addition 
in a separate patch from the internal representation change, as that one is 
essentially just busywork.

I've left some implementation nits...




Comment at: llvm/include/llvm/IR/Attributes.h:1006
+}
+  };
+

Don't think this needs to be in the header.



Comment at: llvm/include/llvm/IR/Attributes.h:1008
+
+  LLVMContext& Ctx;
   std::bitset Attrs;

`LLVMContext ` here and elsewhere.



Comment at: llvm/lib/AsmParser/LLParser.cpp:1242
   parseToken(lltok::lbrace, "expected '{' here") ||
-  parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
+  parseFnAttributeValuePairs(NumberedAttrBuilders.emplace(VarID, 
AttrBuilder(M->getContext())).first->second, unused, true,
  BuiltinLoc) ||

I'd split the if here and store the AttrBuilder in a variable and then reuse 
below. Getting a bit hard to read.



Comment at: llvm/lib/IR/Attributes.cpp:1612
+  return addAttribute(Attribute::get(Ctx, A, V));
+}
+

This method move looks a bit weird, I'd leave it where it was so we don't mix 
add/remove.



Comment at: llvm/lib/IR/Attributes.cpp:1761
 
+  // TODO: Inefficient...
   for (const auto  : B.td_attrs())

Could be more specific here, e.g. `TODO: Could merge both lists in one loop`.



Comment at: llvm/lib/IR/Attributes.cpp:1769
 AttrBuilder ::remove(const AttributeMask ) {
   // FIXME: What if both have an int/type attribute, but they don't match?!
   for (unsigned Index = 0; Index < Attribute::NumIntAttrKinds; ++Index)

Unrelated to this change, but with AttributeMask this FIXME no longer makes 
sense.



Comment at: llvm/lib/IR/Attributes.cpp:1833
+  return IntAttrs == B.IntAttrs && TypeAttrs == B.TypeAttrs &&
+ TargetDepAttrs == B.TargetDepAttrs;
 }

I'd combine the `Attrs == B.Attrs` check into this return as well, so it 
doesn't feel lonely :)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116599/new/

https://reviews.llvm.org/D116599

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


[PATCH] D111457: [clang][test] Add lit helper for windows paths

2022-01-04 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd requested changes to this revision.
compnerd added inline comments.
This revision now requires changes to proceed.



Comment at: clang/test/lit.cfg.py:60
+if platform.system() == 'Windows':
+root_sep = 'C:\\'
+else:

This isn't really a separator, this is the root itself.  I think that it makes 
sense to name it accordingly.  Please do not hard code this to `C:\`.  There is 
no guarantee that the root is `C:\`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D111457/new/

https://reviews.llvm.org/D111457

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


[PATCH] D116599: Simplify AttrBuilder storage for target dependent attributes

2022-01-04 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 397298.
serge-sans-paille added a comment.

upload correct patch version


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116599/new/

https://reviews.llvm.org/D116599

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  llvm/include/llvm/CodeGen/IndirectThunks.h
  llvm/include/llvm/IR/Attributes.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/CodeGen/Analysis.cpp
  llvm/lib/CodeGen/CommandFlags.cpp
  llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
  llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
  llvm/lib/Transforms/Coroutines/CoroSplit.cpp
  llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
  llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
  llvm/tools/bugpoint/CrashDebugger.cpp
  llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp
  llvm/unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
  llvm/unittests/IR/AttributesTest.cpp
  llvm/unittests/IR/InstructionsTest.cpp
  mlir/lib/Target/LLVMIR/ModuleTranslation.cpp

Index: mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -746,7 +746,7 @@
 return func.emitError(
 "llvm.align attribute attached to LLVM non-pointer argument");
   llvmArg.addAttrs(
-  llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt(;
+  llvm::AttrBuilder(llvmArg.getContext()).addAlignmentAttr(llvm::Align(attr.getInt(;
 }
 
 if (auto attr = func.getArgAttrOfType(argIdx, "llvm.sret")) {
@@ -754,7 +754,7 @@
   if (!argTy.isa())
 return func.emitError(
 "llvm.sret attribute attached to LLVM non-pointer argument");
-  llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
+  llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addStructRetAttr(
   llvmArg.getType()->getPointerElementType()));
 }
 
@@ -763,7 +763,7 @@
   if (!argTy.isa())
 return func.emitError(
 "llvm.byval attribute attached to LLVM non-pointer argument");
-  llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
+  llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addByValAttr(
   llvmArg.getType()->getPointerElementType()));
 }
 
Index: llvm/unittests/IR/InstructionsTest.cpp
===
--- llvm/unittests/IR/InstructionsTest.cpp
+++ llvm/unittests/IR/InstructionsTest.cpp
@@ -614,7 +614,7 @@
 
   // Test cloning an attribute.
   {
-AttrBuilder AB;
+AttrBuilder AB(C);
 AB.addAttribute(Attribute::ReadOnly);
 Call->setAttributes(
 AttributeList::get(C, AttributeList::FunctionIndex, AB));
@@ -633,7 +633,7 @@
   std::unique_ptr Call(
   CallInst::Create(FnTy, Callee, Args, OldBundle, "result"));
   Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
-  AttrBuilder AB;
+  AttrBuilder AB(C);
   AB.addAttribute(Attribute::Cold);
   Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
   Call->setDebugLoc(DebugLoc(MDNode::get(C, None)));
@@ -662,7 +662,7 @@
   std::unique_ptr Invoke(
   InvokeInst::Create(FnTy, Callee, NormalDest.get(), UnwindDest.get(), Args,
  OldBundle, "result"));
-  AttrBuilder AB;
+  AttrBuilder AB(C);
   AB.addAttribute(Attribute::Cold);
   Invoke->setAttributes(
   AttributeList::get(C, AttributeList::FunctionIndex, AB));
Index: llvm/unittests/IR/AttributesTest.cpp
===
--- llvm/unittests/IR/AttributesTest.cpp
+++ llvm/unittests/IR/AttributesTest.cpp
@@ -62,9 +62,9 @@
 TEST(Attributes, AddAttributes) {
   LLVMContext C;
   AttributeList AL;
-  AttrBuilder B;
+  AttrBuilder B(C);
   B.addAttribute(Attribute::NoReturn);
-  AL = AL.addFnAttributes(C, AttributeSet::get(C, B));
+  AL = AL.addFnAttributes(C, AttrBuilder(C, AttributeSet::get(C, B)));
   EXPECT_TRUE(AL.hasFnAttr(Attribute::NoReturn));
   B.clear();
   B.addAttribute(Attribute::SExt);
@@ -78,12 +78,12 @@
 
   Attribute AlignAttr = Attribute::getWithAlignment(C, Align(8));
   Attribute StackAlignAttr = Attribute::getWithStackAlignment(C, Align(32));
-  AttrBuilder B_align_readonly;
+  AttrBuilder B_align_readonly(C);
   B_align_readonly.addAttribute(AlignAttr);
   

[PATCH] D116599: Simplify AttrBuilder storage for target dependent attributes

2022-01-04 Thread serge via Phabricator via cfe-commits
serge-sans-paille created this revision.
serge-sans-paille added reviewers: nikic, rnk, dexonsmith.
Herald added subscribers: sdasgup3, wenzhicui, wrengr, Chia-hungDuan, ormris, 
dcaballe, cota, teijeong, rdzhabarov, tatianashp, jdoerfert, msifontes, 
jurahul, Kayjukh, grosul1, Joonsoo, liufengdb, aartbik, lucyrfox, mgester, 
arpith-jacob, antiagainst, shauheen, rriddle, mehdi_amini, hiraditya, 
jgravelle-google, sbc100, dschuff.
Herald added a reviewer: ftynse.
serge-sans-paille requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, stephenneuendorffer, 
nicolasvasilache, aheejin.
Herald added projects: clang, MLIR, LLVM.

Using and `std::map` for target dependent attributes 
is inefficient: it makes its constructor slightly heavier, and involves extra 
allocation for each new string attribute. Storing the attribute key/value as 
strings implies extra allocation/copy step.

Use a sorted vector instead. Given the low number of attributes generally 
involved, this is cheaper, as showcased by 
https://llvm-compile-time-tracker.com/compare.php?from=5de322295f4ade692dc4f1823ae4450ad3c48af2=05bc480bf641a9e3b466619af43a2d123ee3f71d=instructions


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116599

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  llvm/include/llvm/CodeGen/IndirectThunks.h
  llvm/include/llvm/IR/Attributes.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/CodeGen/Analysis.cpp
  llvm/lib/CodeGen/CommandFlags.cpp
  llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
  llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
  llvm/lib/Transforms/Coroutines/CoroSplit.cpp
  llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
  llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
  llvm/tools/bugpoint/CrashDebugger.cpp
  llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp
  llvm/unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
  llvm/unittests/IR/AttributesTest.cpp
  llvm/unittests/IR/InstructionsTest.cpp
  mlir/lib/Target/LLVMIR/ModuleTranslation.cpp

Index: mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -746,7 +746,7 @@
 return func.emitError(
 "llvm.align attribute attached to LLVM non-pointer argument");
   llvmArg.addAttrs(
-  llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt(;
+  llvm::AttrBuilder(llvmArg.getContext()).addAlignmentAttr(llvm::Align(attr.getInt(;
 }
 
 if (auto attr = func.getArgAttrOfType(argIdx, "llvm.sret")) {
@@ -754,7 +754,7 @@
   if (!argTy.isa())
 return func.emitError(
 "llvm.sret attribute attached to LLVM non-pointer argument");
-  llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
+  llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addStructRetAttr(
   llvmArg.getType()->getPointerElementType()));
 }
 
@@ -763,7 +763,7 @@
   if (!argTy.isa())
 return func.emitError(
 "llvm.byval attribute attached to LLVM non-pointer argument");
-  llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
+  llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addByValAttr(
   llvmArg.getType()->getPointerElementType()));
 }
 
Index: llvm/unittests/IR/InstructionsTest.cpp
===
--- llvm/unittests/IR/InstructionsTest.cpp
+++ llvm/unittests/IR/InstructionsTest.cpp
@@ -614,7 +614,7 @@
 
   // Test cloning an attribute.
   {
-AttrBuilder AB;
+AttrBuilder AB(C);
 AB.addAttribute(Attribute::ReadOnly);
 Call->setAttributes(
 AttributeList::get(C, AttributeList::FunctionIndex, AB));
@@ -633,7 +633,7 @@
   std::unique_ptr Call(
   CallInst::Create(FnTy, Callee, Args, OldBundle, "result"));
   Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
-  AttrBuilder AB;
+  AttrBuilder AB(C);
   AB.addAttribute(Attribute::Cold);
   Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
   Call->setDebugLoc(DebugLoc(MDNode::get(C, None)));
@@ -662,7 +662,7 @@
   std::unique_ptr Invoke(
   InvokeInst::Create(FnTy, Callee, NormalDest.get(), UnwindDest.get(), Args,
  OldBundle, "result"));
-  AttrBuilder AB;
+  

[PATCH] D116216: Prevent adding module flag - amdgpu_hostcall multiple times.

2022-01-04 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D116216#3209335 , @pvellien wrote:

> @yaxunl It would be very much helpful to know how to write test coverage for 
> this particular patch? thanks

there is a lit test amdgpu-asan.cu. You can add a call of print to that test 
and make sure it compiles.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116216/new/

https://reviews.llvm.org/D116216

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


[PATCH] D116577: [clang-tidy] Added "boost-use-range-based-for-loop" check

2022-01-04 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.cpp:60
+
+auto Loc = MacroNameToken.getLocation();
+auto Diag = Check->diag(Loc, "use range-based for loop instead of %0")

Please specify type explicitly here.



Comment at: clang-tools-extra/clang-tidy/boost/UseRangeBasedForLoopCheck.h:22
+/// 
http://clang.llvm.org/extra/clang-tidy/checks/boost-use-range-based-for-loop.html
+class UseRangeBasedForLoopCheck : public ClangTidyCheck {
+public:

Please add `isLanguageVersionSupported`.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/boost-use-range-based-for-loop.rst:6
+
+This check converts ``BOOST_FOREACH(..., ...)`` loops to use the new 
range-based loops in C++11.
+

Please synchronize this statement with statement in Release Notes.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/boost-use-range-based-for-loop.rst:21
+
+// Will be changed to
+std::list list_int( /*...*/ );

It will be good idea to move it to separate code block and add something like 
`from` and `to`. See `modernize` checks as example. Same for other examples.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/boost-use-range-based-for-loop.rst:30
+-
+* Client code that use ``BOOST_FOREACH`` with "``std::pair`` of iterators" or 
with "Null-terminated strings (``char`` and ``wchar_t``)" or some other 
sequence types (everything that is not declared in the list "convertible 
correctly" above) will produce broken code (compilation error).
+

Please separate with newline and follow 80 character limit. Also closing quote 
for `Null-terminated strings` is missing.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116577/new/

https://reviews.llvm.org/D116577

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


[PATCH] D116415: [Arm] Remove duplicate CPU tests

2022-01-04 Thread Tomas Matheson via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8aea5d5951dc: [Arm] Remove duplicate CPU tests (authored by 
tmatheson).

Changed prior to commit:
  https://reviews.llvm.org/D116415?vs=396681=397297#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116415/new/

https://reviews.llvm.org/D116415

Files:
  clang/test/Driver/arm-cortex-cpus.c

Index: clang/test/Driver/arm-cortex-cpus.c
===
--- clang/test/Driver/arm-cortex-cpus.c
+++ clang/test/Driver/arm-cortex-cpus.c
@@ -28,7 +28,6 @@
 // RUN: %clang -target armv5 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V5-THUMB %s
 // RUN: %clang -target arm -march=armv5 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V5-THUMB %s
 // RUN: %clang -target armv5t -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V5-THUMB %s
-// RUN: %clang -target arm -march=armv5 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V5-THUMB %s
 // CHECK-V5-THUMB: "-cc1"{{.*}} "-triple" "thumbv5-{{.*}} "-target-cpu" "arm10tdmi"
 
 // RUN: %clang -target armv5e -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V5E %s
@@ -143,7 +142,7 @@
 // RUN: %clang -target arm -march=armv8 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A %s
 // RUN: %clang -target armv8a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A %s
 // RUN: %clang -target arm -march=armv8a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A %s
-// RUN: %clang -target arm -mlittle-endian -march=armv8-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A %s
+// RUN: %clang -target arm -march=armv8-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A %s
 // CHECK-V8A: "-cc1"{{.*}} "-triple" "armv8-{{.*}}" "-target-cpu" "generic"
 
 // RUN: %clang -target armv8r-linux-gnueabi -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8R %s
@@ -176,7 +175,7 @@
 // RUN: %clang -mcpu=generic -target arm -march=armv8 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
 // RUN: %clang -mcpu=generic -target armv8a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
-// RUN: %clang -mcpu=generic -target arm -mlittle-endian -march=armv8-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
+// RUN: %clang -mcpu=generic -target arm -march=armv8-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
 // CHECK-V8A-GENERIC: "-cc1"{{.*}} "-triple" "armv8-{{.*}}" "-target-cpu" "generic"
 
 // RUN: %clang -target armebv8 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V8A %s
@@ -214,17 +213,15 @@
 // RUN: %clang -target arm -march=armv8.1a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -target armv8.1a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -target arm -march=armv8.1-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
-// RUN: %clang -target arm -march=armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -target armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -target arm -march=armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
-// RUN: %clang -target arm -mlittle-endian -march=armv8.1-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
+// RUN: %clang -target arm -march=armv8.1-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8.1a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target armv8.1a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8.1-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
-// RUN: %clang -mcpu=generic -target arm -march=armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
-// RUN: %clang -mcpu=generic -target arm -mlittle-endian -march=armv8.1-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
+// RUN: %clang -mcpu=generic -target arm -march=armv8.1-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // CHECK-V81A: "-cc1"{{.*}} "-triple" "armv8.1a-{{.*}}" "-target-cpu" "generic"
 
 // RUN: %clang -target armebv8.1a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V81A 

[clang] 8aea5d5 - [Arm] Remove duplicate CPU tests

2022-01-04 Thread Tomas Matheson via cfe-commits

Author: Tomas Matheson
Date: 2022-01-04T15:22:10Z
New Revision: 8aea5d5951dc7d2130ad671423830a45e215c540

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

LOG: [Arm] Remove duplicate CPU tests

There are some duplicate test lines in clang/test/Driver/arm-cortex-cpus.c.
Looks like these were duplicated from the corresponding v8.0a tests, which test
both "-target armv8" and "-target armv8a". "-target armv8.X" without the "a"
doesn't work for later versions though.

Several tests also specify the -mlittle-endian twice, which looks unintentional.

Remove duplicate test: -target arm -march=armv5 -mthumb

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

Added: 


Modified: 
clang/test/Driver/arm-cortex-cpus.c

Removed: 




diff  --git a/clang/test/Driver/arm-cortex-cpus.c 
b/clang/test/Driver/arm-cortex-cpus.c
index 7b7a4b355dcc2..f1d2c569ab69f 100644
--- a/clang/test/Driver/arm-cortex-cpus.c
+++ b/clang/test/Driver/arm-cortex-cpus.c
@@ -28,7 +28,6 @@
 // RUN: %clang -target armv5 -mthumb -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V5-THUMB %s
 // RUN: %clang -target arm -march=armv5 -mthumb -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V5-THUMB %s
 // RUN: %clang -target armv5t -mthumb -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V5-THUMB %s
-// RUN: %clang -target arm -march=armv5 -mthumb -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V5-THUMB %s
 // CHECK-V5-THUMB: "-cc1"{{.*}} "-triple" "thumbv5-{{.*}} "-target-cpu" 
"arm10tdmi"
 
 // RUN: %clang -target armv5e -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V5E %s
@@ -143,7 +142,7 @@
 // RUN: %clang -target arm -march=armv8 -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A %s
 // RUN: %clang -target armv8a -mlittle-endian -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8A %s
 // RUN: %clang -target arm -march=armv8a -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A %s
-// RUN: %clang -target arm -mlittle-endian -march=armv8-a -mlittle-endian -### 
-c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A %s
+// RUN: %clang -target arm -march=armv8-a -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A %s
 // CHECK-V8A: "-cc1"{{.*}} "-triple" "armv8-{{.*}}" "-target-cpu" "generic"
 
 // RUN: %clang -target armv8r-linux-gnueabi -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
@@ -176,7 +175,7 @@
 // RUN: %clang -mcpu=generic -target arm -march=armv8 -mlittle-endian -### -c 
%s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
 // RUN: %clang -mcpu=generic -target armv8a -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A-GENERIC %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8a -mlittle-endian -### -c 
%s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
-// RUN: %clang -mcpu=generic -target arm -mlittle-endian -march=armv8-a 
-mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
+// RUN: %clang -mcpu=generic -target arm -march=armv8-a -mlittle-endian -### 
-c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-GENERIC %s
 // CHECK-V8A-GENERIC: "-cc1"{{.*}} "-triple" "armv8-{{.*}}" "-target-cpu" 
"generic"
 
 // RUN: %clang -target armebv8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-BE-V8A %s
@@ -214,17 +213,15 @@
 // RUN: %clang -target arm -march=armv8.1a -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V81A %s
 // RUN: %clang -target armv8.1a -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V81A %s
 // RUN: %clang -target arm -march=armv8.1-a -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V81A %s
-// RUN: %clang -target arm -march=armv8.1a -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -target armv8.1a -mlittle-endian -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V81A %s
 // RUN: %clang -target arm -march=armv8.1a -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V81A %s
-// RUN: %clang -target arm -mlittle-endian -march=armv8.1-a -mlittle-endian 
-### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
+// RUN: %clang -target arm -march=armv8.1-a -mlittle-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8.1a -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target armv8.1a -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8.1-a -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V81A %s
-// RUN: %clang -mcpu=generic -target arm -march=armv8.1a -mlittle-endian -### 
-c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target armv8.1a -mlittle-endian -### -c %s 2>&1 
| FileCheck -check-prefix=CHECK-V81A %s
 // RUN: %clang -mcpu=generic -target arm 

[PATCH] D102669: [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space characters in lookup names when parsing the ctu index file

2022-01-04 Thread Ella Ma via Phabricator via cfe-commits
OikawaKirie updated this revision to Diff 397289.
OikawaKirie added a comment.

Replace on-demand-parsing with loading AST file for the new test case.
Tested on Linux and MacOS(x86).
If it can also pass the CI test on Windows, I think we can have another try on 
landing this patch.

Besides, as mentioned above, to trigger the problem of target triple on MacOS, 
we can simply remove the requirement of Linux system for the two test cases of 
on-demand-parsing, i.e. `clang/test/Analysis/ctu-on-demand-parsing.c` and 
`clang/test/Analysis/ctu-on-demand-parsing.cpp`.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D102669/new/

https://reviews.llvm.org/D102669

Files:
  clang/docs/analyzer/user-docs/CrossTranslationUnit.rst
  clang/include/clang/Basic/DiagnosticCrossTUKinds.td
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-lookup-name-with-space.cpp
  clang/test/Analysis/Inputs/ctu-other.c.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.ast-dump.txt
  
clang/test/Analysis/Inputs/plist-macros-with-expansion-ctu.c.externalDefMap.txt
  clang/test/Analysis/ctu-inherited-default-ctor.cpp
  clang/test/Analysis/ctu-lookup-name-with-space.cpp
  clang/test/Analysis/func-mapping-test.cpp
  clang/unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -61,7 +61,7 @@
 ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("index", "txt", IndexFD,
 IndexFileName));
 llvm::ToolOutputFile IndexFile(IndexFileName, IndexFD);
-IndexFile.os() << "c:@F@f#I# " << ASTFileName << "\n";
+IndexFile.os() << "9:c:@F@f#I# " << ASTFileName << "\n";
 IndexFile.os().flush();
 EXPECT_TRUE(llvm::sys::fs::exists(IndexFileName));
 
Index: clang/test/Analysis/func-mapping-test.cpp
===
--- clang/test/Analysis/func-mapping-test.cpp
+++ clang/test/Analysis/func-mapping-test.cpp
@@ -3,10 +3,10 @@
 int f(int) {
   return 0;
 }
-// CHECK-DAG: c:@F@f#I#
+// CHECK-DAG: 9:c:@F@f#I#
 
 extern const int x = 5;
-// CHECK-DAG: c:@x
+// CHECK-DAG: 4:c:@x
 
 // Non-const variables should not be collected.
 int y = 5;
@@ -18,29 +18,29 @@
   int a;
 };
 extern S const s = {.a = 2};
-// CHECK-DAG: c:@s
+// CHECK-DAG: 4:c:@s
 
 struct SF {
   const int a;
 };
 SF sf = {.a = 2};
-// CHECK-DAG: c:@sf
+// CHECK-DAG: 5:c:@sf
 
 struct SStatic {
   static const int a = 4;
 };
 const int SStatic::a;
-// CHECK-DAG: c:@S@SStatic@a
+// CHECK-DAG: 14:c:@S@SStatic@a
 
 extern int const arr[5] = { 0, 1 };
-// CHECK-DAG: c:@arr
+// CHECK-DAG: 6:c:@arr
 
 union U {
   const int a;
   const unsigned int b;
 };
 U u = {.a = 6};
-// CHECK-DAG: c:@u
+// CHECK-DAG: 4:c:@u
 
 // No USR can be generated for this.
 // Check for no crash in this case.
@@ -48,3 +48,15 @@
   float uf;
   const int ui;
 };
+
+void f(int (*)(char));
+void f(bool (*)(char));
+
+struct G {
+  G() {
+f([](char) -> int { return 42; });
+// CHECK-DAG: 41:c:@S@G@F@G#@Sa@F@operator int (*)(char)#1
+f([](char) -> bool { return true; });
+// CHECK-DAG: 42:c:@S@G@F@G#@Sa@F@operator bool (*)(char)#1
+  }
+};
Index: clang/test/Analysis/ctu-lookup-name-with-space.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-lookup-name-with-space.cpp
@@ -0,0 +1,22 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+
+// RUN: %clang_extdef_map %S/Inputs/ctu-lookup-name-with-space.cpp -- | \
+// RUN:   sed 's:%/S/Inputs/ctu-lookup-name-with-space.cpp:%/t/importee.ast:g' > %t/externalDefMap.txt
+
+// RUN: cd %t
+// RUN: %clang_cc1 -emit-pch %/S/Inputs/ctu-lookup-name-with-space.cpp -o %t/importee.ast
+// RUN: %clang_cc1 -fsyntax-only -analyze \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=. \
+// RUN:   -verify %s
+
+void importee();
+
+void trigger() {
+  // Call an external function to trigger the parsing process of CTU index.
+  // Refer to file Inputs/ctu-lookup-name-with-space.cpp for more details.
+
+  importee(); // expected-no-diagnostics
+}
Index: clang/test/Analysis/ctu-inherited-default-ctor.cpp
===
--- clang/test/Analysis/ctu-inherited-default-ctor.cpp
+++ clang/test/Analysis/ctu-inherited-default-ctor.cpp
@@ -4,7 +4,7 @@
 // RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
 // RUN:   -emit-pch -o %t/ctudir/ctu-inherited-default-ctor-other.cpp.ast \
 // RUN:%S/Inputs/ctu-inherited-default-ctor-other.cpp
-// RUN: echo "c:@N@clang@S@DeclContextLookupResult@SingleElementDummyList 

  1   2   >