[PATCH] D103750: [analyzer] Handle std::make_unique for SmartPtrModeling

2021-06-11 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 351628.
RedDocMD added a comment.

Fixed up technique used to find inner pointer type, put TODO's


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103750

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/smart-ptr-text-output.cpp

Index: clang/test/Analysis/smart-ptr-text-output.cpp
===
--- clang/test/Analysis/smart-ptr-text-output.cpp
+++ clang/test/Analysis/smart-ptr-text-output.cpp
@@ -1,3 +1,8 @@
+// RUN: %clang_analyze_cc1\
+// RUN:  -analyzer-checker=core,cplusplus.Move,alpha.cplusplus.SmartPtr\
+// RUN:  -analyzer-config cplusplus.SmartPtrModeling:ModelSmartPtrDereference=true\
+// RUN:  -analyzer-output=text -std=c++20 %s -verify=expected
+
 // RUN: %clang_analyze_cc1\
 // RUN:  -analyzer-checker=core,cplusplus.Move,alpha.cplusplus.SmartPtr\
 // RUN:  -analyzer-config cplusplus.SmartPtrModeling:ModelSmartPtrDereference=true\
@@ -313,3 +318,27 @@
 // expected-note@-1{{Dereference of null smart pointer 'P'}}
   }
 }
+
+void makeUniqueReturnsNonNullUniquePtr() {
+  auto P = std::make_unique();
+  if (!P) {   // expected-note {{Taking false branch}}
+P->foo(); // should have no warning here, path is impossible
+  }
+  P.reset(); // expected-note {{Smart pointer 'P' reset using a null value}}
+  // Now P is null
+  if (!P) {
+// expected-note@-1 {{Taking true branch}}
+P->foo(); // expected-warning {{Dereference of null smart pointer 'P' [alpha.cplusplus.SmartPtr]}}
+// expected-note@-1{{Dereference of null smart pointer 'P'}}
+  }
+}
+
+#if __cplusplus >= 202002L
+
+void makeUniqueForOverwriteReturnsNullUniquePtr() {
+  auto P = std::make_unique_for_overwrite(); // expected-note {{std::unique_ptr 'P' constructed by std::make_unique_for_overwrite is null}}
+  *P;   // expected-warning {{Dereference of null smart pointer 'P' [alpha.cplusplus.SmartPtr]}}
+  // expected-note@-1{{Dereference of null smart pointer 'P'}}
+}
+
+#endif
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -978,6 +978,17 @@
 void swap(unique_ptr , unique_ptr ) noexcept {
   x.swap(y);
 }
+
+template 
+unique_ptr make_unique(Args &&...args);
+
+#if __cplusplus >= 202002L
+
+template 
+unique_ptr make_unique_for_overwrite();
+
+#endif
+
 } // namespace std
 #endif
 
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -35,6 +35,7 @@
 using namespace ento;
 
 namespace {
+
 class SmartPtrModeling
 : public Checker {
@@ -76,6 +77,9 @@
   {{"release"}, ::handleRelease},
   {{"swap", 1}, ::handleSwap},
   {{"get"}, ::handleGet}};
+  const CallDescription StdMakeUniqueCall{{"std", "make_unique"}};
+  const CallDescription StdMakeUniqueForOverwriteCall{
+  {"std", "make_unique_for_overwrite"}};
 };
 } // end of anonymous namespace
 
@@ -135,6 +139,21 @@
   return State;
 }
 
+// This is for use with standalone-functions like std::make_unique,
+// std::make_unique_for_overwrite, etc. It reads the template parameter and
+// returns the pointer type corresponding to it,
+static QualType getPointerTypeFromTemplateArg(const CallEvent ,
+  CheckerContext ) {
+  const auto *FD = dyn_cast_or_null(Call.getDecl());
+  if (!FD || !FD->isFunctionTemplateSpecialization())
+return {};
+  const auto  = FD->getTemplateSpecializationArgs()->asArray();
+  if (TemplateArgs.size() == 0)
+return {};
+  auto ValueType = TemplateArgs[0].getAsType();
+  return C.getASTContext().getPointerType(ValueType.getCanonicalType());
+}
+
 // Helper method to get the inner pointer type of specialized smart pointer
 // Returns empty type if not found valid inner pointer type.
 static QualType getInnerPointerType(const CallEvent , CheckerContext ) {
@@ -177,7 +196,60 @@
 
 bool SmartPtrModeling::evalCall(const CallEvent ,
 CheckerContext ) const {
+
   ProgramStateRef State = C.getState();
+
+  if (Call.isCalled(StdMakeUniqueCall)) {
+const Optional ThisRegionOpt = Call.getReturnValueUnderConstruction();
+if (!ThisRegionOpt)
+  return false;
+
+const auto PtrVal = C.getSValBuilder().conjureSymbolVal(
+Call.getOriginExpr(), C.getLocationContext(),
+getPointerTypeFromTemplateArg(Call, C), C.blockCount());
+
+const MemRegion *ThisRegion = ThisRegionOpt->getAsRegion();
+State = State->set(ThisRegion, 

[PATCH] D98618: [clang-tidy] Add --skip-headers, part 1 (with TopLevelDecl bit)

2021-06-11 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
chh added a comment.

Please review https://reviews.llvm.org/D98710, which uses get/setTraversalScope 
instead of adding a TopLevelDecl bit.


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

https://reviews.llvm.org/D98618

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


[PATCH] D104155: Add documentation for -fsanitize-address-use-after-return.

2021-06-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/docs/AddressSanitizer.rst:17
 * Use-after-free
-* Use-after-return (runtime flag 
`ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* Use-after-return (clang flag 
`-fsanitize-address-use-after-return=(always|runtime|never)` default: runtime)
+  * Add runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1` to enable 
when compiled with `-fsanitize-address-use-after-return=runtime`)

rst uses two backsticks instead of one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104155

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


[PATCH] D98709: [clang-tidy] Add --skip-headers, part 1

2021-06-11 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
chh updated this revision to Diff 351617.
chh retitled this revision from "clang-tidy skip-headers; Alt#1; fewer changes" 
to "[clang-tidy] Add --skip-headers, part 1".
chh edited the summary of this revision.
chh added a comment.
Herald added subscribers: cfe-commits, xazax.hun.

sync with latest clang/llvm


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

https://reviews.llvm.org/D98709

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-tidy/checkers/Inputs/skip-headers/my_header1.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/skip-headers/my_header2.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-forward-declaration-namespace.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-include.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-interfaces-global-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-namespaces.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-objc-function-naming.m
  clang-tools-extra/test/clang-tidy/checkers/llvm-include-order.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvm-prefer-register-over-unsigned.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvmlibc-implementation-in-namespace.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvmlibc-restrict-system-libc-headers.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-no-recursion.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-cxx03.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-cxx11.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value-header.cpp
  
clang-tools-extra/test/clang-tidy/checkers/portability-restrict-system-includes-allow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/portability-restrict-system-includes-disallow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-chained-conditional-assignment.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-chained-conditional-return.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-members.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/test/clang-tidy/checkers/skip-headers.cpp
  clang/include/clang/ASTMatchers/ASTMatchFinder.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp

Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1202,6 +1202,8 @@
   if (!DeclNode) {
 return true;
   }
+  if (Options.Filter && Options.Filter->skipDecl(DeclNode))
+return true;
 
   bool ScopedTraversal =
   TraversingASTNodeNotSpelledInSource || DeclNode->isImplicit();
@@ -1454,5 +1456,8 @@
   return llvm::None;
 }
 
+// Out of line key method.
+MatchFinder::MatchFinderOptions::DeclFilter::~DeclFilter() = default;
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/include/clang/ASTMatchers/ASTMatchFinder.h
===
--- clang/include/clang/ASTMatchers/ASTMatchFinder.h
+++ clang/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -133,11 +133,19 @@
   /// Per bucket timing information.
   llvm::StringMap 
 };
+struct DeclFilter {
+  virtual bool skipDecl(Decl *) = 0;
+  virtual bool skipLocation(SourceLocation) = 0;
+  virtual ~DeclFilter();
+};
 
 /// Enables per-check timers.
 ///
 /// It prints a report after match.
 llvm::Optional CheckProfiling;
+
+/// Check if a Decl should be skipped.
+std::shared_ptr Filter;
   };
 
   MatchFinder(MatchFinderOptions Options = MatchFinderOptions());
Index: clang-tools-extra/test/clang-tidy/checkers/skip-headers.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/skip-headers.cpp
@@ -0,0 +1,54 @@
+// Test --skip-headers, --show-all-warnings, and --header-filter.
+// TODO: when skip-headers implementation is complete, add back
+//  -implicit-check-not="{{warning|error}}:"
+// and use no_hint instead of hint
+//
+// Default shows no warning in .h files, and give HINT to use --header-filter
+// RUN: clang-tidy %s -checks='*' -- \
+// RUN: 2>&1 | FileCheck %s -check-prefixes WARN,MAIN,HINT
+// later:-implicit-check-not="{{warning|error}}:"
+//
+// --skip-headers skips included files; finds only warnings in the main file.
+// RUN: clang-tidy 

[PATCH] D98710: [clang-tidy] Add --skip-headers, part 1

2021-06-11 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
chh updated this revision to Diff 351616.
chh retitled this revision from "WIP; clang-tidy skip-headers; Alt#2; need more 
changes" to "[clang-tidy] Add --skip-headers, part 1".
chh edited the summary of this revision.
chh added a comment.
Herald added subscribers: cfe-commits, xazax.hun.

sync with latest clang/llvm


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

https://reviews.llvm.org/D98710

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-tidy/checkers/Inputs/skip-headers/my_header1.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/skip-headers/my_header2.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-forward-declaration-namespace.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-include.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-interfaces-global-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-namespaces.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-objc-function-naming.m
  clang-tools-extra/test/clang-tidy/checkers/llvm-include-order.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvm-prefer-register-over-unsigned.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvmlibc-implementation-in-namespace.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvmlibc-restrict-system-libc-headers.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-no-recursion.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-cxx03.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-cxx11.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value-header.cpp
  
clang-tools-extra/test/clang-tidy/checkers/portability-restrict-system-includes-allow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/portability-restrict-system-includes-disallow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-chained-conditional-assignment.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-chained-conditional-return.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-members.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/test/clang-tidy/checkers/skip-headers.cpp
  clang/include/clang/ASTMatchers/ASTMatchFinder.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp

Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1306,12 +1306,25 @@
MatchFinder::ParsingDoneTestCallback *ParsingDone)
   : Finder(Finder), ParsingDone(ParsingDone) {}
 
+  bool HandleTopLevelDecl(DeclGroupRef DG) override {
+Finder->HandleTopLevelDecl(DG);
+return true;
+  }
+
 private:
   void HandleTranslationUnit(ASTContext ) override {
 if (ParsingDone != nullptr) {
   ParsingDone->run();
 }
-Finder->matchAST(Context);
+if (Finder->hasFilter()) {
+  auto SavedScope = Context.getTraversalScope();
+  auto  = Finder->getTraversalScope();
+  Context.setTraversalScope(MyTopDecls);
+  Finder->matchAST(Context);
+  Context.setTraversalScope(SavedScope);
+} else {
+  Finder->matchAST(Context);
+}
   }
 
   MatchFinder *Finder;
@@ -1454,5 +1467,44 @@
   return llvm::None;
 }
 
+// Out of line key method.
+MatchFinder::MatchFinderOptions::DeclFilter::~DeclFilter() = default;
+
+template 
+bool isTemplateSpecializationKind(const NamedDecl *D,
+  TemplateSpecializationKind Kind) {
+  if (const auto *TD = dyn_cast(D))
+return TD->getTemplateSpecializationKind() == Kind;
+  return false;
+}
+
+bool isTemplateSpecializationKind(const NamedDecl *D,
+  TemplateSpecializationKind Kind) {
+  return isTemplateSpecializationKind(D, Kind) ||
+ isTemplateSpecializationKind(D, Kind) ||
+ isTemplateSpecializationKind(D, Kind);
+}
+
+bool isImplicitTemplateInstantiation(const NamedDecl *D) {
+  return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation);
+}
+
+void MatchFinder::HandleTopLevelDecl(DeclGroupRef DG) {
+  if (hasFilter()) {
+for (Decl *D : DG) {
+  if (const NamedDecl *ND = dyn_cast(D))
+if (isImplicitTemplateInstantiation(ND))
+  continue;
+
+  // ObjCMethodDecl are not actually top-level decls.
+  if (isa(D))
+continue;
+
+  if (!Options.Filter->skipDecl(D))
+

[PATCH] D98618: [clang-tidy] Add --skip-headers, part 1

2021-06-11 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
chh updated this revision to Diff 351615.
chh added a comment.
Herald added a subscriber: cfe-commits.

sync with latest clang/llvm


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

https://reviews.llvm.org/D98618

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-tidy/checkers/Inputs/skip-headers/my_header1.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/skip-headers/my_header2.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-forward-declaration-namespace.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-include.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-interfaces-global-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-namespaces.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-objc-function-naming.m
  clang-tools-extra/test/clang-tidy/checkers/llvm-include-order.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvm-prefer-register-over-unsigned.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvmlibc-implementation-in-namespace.cpp
  
clang-tools-extra/test/clang-tidy/checkers/llvmlibc-restrict-system-libc-headers.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-no-recursion.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-cxx03.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-deprecated-headers-cxx11.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-pass-by-value-header.cpp
  
clang-tools-extra/test/clang-tidy/checkers/portability-restrict-system-includes-allow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/portability-restrict-system-includes-disallow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-chained-conditional-assignment.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-chained-conditional-return.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-members.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/test/clang-tidy/checkers/skip-headers.cpp
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/ASTMatchers/ASTMatchFinder.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/Parse/ParseAST.cpp

Index: clang/lib/Parse/ParseAST.cpp
===
--- clang/lib/Parse/ParseAST.cpp
+++ clang/lib/Parse/ParseAST.cpp
@@ -159,14 +159,20 @@
   // If we got a null return and something *was* parsed, ignore it.  This
   // is due to a top-level semicolon, an action override, or a parse error
   // skipping something.
-  if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
-return;
+  if (ADecl) {
+for (Decl *D : ADecl.get())
+  D->setTopLevelDecl();
+if (!Consumer->HandleTopLevelDecl(ADecl.get()))
+  return;
+  }
 }
   }
 
   // Process any TopLevelDecls generated by #pragma weak.
-  for (Decl *D : S.WeakTopLevelDecls())
+  for (Decl *D : S.WeakTopLevelDecls()) {
+D->setTopLevelDecl();
 Consumer->HandleTopLevelDecl(DeclGroupRef(D));
+  }
 
   Consumer->HandleTranslationUnit(S.getASTContext());
 
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1202,6 +1202,8 @@
   if (!DeclNode) {
 return true;
   }
+  if (Options.Filter && Options.Filter->skipDecl(DeclNode))
+return true;
 
   bool ScopedTraversal =
   TraversingASTNodeNotSpelledInSource || DeclNode->isImplicit();
@@ -1454,5 +1456,8 @@
   return llvm::None;
 }
 
+// Out of line key method.
+MatchFinder::MatchFinderOptions::DeclFilter::~DeclFilter() = default;
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/include/clang/ASTMatchers/ASTMatchFinder.h
===
--- clang/include/clang/ASTMatchers/ASTMatchFinder.h
+++ clang/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -133,11 +133,19 @@
   /// Per bucket timing information.
   llvm::StringMap 
 };
+struct DeclFilter {
+  virtual bool skipDecl(Decl *) = 0;
+  virtual bool skipLocation(SourceLocation) = 0;
+  virtual ~DeclFilter();
+};
 
 /// Enables per-check timers.
 ///
 /// It prints a report after match.
 llvm::Optional CheckProfiling;
+
+/// Check if a Decl should be skipped.
+std::shared_ptr Filter;
   };
 
   

[PATCH] D104088: Add clang frontend flags for MIP

2021-06-11 Thread Ellis Hoag via Phabricator via cfe-commits
ellis updated this revision to Diff 351604.
ellis added a comment.

Move llvm-strip logic into its own commit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104088

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/Darwin.h
  clang/lib/Driver/ToolChains/DragonFly.cpp
  clang/lib/Driver/ToolChains/FreeBSD.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Fuchsia.h
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/Linux.h
  clang/lib/Driver/ToolChains/NetBSD.cpp
  clang/lib/Driver/ToolChains/Solaris.cpp
  clang/test/CMakeLists.txt
  clang/test/Driver/clang-mip-flags.c

Index: clang/test/Driver/clang-mip-flags.c
===
--- /dev/null
+++ clang/test/Driver/clang-mip-flags.c
@@ -0,0 +1,44 @@
+// REQUIRES: clang-driver
+
+// RUN: %clang -### -fmachine-profile-use=/path/to/profile.mip %s 2>&1 | FileCheck %s --check-prefix USE
+// USE: "-cc1"
+// USE-SAME: "-mllvm" "-machine-profile-use=/path/to/profile.mip"
+// USE-SAME: "-mllvm" "-link-unit-name=a.out"
+
+// RUN: %clang -### -fmachine-profile-use=/path/to/profile.mip -o my-executable %s 2>&1 | FileCheck %s --check-prefix USE-OUTPUT
+// RUN: %clang -### -fmachine-profile-use=/path/to/profile.mip -fmachine-profile-link-unit-name=my-executable %s 2>&1 | FileCheck %s --check-prefix USE-OUTPUT
+// USE-OUTPUT: "-cc1"
+// USE-OUTPUT-SAME: "-mllvm" "-link-unit-name=my-executable"
+
+// RUN: %clang -### -fmachine-profile-generate %s 2>&1 | FileCheck %s --check-prefix GEN
+// RUN: %clang -### -fno-machine-profile-generate -fmachine-profile-generate %s 2>&1 | FileCheck %s --check-prefix GEN
+// GEN: "-cc1"
+// GEN-SAME: "-mllvm" "-enable-machine-instrumentation"
+// GEN-SAME: "-mllvm" "-link-unit-name=a.out"
+
+// RUN: %clang -### %s 2>&1 | FileCheck %s --check-prefix NOGEN
+// RUN: %clang -### -fno-machine-profile-generate %s 2>&1 | FileCheck %s --check-prefix NOGEN
+// RUN: %clang -### -fmachine-profile-generate -fno-machine-profile-generate %s 2>&1 | FileCheck %s --check-prefix NOGEN
+// NOGEN-NOT: "-enable-machine-instrumentation"
+
+// RUN: %clang -### -fmachine-profile-generate -fmachine-profile-function-coverage %s 2>&1 | FileCheck %s --check-prefix FUNCCOV
+// FUNCCOV: "-cc1"
+// FUNCCOV-SAME: "-mllvm" "-enable-machine-function-coverage"
+
+// RUN: %clang -### -fmachine-profile-generate -fmachine-profile-block-coverage %s 2>&1 | FileCheck %s --check-prefix BLOCKCOV
+// BLOCKCOV: "-cc1"
+// BLOCKCOV-SAME: "-mllvm" "-enable-machine-block-coverage"
+
+// RUN: %clang -### -fmachine-profile-generate %s 2>&1 | FileCheck %s --check-prefix FULL
+// RUN: %clang -### -fmachine-profile-generate -fmachine-profile-call-graph %s 2>&1 | FileCheck %s --check-prefix FULL
+// FULL: "-cc1"
+// FULL-SAME: "-mllvm" "-enable-machine-call-graph"
+
+// RUN: %clang -### -fmachine-profile-generate -fmachine-profile-runtime-buffer=1024 %s 2>&1 | FileCheck %s --check-prefix RUNTIMEBUF
+// RUNTIMEBUF: "-cc1"
+// RUNTIMEBUF-SAME: "-mllvm" "-machine-profile-runtime-buffer=1024"
+
+// RUN: %clang -### -fmachine-profile-generate -fmachine-profile-function-group-count=22 -fmachine-profile-selected-function-group=11 %s 2>&1 | FileCheck %s --check-prefix GEN-GROUPS
+// GEN-GROUPS: "-cc1"
+// GEN-GROUPS-SAME: "-mllvm" "-machine-profile-function-group-count=22"
+// GEN-GROUPS-SAME: "-mllvm" "-machine-profile-selected-function-group=11"
Index: clang/test/CMakeLists.txt
===
--- clang/test/CMakeLists.txt
+++ clang/test/CMakeLists.txt
@@ -118,6 +118,7 @@
 llvm-lto2
 llvm-modextract
 llvm-nm
+llvm-mipdata
 llvm-objcopy
 llvm-objdump
 llvm-profdata
Index: clang/lib/Driver/ToolChains/Solaris.cpp
===
--- clang/lib/Driver/ToolChains/Solaris.cpp
+++ clang/lib/Driver/ToolChains/Solaris.cpp
@@ -149,6 +149,7 @@
   CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
 
   getToolChain().addProfileRTLibs(Args, CmdArgs);
+  getToolChain().addMachineProfileRTLibs(Args, CmdArgs);
 
   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
   C.addCommand(std::make_unique(JA, *this, ResponseFileSupport::None(),
Index: clang/lib/Driver/ToolChains/NetBSD.cpp
===
--- clang/lib/Driver/ToolChains/NetBSD.cpp
+++ clang/lib/Driver/ToolChains/NetBSD.cpp
@@ -337,6 +337,7 @@
   }
 
   ToolChain.addProfileRTLibs(Args, CmdArgs);
+  ToolChain.addMachineProfileRTLibs(Args, CmdArgs);
 
   const char *Exec = 

[PATCH] D88666: DirectoryWatcher: add an implementation for Windows

2021-06-11 Thread Adrian McCarthy via Phabricator via cfe-commits
amccarth added a comment.

This patch was reverted a while back because a couple DirectoryWatcher tests 
routinely timed out on build bots even though they work when run in isolation.

I believe the problem is that, on a machine busy doing a build, the startup of 
the watcher thread is delayed (either because the scheduler algorithm or the 
thread pool policy).  Thus the "initial scan" on the test thread can complete 
_before_ the watcher thread has called ReadDirectoryChangesW.  This leaves a 
window of time where the test can change a file that the watcher thread will 
miss.

To test this hypothesis, I took this patch and created one more event called 
`WatcherThreadReady`.  I have the watcher thread set this event after 
successfully calling ReadDirectoryChangesW.  In the constructor, I changed:

  if (WaitForInitialSync)
InitialScan();

to

  if (WaitForInitialSync) {
::WaitForSingleObject(WatcherThreadReady, 1);
InitialScan();
  }

This is crude, but it seems to be effective.  The tests pass reliably for me 
when my machine is fully loaded.  I didn't use an INFINITE timeout because it 
seems possibly missing a file change is less bad than hanging forever.  I 
didn't even bother to check the result from the wait because there's nothing 
sane to do besides "best effort" if something goes wrong.  I used a Windows 
event because those are most familiar to me and it's Windows-only code.   But 
it certainly could be done with other type of synchronization object.

There may be more elegant ways to solve this, but something like this directly 
addresses the root cause with fairly minimal changes.

I wonder if the Linux and Mac implementations might suffer from a similar 
window but the bug is rare because of differences in thread scheduler.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88666

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


[PATCH] D103131: support debug info for alias variable

2021-06-11 Thread kamlesh kumar via Phabricator via cfe-commits
kamleshbhalui added a comment.

In D103131#2814015 , @dblaikie wrote:

> In D103131#2811969 , @kamleshbhalui 
> wrote:
>
>> In D103131#2811220 , @dblaikie 
>> wrote:
>>
>>> Any idea if the GDB test suite covers this functionality? I'd hope so, but 
>>> maybe it doesn't.
>>>
>>> But yeah, at the moment I don't have any great reason to avoid the imported 
>>> declaration form - so happy to go with that.
>>
>> Hi David,
>>
>> with imported declaration patch and with current patch(in review or say gcc 
>> way) this case works ok(we can print type and value of newname)
>> $cat test.c
>> int oldname = 1;
>> extern int newname attribute((alias("oldname")));
>>
>> but when we make newname static it works with current patch(in review or say 
>> gcc way) but it does not work with imported decl 
>> patch(https://reviews.llvm.org/D103131?id=347883).
>>
>> Should we go with gcc way or am I missing something?
>> note: used gdb debugger.
>
> An ideas what's happening when `newname` is static? Is the DWARF any 
> different/interesting there? (since the DWARF for imported decl seems like it 
> would have nothing to do with the linkange of the alias - since it doesn't 
> refer to the actual alias in the object file, etc)

There not much different apart from extern has external attribute.
**case 1) when `newname` is static**

.debug_info contents:
0x: Compile Unit: length = 0x0072, format = DWARF32, version = 
0x0004, abbr_offset = 0x, addr_size = 0x08 (next unit at 0x0076)

0x000b: DW_TAG_compile_unit

  DW_AT_producer("clang version 13.0.0 
(g...@github.com:llvm/llvm-project.git 
4cd7169f5517167ef456e82c6dcae669bde6c725)")
  DW_AT_language(DW_LANG_C99)
  DW_AT_name("test.c")
  DW_AT_stmt_list   (0x)
  DW_AT_comp_dir("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin")
  DW_AT_low_pc  (0x)
  DW_AT_high_pc (0x0008)

0x002a:   DW_TAG_variable

  DW_AT_name  ("oldname")
  DW_AT_type  (0x003f "int")
  DW_AT_external  (true)
  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (1)
  DW_AT_location  (DW_OP_addr 0x0)

0x003f:   DW_TAG_base_type

  DW_AT_name  ("int")
  DW_AT_encoding  (DW_ATE_signed)
  DW_AT_byte_size (0x04)

0x0046:   DW_TAG_variable

  DW_AT_name  ("newname")
  DW_AT_type  (0x003f "int")
  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (2)
  DW_AT_declaration   (true)

0x0051:   DW_TAG_imported_declaration

  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (2)
  DW_AT_import(0x0046)
  DW_AT_name  ("newname")

0x005c:   DW_TAG_subprogram

  DW_AT_low_pc(0x)
  DW_AT_high_pc   (0x0008)
  DW_AT_frame_base(DW_OP_reg6 RBP)
  DW_AT_name  ("main")
  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (3)
  DW_AT_type  (0x003f "int")
  DW_AT_external  (true)

0x0075:   NULL

**case 2) when `newname` is extern**

.debug_info contents:
0x: Compile Unit: length = 0x0072, format = DWARF32, version = 
0x0004, abbr_offset = 0x, addr_size = 0x08 (next unit at 0x0076)

0x000b: DW_TAG_compile_unit

  DW_AT_producer("clang version 13.0.0 
(g...@github.com:llvm/llvm-project.git 
4cd7169f5517167ef456e82c6dcae669bde6c725)")
  DW_AT_language(DW_LANG_C99)
  DW_AT_name("test.c")
  DW_AT_stmt_list   (0x)
  DW_AT_comp_dir("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin")
  DW_AT_low_pc  (0x)
  DW_AT_high_pc (0x0008)

0x002a:   DW_TAG_variable

  DW_AT_name  ("oldname")
  DW_AT_type  (0x003f "int")
  DW_AT_external  (true)
  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (1)
  DW_AT_location  (DW_OP_addr 0x0)

0x003f:   DW_TAG_base_type

  DW_AT_name  ("int")
  DW_AT_encoding  (DW_ATE_signed)
  DW_AT_byte_size (0x04)

0x0046:   DW_TAG_variable

  DW_AT_name  ("newname")
  DW_AT_type  (0x003f "int")
  DW_AT_external  (true)
  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (2)
  DW_AT_declaration   (true)

0x0051:   DW_TAG_imported_declaration

  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (2)
  DW_AT_import(0x0046)
  DW_AT_name  ("newname")

0x005c:   DW_TAG_subprogram

  DW_AT_low_pc(0x)
  DW_AT_high_pc   (0x0008)
  DW_AT_frame_base(DW_OP_reg6 RBP)
  DW_AT_name  ("main")
  DW_AT_decl_file ("/folk/kkumar/tcllvm/llvm-build-lldb-rel/bin/test.c")
  DW_AT_decl_line (3)
  DW_AT_type  (0x003f "int")
  DW_AT_external  (true)

0x0075:   NULL



[PATCH] D103936: [compiler-rt][hwasan] Define fuchsia implementations of required hwasan functions

2021-06-11 Thread Roland McGrath via Phabricator via cfe-commits
mcgrathr added inline comments.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:29
+
+uptr kHighMemEnd;
+uptr kHighMemBeg;

leonardchan wrote:
> mcgrathr wrote:
> > These need comments about what they are and why they need to exist as 
> > runtime variables at all.
> `kHighMemEnd` and `kHighMemBeg` are used only by `MemIsApp` which is only 
> used in `hwasan_thread.cpp` for some debugging checks:
> 
> ```
>   if (stack_bottom_) {
> int local;
> CHECK(AddrIsInStack((uptr)));
> CHECK(MemIsApp(stack_bottom_));
> CHECK(MemIsApp(stack_top_ - 1));
>   }
> ```
> 
> Rather than having these, we could just use their values 
> (`__sanitizer::ShadowBounds.memory_limit - 1` and 
> `__sanitizer::ShadowBounds.shadow_limit`) directly in `MemIsApp` to avoid 
> these globals.
> 
> `kAliasRegionStart` is used in `HwasanAllocatorInit` for setting up the 
> allocator, but is only relevant for an experimental x86 implementation that 
> uses page aliasing for placing tags in heap allocations (see D98875). I 
> didn't look too much into   the machinery for this since I didn't think we 
> would be using hwasan for x86 anytime soon, but we can explore this now if we 
> want to plan ahead. We could also make it such that this is just defined as 0 
> on x86 platforms, similar to `SHADOW_OFFSET` in asan.
MemIsApp is defined in this file so don't define any globals on its account (if 
it needs anything, make it static in this file).

HWASAN_ALIASING_MODE is not supported for Fuchsia and we don't need to make 
sure it compiles.  Just leave out anything related to it entirely for now.





Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:34
+bool InitShadow() {
+  __hwasan_shadow_memory_dynamic_address = 0;
+

leonardchan wrote:
> mcgrathr wrote:
> > What actually refers to this?
> > The optimal implementation for Fuchsia would just know everywhere at 
> > compile time that it's a fized value.
> > If there's reason for the runtime variable to exist at all, it should have 
> > comments.
> It's only used for converting between application memory and shadow memory:
> 
> ```
> // hwasan_mapping.h
> inline uptr MemToShadow(uptr untagged_addr) {
>   return (untagged_addr >> kShadowScale) +
>  __hwasan_shadow_memory_dynamic_address;
> }
> inline uptr ShadowToMem(uptr shadow_addr) {
>   return (shadow_addr - __hwasan_shadow_memory_dynamic_address) << 
> kShadowScale;
> }
> ```
> 
> Perhaps we could have something similar to the `SHADOW_OFFSET` macro in asan 
> where it can be defined to either a constant or 
> `__hwasan_shadow_memory_dynamic_address` on different platforms and these 
> functions can just use the macro.
That sounds good.  But we can make that a separate refactoring cleanup of its 
own.  It's fine to just define it to 0 here and leave a TODO comment about 
removing the runtime variable altogether on Fuchsia.

That's a refactoring you could either land separately on its own first before 
landing the Fuchsia port, or do afterwards as a separate cleanup change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103936

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


[PATCH] D104085: [compiler-rt][hwasan] Setup hwasan thread handling on Fuchsia

2021-06-11 Thread Roland McGrath via Phabricator via cfe-commits
mcgrathr added a comment.

Usually we like to split changes up into separate small changes for the pure 
refactoring, and then changes that purely add new Fuchsia-specific code.
I'll do an initial review round of the Fuchsia code here since you've sent it.  
But then I think this review should be tightened to just the pure refactoring, 
and we should have a separate review thread for the Fuchsia parts.




Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:26
+// used to always find the hwasan thread object associated with the current
+// running thread.
+SANITIZER_INTERFACE_ATTRIBUTE

Specifically call out here that the compiler generates direct TLS references to 
this and that's why it has a public C ABI name.

For Fuchsia the hwasan will always be in a DSO that is a dependency of libc.so 
and so always loaded at startup.  Hence we can use 
`[[gnu::tls_model("initial-exec")]]` here.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:32-33
+
+// These are known parameters passed to the hwasan runtime on thread creation
+// when creating a thread.
+struct Thread::InitOptions {

department of redundancy department



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:34
+// when creating a thread.
+struct Thread::InitOptions {
+  uptr stack_bottom, stack_top;

Nit: I'd call it something more like InitState.




Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:41
+void InitThreads() {
+  uptr alloc_size = UINT64_C(1) << kShadowBaseAlignment;
+  uptr thread_start = reinterpret_cast(

What depends on this alignment?  I'm not aware of anything that does in the 
compiler ABI we're using on Fuchsia.
If it's needed, it should have comments.




Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:84-88
+// are known before thread creation. However, we cannot setup the stack ring
+// buffer just yet because it is stored in the global __hwasan_tls, which we 
can
+// only correctly access once in the new thread. This will be set up in the
+// ThreadStartHook where we can safely reference __hwasan_tls while in the new
+// thread.

Actually we could do all of the allocation and setup except for storing the 
uptr in `__hwasan_tls`.
But that would take more refactoring of the common code and it's not clear 
there's a particular benefit.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:137
+// __hwasan_tls can be referenced.
+static void FinishThreadInitialization(Thread *thread) {
+  CHECK_NE(thread, nullptr);

Most of what's happening in this function is common with the Linux code.
I think a shared function can be factored out and put into hwasan_thread.cpp.




Comment at: compiler-rt/lib/hwasan/hwasan_thread.cpp:42-45
-  static u64 unique_id;
-  unique_id_ = unique_id++;
-  if (auto sz = flags()->heap_history_size)
-heap_allocations_ = HeapAllocationsRingBuffer::New(sz);

This is stuff that could be done either in the before-create hook or in the 
on-start hook.  But it's probably not especially worthwhile to move it to 
before-create as long as we have on-start doing any allocation at all.  So to 
avoid a whole lot more refactoring to move the ringbuffer setup and such, might 
as well just leave this in on-start too.



Comment at: compiler-rt/lib/hwasan/hwasan_thread.cpp:58-63
-  uptr tls_size;
-  uptr stack_size;
-  GetThreadStackAndTls(IsMainThread(), _bottom_, _size, 
_begin_,
-   _size);
-  stack_top_ = stack_bottom_ + stack_size;
-  tls_end_ = tls_begin_ + tls_size;

This is probably the only part that actually needs to be different between 
Linux and Fuchsia.
So this code could just move into an InitStackAndTls(options) that looks like 
this on Linux and on Fuchsia is just copying values out of options. 




Comment at: compiler-rt/lib/hwasan/hwasan_thread.h:85
   HeapAllocationsRingBuffer *heap_allocations_;
-  StackAllocationsRingBuffer *stack_allocations_;
+  StackAllocationsRingBuffer *stack_allocations_ = nullptr;
 

I think these need to be left uniformly uninitialized to guarantee they can be 
"linker-initialized".
At any rate, there's no reason one pointer member here should be initialized 
and the others not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104085

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


[PATCH] D104155: Add documentation for -fsanitize-address-use-after-return.

2021-06-11 Thread Kevin Athey via Phabricator via cfe-commits
kda updated this revision to Diff 351571.
kda marked an inline comment as done.
kda added a comment.

- Revised according to feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104155

Files:
  clang/docs/AddressSanitizer.rst
  clang/docs/ClangCommandLineReference.rst


Index: clang/docs/ClangCommandLineReference.rst
===
--- clang/docs/ClangCommandLineReference.rst
+++ clang/docs/ClangCommandLineReference.rst
@@ -881,6 +881,15 @@
 * ``global`` - Emit module destructors that are called via a platform specific 
array (see `llvm.global_dtors`).
 * ``none`` - Do not emit module destructors.
 
+.. option:: -fsanitize-address-use-after-return=
+
+Select the enabling method of detecting stack use-after-return in 
AddressSanitizer.
+
+Valid options are:
+* ``always`` - Detect use-after-return.
+* ``runtime`` - Detect use-after-return with runtime ON/OFF switch 
(environment variable `ASAN_OPTIONS=detect_stack_use_after_return=1`, default: 
0)
+* ``never`` - Do not detect use-after-return.
+
 .. option:: -fsanitize-ignorelist=
 
 Path to ignorelist file for sanitizers
Index: clang/docs/AddressSanitizer.rst
===
--- clang/docs/AddressSanitizer.rst
+++ clang/docs/AddressSanitizer.rst
@@ -14,7 +14,8 @@
 
 * Out-of-bounds accesses to heap, stack and globals
 * Use-after-free
-* Use-after-return (runtime flag 
`ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* Use-after-return (clang flag 
`-fsanitize-address-use-after-return=(always|runtime|never)` default: runtime)
+  * Add runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1` to enable 
when compiled with `-fsanitize-address-use-after-return=runtime`)
 * Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)
 * Double-free, invalid free
 * Memory leaks (experimental)


Index: clang/docs/ClangCommandLineReference.rst
===
--- clang/docs/ClangCommandLineReference.rst
+++ clang/docs/ClangCommandLineReference.rst
@@ -881,6 +881,15 @@
 * ``global`` - Emit module destructors that are called via a platform specific array (see `llvm.global_dtors`).
 * ``none`` - Do not emit module destructors.
 
+.. option:: -fsanitize-address-use-after-return=
+
+Select the enabling method of detecting stack use-after-return in AddressSanitizer.
+
+Valid options are:
+* ``always`` - Detect use-after-return.
+* ``runtime`` - Detect use-after-return with runtime ON/OFF switch (environment variable `ASAN_OPTIONS=detect_stack_use_after_return=1`, default: 0)
+* ``never`` - Do not detect use-after-return.
+
 .. option:: -fsanitize-ignorelist=
 
 Path to ignorelist file for sanitizers
Index: clang/docs/AddressSanitizer.rst
===
--- clang/docs/AddressSanitizer.rst
+++ clang/docs/AddressSanitizer.rst
@@ -14,7 +14,8 @@
 
 * Out-of-bounds accesses to heap, stack and globals
 * Use-after-free
-* Use-after-return (runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* Use-after-return (clang flag `-fsanitize-address-use-after-return=(always|runtime|never)` default: runtime)
+  * Add runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1` to enable when compiled with `-fsanitize-address-use-after-return=runtime`)
 * Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)
 * Double-free, invalid free
 * Memory leaks (experimental)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D104155: Add documentation for -fsanitize-address-use-after-return.

2021-06-11 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: clang/docs/AddressSanitizer.rst:18
+* Use-after-return (clang flag 
`-fsanitize-address-use-after-return=(always|runtime|never)` default: runtime)
+  * Add runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1` to enable 
when compiled with `-fsanitize-address-use-after-return=runtime`)
 * Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)

Please check that this is formatted reasonable in preview.



Comment at: clang/docs/ClangCommandLineReference.rst:889
+Valid options are:
+* ``always`` - Always detect use-after-return.  (Code generated and always 
enabled.)
+* ``runtime`` - Detect use-after-return at runtime if enabled by runtime 
command line (flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)

"Code generated and always enabled." is implementation details.
Something like this? 

```
Valid options are:
* ``always`` - Detect use-after-return.
* ``runtime`` - Detect use-after-return with runtime ON/OFF switch (environment 
variable `ASAN_OPTIONS=detect_stack_use_after_return=1`, default: 0)
* ``never`` - Do not detect use-after-return.
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104155

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


[PATCH] D104155: Add documentation for -fsanitize-address-use-after-return.

2021-06-11 Thread Kevin Athey via Phabricator via cfe-commits
kda created this revision.
kda added a reviewer: vitalybuka.
kda requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

for issue: https://github.com/google/sanitizers/issues/1394


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104155

Files:
  clang/docs/AddressSanitizer.rst
  clang/docs/ClangCommandLineReference.rst


Index: clang/docs/ClangCommandLineReference.rst
===
--- clang/docs/ClangCommandLineReference.rst
+++ clang/docs/ClangCommandLineReference.rst
@@ -881,6 +881,15 @@
 * ``global`` - Emit module destructors that are called via a platform specific 
array (see `llvm.global_dtors`).
 * ``none`` - Do not emit module destructors.
 
+.. option:: -fsanitize-address-use-after-return=
+
+Select the enabling method of detecting stack use-after-return in 
AddressSanitizer.
+
+Valid options are:
+* ``always`` - Always detect use-after-return.  (Code generated and always 
enabled.)
+* ``runtime`` - Detect use-after-return at runtime if enabled by runtime 
command line (flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* ``never`` - Never detect use-after-return.  (Code not generated for 
detection.)
+
 .. option:: -fsanitize-ignorelist=
 
 Path to ignorelist file for sanitizers
Index: clang/docs/AddressSanitizer.rst
===
--- clang/docs/AddressSanitizer.rst
+++ clang/docs/AddressSanitizer.rst
@@ -14,7 +14,8 @@
 
 * Out-of-bounds accesses to heap, stack and globals
 * Use-after-free
-* Use-after-return (runtime flag 
`ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* Use-after-return (clang flag 
`-fsanitize-address-use-after-return=(always|runtime|never)` default: runtime)
+  * Add runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1` to enable 
when compiled with `-fsanitize-address-use-after-return=runtime`)
 * Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)
 * Double-free, invalid free
 * Memory leaks (experimental)


Index: clang/docs/ClangCommandLineReference.rst
===
--- clang/docs/ClangCommandLineReference.rst
+++ clang/docs/ClangCommandLineReference.rst
@@ -881,6 +881,15 @@
 * ``global`` - Emit module destructors that are called via a platform specific array (see `llvm.global_dtors`).
 * ``none`` - Do not emit module destructors.
 
+.. option:: -fsanitize-address-use-after-return=
+
+Select the enabling method of detecting stack use-after-return in AddressSanitizer.
+
+Valid options are:
+* ``always`` - Always detect use-after-return.  (Code generated and always enabled.)
+* ``runtime`` - Detect use-after-return at runtime if enabled by runtime command line (flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* ``never`` - Never detect use-after-return.  (Code not generated for detection.)
+
 .. option:: -fsanitize-ignorelist=
 
 Path to ignorelist file for sanitizers
Index: clang/docs/AddressSanitizer.rst
===
--- clang/docs/AddressSanitizer.rst
+++ clang/docs/AddressSanitizer.rst
@@ -14,7 +14,8 @@
 
 * Out-of-bounds accesses to heap, stack and globals
 * Use-after-free
-* Use-after-return (runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
+* Use-after-return (clang flag `-fsanitize-address-use-after-return=(always|runtime|never)` default: runtime)
+  * Add runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1` to enable when compiled with `-fsanitize-address-use-after-return=runtime`)
 * Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)
 * Double-free, invalid free
 * Memory leaks (experimental)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2021-06-11 Thread Michael Benfield via Phabricator via cfe-commits
mbenfield updated this revision to Diff 351563.
mbenfield added a comment.

rebase and rerun builds


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103623

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


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


Index: clang/test/Sema/warn-unused-but-set-variables.c
===
--- clang/test/Sema/warn-unused-but-set-variables.c
+++ clang/test/Sema/warn-unused-but-set-variables.c
@@ -23,6 +23,10 @@
   int a;
   w = (a = 0);
 
+  // Following gcc, warn for a volatile variable.
+  volatile int b; // expected-warning{{variable 'b' set but not used}}
+  b = 0;
+
   int x;
   x = 0;
   return x;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D104138: Create install targets for scan-build-py.

2021-06-11 Thread Petr Hosek via Phabricator via cfe-commits
phosek accepted this revision.
phosek added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104138

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


[clang] 22dea69 - [clang][ObjC] allow the use of NSAttributedString * argument type with format attribute

2021-06-11 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-06-11T13:24:32-07:00
New Revision: 22dea6923155b18d172db64e5dab4b71afe19e6e

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

LOG: [clang][ObjC] allow the use of NSAttributedString * argument type with 
format attribute

This is useful for APIs that want to accept an attributed NSString as their 
format string

rdar://79163229

Added: 


Modified: 
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/SemaObjC/format-strings-objc.m

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 2448636bdd52..17fe8c071345 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3471,7 +3471,7 @@ static void handleFormatAttr(Sema , Decl *D, const 
ParsedAttr ) {
   } else if (Kind == NSStringFormat) {
 // FIXME: do we need to check if the type is NSString*?  What are the
 // semantics?
-if (!isNSStringType(Ty, S.Context)) {
+if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
   S.Diag(AL.getLoc(), diag::err_format_attribute_not)
 << "an NSString" << IdxExpr->getSourceRange()
 << getFunctionOrMethodParamRange(D, ArgIdx);

diff  --git a/clang/test/SemaObjC/format-strings-objc.m 
b/clang/test/SemaObjC/format-strings-objc.m
index e5a1a824abba..d80424487c6f 100644
--- a/clang/test/SemaObjC/format-strings-objc.m
+++ b/clang/test/SemaObjC/format-strings-objc.m
@@ -34,6 +34,11 @@ @interface NSSimpleCString : NSString {} @end
 @interface NSConstantString : NSSimpleCString @end
 extern void *_NSConstantStringClassReference;
 
+@interface NSAttributedString : NSObject
++(instancetype)stringWithFormat:(NSAttributedString *)fmt, ...
+__attribute__((format(__NSString__, 1, 2)));
+@end
+
 typedef const struct __CFString * CFStringRef;
 extern void CFStringCreateWithFormat(CFStringRef format, ...) 
__attribute__((format(CFString, 1, 2)));
 #define CFSTR(cStr)  ((CFStringRef) __builtin___CFStringMakeConstantString ("" 
cStr ""))
@@ -317,6 +322,9 @@ - (NSString *)someRandomMethod:(NSString *)key
  value:(nullable NSString *)value
  table:(nullable NSString *)tableName
 __attribute__((format_arg(1)));
+
+- (NSAttributedString *)someMethod2:(NSString *)key
+__attribute__((format_arg(1)));
 @end
 
 void useLocalizedStringForKey(NSBundle *bndl) {
@@ -341,4 +349,9 @@ void useLocalizedStringForKey(NSBundle *bndl) {
   [bndl someRandomMethod:@"flerp"
value:0
table:0], 42]; // expected-warning{{data 
argument not used by format string}}
+
+  [NSAttributedString stringWithFormat:
+  [bndl someMethod2: @"test"], 5]; // expected-warning{{data 
argument not used by format string}}
+  [NSAttributedString stringWithFormat:
+  [bndl someMethod2: @"%f"], 42]; // expected-warning{{format 
specifies type 'double' but the argument has type 'int'}}
 }



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


[PATCH] D104135: [analyzer] Decouple NoteTag from its Factory

2021-06-11 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D104135#2814081 , @NoQ wrote:

> P.S. I like this design!
>
> I'm trying to remember why we needed a factory in the first place.

Who's gonna carry your callbacks for ya, huh?

> I think a lot of tags work just fine as static variables.

Sure, but if you have data, let's say it's something that doesn't need to be 
stored somewhere to prolong its lifetime, you still need to have static 
variable for each possible value of that piece of data.  Not really feasible in 
the vast majority of cases.  Because you might need to refer to the same tag 
with different possible values.

> In case of D104136  IIUC `IdentityCall` 
> could always be discovered as the current program point...

That's true, I put this one as "just in case".

> ...and its `Source` is its only argument...

Not really, there is also case when the call is `IdentityThis`, so its `Source` 
is not its only argument.

> ...so all we need is a marker that says "we did indeed model this code as 
> identity" so it could potentially be allocated statically. But when the tag 
> really needs to carry more data then there's probably no way around the 
> factory.






Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:777
   static bool classof(const ProgramPointTag *T) {
 return T->getTagKind() == 
   }

NoQ wrote:
> NoQ wrote:
> > It sounds like `NoteTag` `isn't` despite inheriting from it.
> Wait nvm, `DataTag` doesn't provide a `classof` at all. This means we can't 
> write `isa` at all, right?
Yes, it's purely abstract.  `ProgramPointTag` also doesn't have `classof`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104135

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread David Li via Phabricator via cfe-commits
davidxl added a comment.

Adding Wei to help measure performance impact on our internal workloads.  Also 
add Wenlei to help measure impact with FB's workloads.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D103184: [AArch64] handle -Wa,-march=

2021-06-11 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D103184#2813748 , @thakis wrote:

> In D103184#2804241 , @jcai19 wrote:
>
>> In D103184#2803768 , @thakis wrote:
>>
>>> FWIW the failure goes away locally if I revert this change here, so it's 
>>> definitely due to this change here.
>>>
>>> Things have been red for a while, probably good to revert while you 
>>> investigate by this point.
>>
>> Sorry for the delay but my macbook had some issues so I just finished 
>> building LLVM, but I can't seem to reproduce the test failure locally 
>> (neither by running the test directly with llvm-lit nor with `ninja 
>> check-clang`). In fact I don't quite understand why this test failed.  Like 
>> @nickdesaulniers mentioned the build failure should have been fixed in 
>> https://reviews.llvm.org/rG76d9bc72784d88f4dd57b9939e52c73739438af5 for a 
>> different patch. Do you mind sharing the instructions you used to reproduce 
>> the test failure? Thanks.
>
> Did you try on a mac with a m1 processor?

This suggestion doesn't make sense to me. The order of events:

1. https://reviews.llvm.org/rG3cc3c0f8352ec33ca2f2636f94cb1d85fc57ac16 landed, 
broke the build
2. 1 was reverted in 
https://reviews.llvm.org/rGbf2479c347c8ca88fefdb144d8bae0a7a4231e2a
3. 1 was relanded in 
https://reviews.llvm.org/rG76d9bc72784d88f4dd57b9939e52c73739438af5
4. different patch was landed 
https://reviews.llvm.org/rGfd11a26d368c5a909fb88548fef2cee7a6c2c931
5. @thakis  reports patch from 4 causes a test failure, but the test failure 
looks like the test failure from 1, not 4.
6. 4 is reverted in 
https://reviews.llvm.org/rG9145a3d4ab7eb05d9fb113b5392e8961df629b88

#5 doesn't make sense to me, and I don't see how the test would turn out 
differently on an m1 mac vs x86


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103184

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


[PATCH] D104135: [analyzer] Decouple NoteTag from its Factory

2021-06-11 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

P.S. I like this design!

I'm trying to remember why we needed a factory in the first place. I think a 
lot of tags work just fine as static variables. In case of D104136 
 IIUC `IdentityCall` could always be 
discovered as the current program point and its `Source` is its only argument 
so all we need is a marker that says "we did indeed model this code as 
identity" so it could potentially be allocated statically. But when the tag 
really needs to carry more data then there's probably no way around the factory.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:777
   static bool classof(const ProgramPointTag *T) {
 return T->getTagKind() == 
   }

NoQ wrote:
> It sounds like `NoteTag` `isn't` despite inheriting from it.
Wait nvm, `DataTag` doesn't provide a `classof` at all. This means we can't 
write `isa` at all, right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104135

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


[PATCH] D104076: [clang-cl][sanitizer] Add -fsanitize-address-use-after-return to clang.

2021-06-11 Thread Kevin Athey 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 rGe0b469ffa142: [clang-cl][sanitizer] Add 
-fsanitize-address-use-after-return to clang. (authored by kda).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104076

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/Sanitizers.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/Basic/Sanitizers.cpp
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/asan-use-after-return.cpp
  clang/test/Driver/cl-options.c
  clang/test/Driver/fsanitize-use-after-return.c
  llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -633,17 +633,24 @@
 struct AddressSanitizer {
   AddressSanitizer(Module , const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
-   bool UseAfterScope = false)
+   bool UseAfterScope = false,
+   AsanDetectStackUseAfterReturnMode UseAfterReturn =
+   AsanDetectStackUseAfterReturnMode::Runtime)
   : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
 : CompileKernel),
 Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
-UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
+UseAfterScope(UseAfterScope || ClUseAfterScope),
+UseAfterReturn(ClUseAfterReturn.getNumOccurrences() ? ClUseAfterReturn
+: UseAfterReturn),
+GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
 TargetTriple = Triple(M.getTargetTriple());
 
 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
+
+assert(this->UseAfterReturn != AsanDetectStackUseAfterReturnMode::Invalid);
   }
 
   uint64_t getAllocaSizeInBytes(const AllocaInst ) const {
@@ -727,6 +734,7 @@
   bool CompileKernel;
   bool Recover;
   bool UseAfterScope;
+  AsanDetectStackUseAfterReturnMode UseAfterReturn;
   Type *IntptrTy;
   ShadowMapping Mapping;
   FunctionCallee AsanHandleNoReturnFunc;
@@ -754,11 +762,13 @@
 public:
   static char ID;
 
-  explicit AddressSanitizerLegacyPass(bool CompileKernel = false,
-  bool Recover = false,
-  bool UseAfterScope = false)
+  explicit AddressSanitizerLegacyPass(
+  bool CompileKernel = false, bool Recover = false,
+  bool UseAfterScope = false,
+  AsanDetectStackUseAfterReturnMode UseAfterReturn =
+  AsanDetectStackUseAfterReturnMode::Runtime)
   : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
-UseAfterScope(UseAfterScope) {
+UseAfterScope(UseAfterScope), UseAfterReturn(UseAfterReturn) {
 initializeAddressSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
   }
 
@@ -777,7 +787,7 @@
 const TargetLibraryInfo *TLI =
 ().getTLI(F);
 AddressSanitizer ASan(*F.getParent(), , CompileKernel, Recover,
-  UseAfterScope);
+  UseAfterScope, UseAfterReturn);
 return ASan.instrumentFunction(F, TLI);
   }
 
@@ -785,6 +795,7 @@
   bool CompileKernel;
   bool Recover;
   bool UseAfterScope;
+  AsanDetectStackUseAfterReturnMode UseAfterReturn;
 };
 
 class ModuleAddressSanitizer {
@@ -1227,10 +1238,11 @@
   return GlobalsMetadata(M);
 }
 
-AddressSanitizerPass::AddressSanitizerPass(bool CompileKernel, bool Recover,
-   bool UseAfterScope)
+AddressSanitizerPass::AddressSanitizerPass(
+bool CompileKernel, bool Recover, bool UseAfterScope,
+AsanDetectStackUseAfterReturnMode UseAfterReturn)
 : CompileKernel(CompileKernel), Recover(Recover),
-  UseAfterScope(UseAfterScope) {}
+  UseAfterScope(UseAfterScope), UseAfterReturn(UseAfterReturn) {}
 
 PreservedAnalyses AddressSanitizerPass::run(Function ,
 AnalysisManager ) {
@@ -1238,7 +1250,8 @@
   Module  = *F.getParent();
   if (auto *R = MAMProxy.getCachedResult(M)) {
 const TargetLibraryInfo *TLI = (F);
-AddressSanitizer Sanitizer(M, R, CompileKernel, Recover, UseAfterScope);
+AddressSanitizer Sanitizer(M, R, CompileKernel, Recover, UseAfterScope,
+ 

[clang] e0b469f - [clang-cl][sanitizer] Add -fsanitize-address-use-after-return to clang.

2021-06-11 Thread Kevin Athey via cfe-commits

Author: Kevin Athey
Date: 2021-06-11T12:07:35-07:00
New Revision: e0b469ffa142353fc90bfc6eadb638a805ebed75

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

LOG: [clang-cl][sanitizer] Add -fsanitize-address-use-after-return to clang.

Also:
  - add driver test (fsanitize-use-after-return.c)
  - add basic IR test (asan-use-after-return.cpp)
  - (NFC) cleaned up logic for generating table of __asan_stack_malloc
depending on flag.

for issue: https://github.com/google/sanitizers/issues/1394

Reviewed By: vitalybuka

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

Added: 
clang/test/CodeGen/asan-use-after-return.cpp
clang/test/Driver/fsanitize-use-after-return.c

Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Basic/Sanitizers.h
clang/include/clang/Driver/Options.td
clang/include/clang/Driver/SanitizerArgs.h
clang/lib/Basic/Sanitizers.cpp
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/SanitizerArgs.cpp
clang/test/Driver/cl-options.c
llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h
llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index b4699805eb40..e3202cf88756 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -212,6 +212,10 @@ CODEGENOPT(NewStructPathTBAA , 1, 0) ///< Whether or not 
to use enhanced struct-
 CODEGENOPT(SaveTempLabels, 1, 0) ///< Save temporary labels.
 CODEGENOPT(SanitizeAddressUseAfterScope , 1, 0) ///< Enable use-after-scope 
detection
 ///< in AddressSanitizer
+ENUM_CODEGENOPT(SanitizeAddressUseAfterReturn,
+llvm::AsanDetectStackUseAfterReturnMode, 2,
+llvm::AsanDetectStackUseAfterReturnMode::Runtime
+) ///< Set detection mode for stack-use-after-return.
 CODEGENOPT(SanitizeAddressPoisonCustomArrayCookie, 1,
0) ///< Enable poisoning operator new[] which is not a replaceable
   ///< global allocation function in AddressSanitizer

diff  --git a/clang/include/clang/Basic/Sanitizers.h 
b/clang/include/clang/Basic/Sanitizers.h
index 82e5a73dee2e..b12a3b7821d7 100644
--- a/clang/include/clang/Basic/Sanitizers.h
+++ b/clang/include/clang/Basic/Sanitizers.h
@@ -192,6 +192,12 @@ StringRef AsanDtorKindToString(llvm::AsanDtorKind kind);
 
 llvm::AsanDtorKind AsanDtorKindFromString(StringRef kind);
 
+StringRef AsanDetectStackUseAfterReturnModeToString(
+llvm::AsanDetectStackUseAfterReturnMode mode);
+
+llvm::AsanDetectStackUseAfterReturnMode
+AsanDetectStackUseAfterReturnModeFromString(StringRef modeStr);
+
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_SANITIZERS_H

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6f3169644396..3968aa3431ea 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1587,6 +1587,16 @@ defm sanitize_address_use_after_scope : BoolOption<"f", 
"sanitize-address-use-af
   PosFlag, NegFlag,
   BothFlags<[], " use-after-scope detection in AddressSanitizer">>,
   Group;
+def sanitize_address_use_after_return_EQ
+  : Joined<["-"], "fsanitize-address-use-after-return=">,
+MetaVarName<"">,
+Flags<[CC1Option]>,
+HelpText<"Select the mode of detecting stack use-after-return in 
AddressSanitizer">,
+Group,
+Values<"never,runtime,always">,
+NormalizedValuesScope<"llvm::AsanDetectStackUseAfterReturnMode">,
+NormalizedValues<["Never", "Runtime", "Always"]>,
+MarshallingInfoEnum, 
"Runtime">;
 defm sanitize_address_poison_custom_array_cookie : BoolOption<"f", 
"sanitize-address-poison-custom-array-cookie",
   CodeGenOpts<"SanitizeAddressPoisonCustomArrayCookie">, DefaultFalse,
   PosFlag, NegFlag,

diff  --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index adfc26382f60..63a195fdf753 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -12,6 +12,7 @@
 #include "clang/Driver/Types.h"
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
+#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
 #include 
 #include 
 
@@ -58,6 +59,8 @@ class SanitizerArgs {
   bool ImplicitCfiRuntime = false;
   bool NeedsMemProfRt = false;
   bool HwasanUseAliases = false;
+  llvm::AsanDetectStackUseAfterReturnMode AsanUseAfterReturn =
+  llvm::AsanDetectStackUseAfterReturnMode::Invalid;
 
 public:
   /// Parses the sanitizer arguments from an argument list.

diff  --git a/clang/lib/Basic/Sanitizers.cpp 

[PATCH] D104096: [Clang-Format] Add ReferenceAlignment directive

2021-06-11 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Can you also add tests with the alignment of declarations? We already have such 
for pointers.




Comment at: clang/include/clang/Format/Format.h:2706
+  /// references).
+  ReferenceAlignmentStyle ReferenceAlignment;
+

Please move below the RawStringFormats, same for the comparison etc.



Comment at: clang/unittests/Format/FormatTest.cpp:1243-1244
+  verifyFormat("int *f1(int ) const & = 0;", Style);
+  verifyFormat("int *a = f1();\nint  = f2();\nint & = f3();", Style);
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  Style.ReferenceAlignment = FormatStyle::RAS_Pointer;

MyDeveloperDay wrote:
> could you put each line on its own line. makes it easier to reason about
Please also add the empty line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104096

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


[PATCH] D103888: [ADT] Remove APInt/APSInt toString() std::string variants

2021-06-11 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D103888#2813236 , @RKSimon wrote:

> In D103888#2811305 , @dblaikie 
> wrote:
>
>> Sounds OK.
>>
>> I wouldn't mind the places that can use op<< to use that - not sure 
>> preserving the explicit radix argument is super high value. (I think people 
>> would generally assume that's the default)
>> Possible we could call it `to_string`, is std::to_string meant to be an ADL 
>> extension point, so that other types expose a to_string in their own 
>> associated namespace, etc?
>
> We already have a llvm::to_string(V) wrapper inside ScopedPrinter.h that uses 
> a temp llvm::raw_string_ostream to create the string - do you think that'd be 
> good enough?

That's a weird place for such a general purpose/name template to live... but 
sort of.

What I mean is you could overload to_string to do the efficient thing - rather 
than having to stream it out, then come back to a string again. That way 
generic code would get the efficient behavior without intermediate streams.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103888

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


[PATCH] D88174: [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread Chris Hamilton via Phabricator via cfe-commits
chrish_ericsson_atx added a comment.

I'm aware that this commit triggers one failure in ASan/Windows -- I have 
posted a patch for review to address that here: https://reviews.llvm.org/D104141


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88174

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


[PATCH] D104044: [clang-format] Fix the issue of no empty line after namespace

2021-06-11 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Going the full way, to fix the number of empty lines after/before/between 
elements would be real nice. But even nicer would be if you can state a range.

But I think all those proposed options should not be added in one go.

In D104044#2812399 , @darwin wrote:

> About the issue, let me explain it. It isn't bound to the google style or 
> LLVM style either, since both of them keep the first brace at the same line 
> of the namespace.

Then I would like to use the LLVM style in the tests, otherwise it suggests 
that the issue is a result of using google style.


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D104044

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


[PATCH] D103131: support debug info for alias variable

2021-06-11 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D103131#2811969 , @kamleshbhalui 
wrote:

> In D103131#2811220 , @dblaikie 
> wrote:
>
>> Any idea if the GDB test suite covers this functionality? I'd hope so, but 
>> maybe it doesn't.
>>
>> But yeah, at the moment I don't have any great reason to avoid the imported 
>> declaration form - so happy to go with that.
>
> Hi David,
>
> with imported declaration patch and with current patch(in review or say gcc 
> way) this case works ok(we can print type and value of newname)
> $cat test.c
> int oldname = 1;
> extern int newname attribute((alias("oldname")));
>
> but when we make newname static it works with current patch(in review or say 
> gcc way) but it does not work with imported decl 
> patch(https://reviews.llvm.org/D103131?id=347883).
>
> Should we go with gcc way or am I missing something?
> note: used gdb debugger.

An ideas what's happening when `newname` is static? Is the DWARF any 
different/interesting there? (since the DWARF for imported decl seems like it 
would have nothing to do with the linkange of the alias - since it doesn't 
refer to the actual alias in the object file, etc)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103131

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


[PATCH] D104136: [analyzer] Add better tracking for RetainCountChecker leak warnings

2021-06-11 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp:953-957
+  // Let's traverse...
+  for (const ExplodedNode *N = ExprNode;
+   // ...all the nodes corresponding to the given expression...
+   N != nullptr && N->getStmtForDiagnostics() == E;
+   N = N->getFirstPred()) {

I guess this part should ultimately be written in one place, eg. 
`ExplodedNode::findTag()` or something like that.

I'd also really like to explore the possibility to further limit the variety of 
nodes traversed here. What nodes are typically traversed here? Is it 
checker-tagged nodes or is it purge dead symbol nodes or something else?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104136

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


[PATCH] D104135: [analyzer] Decouple NoteTag from its Factory

2021-06-11 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:777
   static bool classof(const ProgramPointTag *T) {
 return T->getTagKind() == 
   }

It sounds like `NoteTag` `isn't` despite inheriting from it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104135

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


[PATCH] D104082: [CodeGen] Don't create a fake FunctionDecl when generating block/block_byref copy/dispose helper functions

2021-06-11 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D104082#2812088 , @ahatanak wrote:

> Also, is it okay to emit the `linkageName`, but not the `name` for the helper 
> functions? It seems okay to me, but I'm not sure.

Not 100% sure - perhaps @aprantl can weigh in on this. If you can find some 
precedent/existing cases where we do that, might help provide some confidence 
(one way I'd do that would be to put an assertion in the CGDebugInfo code that 
makes the choice about which names to add - asserting if only a linkage name is 
added and no non-linkage name - then run check-clang and see what, if any, 
tests fail - that'll identify cases that have this property)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104082

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


[PATCH] D104046: [analyzer] Simplify the process of producing notes for stores

2021-06-11 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 351515.
vsavchenko added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104046

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1214,136 +1214,144 @@
   return FrameSpace->getStackFrame() == LCtx->getStackFrame();
 }
 
+static bool isObjCPointer(const MemRegion *R) {
+  if (R->isBoundable())
+if (const auto *TR = dyn_cast(R))
+  return TR->getValueType()->isObjCObjectPointerType();
+
+  return false;
+}
+
+static bool isObjCPointer(const ValueDecl *D) {
+  return D->getType()->isObjCObjectPointerType();
+}
+
 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
-static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream ,
-  const MemRegion *NewR, SVal V,
-  const MemRegion *OldR, const DeclStmt *DS) {
-  if (NewR->canPrintPretty()) {
-NewR->printPretty(os);
-os << " ";
-  }
-
-  if (V.getAs()) {
-bool b = false;
-if (NewR->isBoundable()) {
-  if (const auto *TR = dyn_cast(NewR)) {
-if (TR->getValueType()->isObjCObjectPointerType()) {
-  os << action << "nil";
-  b = true;
-}
-  }
-}
-if (!b)
-  os << action << "a null pointer value";
-
-  } else if (auto CVal = V.getAs()) {
-os << action << CVal->getValue();
-  } else if (OldR && OldR->canPrintPretty()) {
-os << action << "the value of ";
-OldR->printPretty(os);
-  } else if (DS) {
-if (V.isUndef()) {
-  if (isa(NewR)) {
+static void showBRDiagnostics(llvm::raw_svector_ostream , StoreInfo SI) {
+  const bool HasPrefix = SI.Dest->canPrintPretty();
+
+  if (HasPrefix) {
+SI.Dest->printPretty(OS);
+OS << " ";
+  }
+
+  const char *Action = nullptr;
+
+  switch (SI.StoreKind) {
+  case StoreInfo::Initialization:
+Action = HasPrefix ? "initialized to " : "Initializing to ";
+break;
+  case StoreInfo::BlockCapture:
+Action = HasPrefix ? "captured by block as " : "Captured by block as ";
+break;
+  default:
+llvm_unreachable("Unexpected store kind");
+  }
+
+  if (SI.Value.getAs()) {
+OS << Action << (isObjCPointer(SI.Dest) ? "nil" : "a null pointer value");
+
+  } else if (auto CVal = SI.Value.getAs()) {
+OS << Action << CVal->getValue();
+
+  } else if (SI.Origin && SI.Origin->canPrintPretty()) {
+OS << Action << "the value of ";
+SI.Origin->printPretty(OS);
+
+  } else if (SI.StoreKind == StoreInfo::Initialization) {
+// We don't need to check here, all these conditions were
+// checked by StoreSiteFinder, when it figured out that it is
+// initialization.
+const auto *DS =
+cast(SI.StoreSite->getLocationAs()->getStmt());
+
+if (SI.Value.isUndef()) {
+  if (isa(SI.Dest)) {
 const auto *VD = cast(DS->getSingleDecl());
+
 if (VD->getInit()) {
-  os << (NewR->canPrintPretty() ? "initialized" : "Initializing")
+  OS << (HasPrefix ? "initialized" : "Initializing")
  << " to a garbage value";
 } else {
-  os << (NewR->canPrintPretty() ? "declared" : "Declaring")
+  OS << (HasPrefix ? "declared" : "Declaring")
  << " without an initial value";
 }
   }
 } else {
-  os << (NewR->canPrintPretty() ? "initialized" : "Initialized") << " here";
+  OS << (HasPrefix ? "initialized" : "Initialized") << " here";
 }
   }
 }
 
 /// Display diagnostics for passing bad region as a parameter.
-static void showBRParamDiagnostics(llvm::raw_svector_ostream ,
-   const VarRegion *VR, SVal V,
-   const MemRegion *ValueR) {
+static void showBRParamDiagnostics(llvm::raw_svector_ostream ,
+   StoreInfo SI) {
+  const auto *VR = cast(SI.Dest);
   const auto *Param = cast(VR->getDecl());
 
-  os << "Passing ";
+  OS << "Passing ";
+
+  if (SI.Value.getAs()) {
+OS << (isObjCPointer(Param) ? "nil object reference"
+: "null pointer value");
+
+  } else if (SI.Value.isUndef()) {
+OS << "uninitialized value";
+
+  } else if (auto CI = SI.Value.getAs()) {
+OS << "the value " << CI->getValue();
+
+  } else if (SI.Origin && SI.Origin->canPrintPretty()) {
+SI.Origin->printPretty(OS);
 
-  if (V.getAs()) {
-if (Param->getType()->isObjCObjectPointerType())
-  os << "nil object reference";
-else
-  os << "null pointer value";
-  } else if (V.isUndef()) {
-os << "uninitialized value";
-  

[PATCH] D103644: [analyzer] Refactor StoreSiteFinder and extract DefaultStoreHandler

2021-06-11 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 351512.
vsavchenko marked 2 inline comments as done.
vsavchenko added a comment.

Fix review remarks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103644

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1232,12 +1232,7 @@
   SVal V;
   bool Satisfied = false;
 
-  /// If the visitor is tracking the value directly responsible for the
-  /// bug, we are going to employ false positive suppression.
-  bool EnableNullFPSuppression;
-
-  using TrackingKind = bugreporter::TrackingKind;
-  TrackingKind TKind;
+  TrackingOptions Options;
   const StackFrameContext *OriginSFC;
 
 public:
@@ -1252,11 +1247,9 @@
   ///this visitor can prevent that without polluting the bugpath too
   ///much.
   StoreSiteFinder(bugreporter::TrackerRef ParentTracker, KnownSVal V,
-  const MemRegion *R, bool InEnableNullFPSuppression,
-  TrackingKind TKind,
+  const MemRegion *R, TrackingOptions Options,
   const StackFrameContext *OriginSFC = nullptr)
-  : TrackingBugReporterVisitor(ParentTracker), R(R), V(V),
-EnableNullFPSuppression(InEnableNullFPSuppression), TKind(TKind),
+  : TrackingBugReporterVisitor(ParentTracker), R(R), V(V), Options(Options),
 OriginSFC(OriginSFC) {
 assert(R);
   }
@@ -1273,8 +1266,8 @@
   ID.AddPointer();
   ID.AddPointer(R);
   ID.Add(V);
-  ID.AddInteger(static_cast(TKind));
-  ID.AddBoolean(EnableNullFPSuppression);
+  ID.AddInteger(static_cast(Options.Kind));
+  ID.AddBoolean(Options.EnableNullFPSuppression);
 }
 
 /// Returns true if \p N represents the DeclStmt declaring and initializing
@@ -1533,8 +1526,7 @@
 if (!IsParam)
   InitE = InitE->IgnoreParenCasts();
 
-getParentTracker().track(InitE, StoreSite,
- {TKind, EnableNullFPSuppression});
+getParentTracker().track(InitE, StoreSite, Options);
   }
 
   // Let's try to find the region where the value came from.
@@ -1605,7 +1597,7 @@
 }
   }
 
-  if (TKind == TrackingKind::Condition &&
+  if (Options.Kind == TrackingKind::Condition && OriginSFC &&
   !OriginSFC->isParentOf(StoreSite->getStackFrame()))
 return nullptr;
 
@@ -1613,60 +1605,41 @@
   SmallString<256> sbuf;
   llvm::raw_svector_ostream os(sbuf);
 
+  StoreInfo SI = {StoreInfo::Assignment, // default kind
+  StoreSite,
+  InitE,
+  V,
+  R,
+  OldRegion};
+
   if (Optional PS = StoreSite->getLocationAs()) {
 const Stmt *S = PS->getStmt();
-const char *action = nullptr;
 const auto *DS = dyn_cast(S);
 const auto *VR = dyn_cast(R);
 
 if (DS) {
-  action = R->canPrintPretty() ? "initialized to " :
- "Initializing to ";
+  SI.StoreKind = StoreInfo::Initialization;
 } else if (isa(S)) {
-  action = R->canPrintPretty() ? "captured by block as " :
- "Captured by block as ";
+  SI.StoreKind = StoreInfo::BlockCapture;
   if (VR) {
 // See if we can get the BlockVarRegion.
 ProgramStateRef State = StoreSite->getState();
 SVal V = StoreSite->getSVal(S);
 if (const auto *BDR =
-  dyn_cast_or_null(V.getAsRegion())) {
+dyn_cast_or_null(V.getAsRegion())) {
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
-if (auto KV = State->getSVal(OriginalR).getAs())
-  getParentTracker().track(
-  *KV, OriginalR, {TKind, EnableNullFPSuppression}, OriginSFC);
+getParentTracker().track(State->getSVal(OriginalR), OriginalR,
+ Options, OriginSFC);
   }
 }
   }
 }
-if (action)
-  showBRDiagnostics(action, os, R, V, OldRegion, DS);
-
-  } else if (StoreSite->getLocation().getAs()) {
-if (const auto *VR = dyn_cast(R))
-  showBRParamDiagnostics(os, VR, V, OldRegion);
+  } else if (SI.StoreSite->getLocation().getAs() &&
+ isa(SI.Dest)) {
+SI.StoreKind = StoreInfo::CallArgument;
   }
 
-  if (os.str().empty())
-showBRDefaultDiagnostics(os, R, V, OldRegion);
-
-  if (TKind == bugreporter::TrackingKind::Condition)
-os << WillBeUsedForACondition;
-
-  // Construct a new PathDiagnosticPiece.
-  ProgramPoint P = StoreSite->getLocation();
-  PathDiagnosticLocation L;
-  if (P.getAs() && InitE)
-L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
- 

[PATCH] D103750: [analyzer] Handle std::make_unique for SmartPtrModeling

2021-06-11 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:201-202
+const TypedValueRegion *TVR = llvm::dyn_cast(ThisRegion);
+assert(TVR && "expected std::make_unique to return a std::unique_ptr "
+  "object (which is typed)");
+const QualType InnerPtrType =

Untyped region isn't a region without a type; everything has a type. Untyped 
region is when we //don't know// the type. A typical situation that produces 
untyped region is when the region comes in through a void pointer.

I vaguely remember that one way to trick your specific code may be to do
```lang=c++
std::unique_ptr foo() {
  return make_unique(123);
}
```
which will RVO into an unknown region. I also wouldn't rely on it being typed 
in all other cases.

A much safer way to access the inner pointer type would be to query the 
function's template parameter.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:214-217
+auto  = State->getStateManager().getOwningEngine();
+State = Engine.updateObjectsUnderConstruction(
+*ThisRegionOpt, nullptr, State, C.getLocationContext(),
+Call.getConstructionContext(), {});

I suggest a `TODO: ExprEngine should do this for us.`.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:219
+
+C.addTransition(State);
+return true;

Do we need a note here as well? I guess we don't because we'll never emit null 
dereference reports against a non-null pointer. But if we later emit more 
sophisticated bug reports, we might need one. Maybe leave a comment?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103750

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


[PATCH] D103936: [compiler-rt][hwasan] Define fuchsia implementations of required hwasan functions

2021-06-11 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added inline comments.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:29
+
+uptr kHighMemEnd;
+uptr kHighMemBeg;

mcgrathr wrote:
> These need comments about what they are and why they need to exist as runtime 
> variables at all.
`kHighMemEnd` and `kHighMemBeg` are used only by `MemIsApp` which is only used 
in `hwasan_thread.cpp` for some debugging checks:

```
  if (stack_bottom_) {
int local;
CHECK(AddrIsInStack((uptr)));
CHECK(MemIsApp(stack_bottom_));
CHECK(MemIsApp(stack_top_ - 1));
  }
```

Rather than having these, we could just use their values 
(`__sanitizer::ShadowBounds.memory_limit - 1` and 
`__sanitizer::ShadowBounds.shadow_limit`) directly in `MemIsApp` to avoid these 
globals.

`kAliasRegionStart` is used in `HwasanAllocatorInit` for setting up the 
allocator, but is only relevant for an experimental x86 implementation that 
uses page aliasing for placing tags in heap allocations (see D98875). I didn't 
look too much into   the machinery for this since I didn't think we would be 
using hwasan for x86 anytime soon, but we can explore this now if we want to 
plan ahead. We could also make it such that this is just defined as 0 on x86 
platforms, similar to `SHADOW_OFFSET` in asan.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:34
+bool InitShadow() {
+  __hwasan_shadow_memory_dynamic_address = 0;
+

mcgrathr wrote:
> What actually refers to this?
> The optimal implementation for Fuchsia would just know everywhere at compile 
> time that it's a fized value.
> If there's reason for the runtime variable to exist at all, it should have 
> comments.
It's only used for converting between application memory and shadow memory:

```
// hwasan_mapping.h
inline uptr MemToShadow(uptr untagged_addr) {
  return (untagged_addr >> kShadowScale) +
 __hwasan_shadow_memory_dynamic_address;
}
inline uptr ShadowToMem(uptr shadow_addr) {
  return (shadow_addr - __hwasan_shadow_memory_dynamic_address) << kShadowScale;
}
```

Perhaps we could have something similar to the `SHADOW_OFFSET` macro in asan 
where it can be defined to either a constant or 
`__hwasan_shadow_memory_dynamic_address` on different platforms and these 
functions can just use the macro.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:37
+  // This initializes __sanitizer::ShadowBounds.
+  kHighMemEnd = GetMaxUserVirtualAddress();
+  kHighMemBeg = __sanitizer::ShadowBounds.shadow_limit;

mcgrathr wrote:
> Isn't this `__sanitizer::GetMaxUserVirtualAddress()` ?
It is. It looks there's

```
namespace __hwasan {
using namespace __sanitizer;
}
```

in `sanitizer_internal_defs.h` included through `hwasan.h`. Will add the 
`__sanitizer::` bits.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:59
+
+// -- TSD  {{{
+

mcgrathr wrote:
> This comment isn't very meaningful, since it only really applies to the two 
> functions after these three.
> This is also a weird comment syntax not used elsewhere in this file.
> 
Removed.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:62
+extern "C" {
+void __sanitizer_thread_start_hook(void *hook, thrd_t self) {
+  hwasanThreadList().CreateCurrentThread()->InitRandomState();

mcgrathr wrote:
> As we discussed before, this is insufficient plumbing for the thread tracking.
> It probably makes sense to either do all the necessary refactoring for the 
> thread tracking plumbing first, or else start this file simpler without 
> anything related to thread tracking, and then add more stuff later.
> 
> Also, as a matter of style it's best to define C++ functions in the __hwasan 
> namespace or a local anonymous namespace, and then have an `extern "C"` block 
> at the end where the libc hook API implementation functions are just simple 
> wrapper calls with no more than a line or two in them.
> 
> See asan_fuchsia.cpp for a good example of how to arrange the hook functions.
> 
> 
Moved these in D104085 and left the remaining functions here.



Comment at: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp:74
+
+void __sanitizer_exit() { __hwasan::HwasanAtExit(); }
+}  // extern "C"

mcgrathr wrote:
> This is not the name of the hook.  `__sanitizer_process_exit_hook` is the 
> name of the hook.  This is a good example of a simple wrapper.
> 
> However, it's unclear whether this should use the exit hook or not.  We don't 
> use that hook in asan, we just use its normal atexit method.  In hwasan, the 
> atexit hook doesn't really do much.  ReportStats is a no-op in hwasan, and 
> DumpProcessMap is always a no-op on Fuchsia anyway.  So all it's really doing 
> in practice is changing the exit code, which is what's a perfect fit for the 
> sanitizer hook.
> 
Ah, if the functions in `HwasanAtExit` are no-ops and it only sets the exit 

[PATCH] D103936: [compiler-rt][hwasan] Define fuchsia implementations of required hwasan functions

2021-06-11 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan updated this revision to Diff 351510.
leonardchan marked an inline comment as done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103936

Files:
  compiler-rt/lib/hwasan/CMakeLists.txt
  compiler-rt/lib/hwasan/hwasan_fuchsia.cpp


Index: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp
===
--- /dev/null
+++ compiler-rt/lib/hwasan/hwasan_fuchsia.cpp
@@ -0,0 +1,69 @@
+//===-- hwasan_fuchsia.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
+//
+//===--===//
+///
+/// \file
+/// This file is a part of HWAddressSanitizer and contains Fuchsia-specific
+/// code.
+///
+//===--===//
+
+#include "sanitizer_common/sanitizer_fuchsia.h"
+#if SANITIZER_FUCHSIA
+
+#include "hwasan.h"
+#include "hwasan_interface_internal.h"
+#include "hwasan_report.h"
+#include "hwasan_thread.h"
+#include "hwasan_thread_list.h"
+
+namespace __hwasan {
+
+// This is used by the hwasan allocator when page aliasing on x86 is enabled,
+// but should always remain zero on non-x86 implementations.
+uptr kAliasRegionStart = 0;
+
+bool InitShadow() {
+  __hwasan_shadow_memory_dynamic_address = 0;
+
+  // Call this explicitly to set the ShadowBounds global so we can reference it
+  // now. Otherwise, ShadowBounds will be a zero-initialized global.
+  ShadowBounds = __sanitizer_shadow_bounds();
+  CHECK_NE(__sanitizer::ShadowBounds.shadow_limit, 0);
+
+  return true;
+}
+
+bool MemIsApp(uptr p) {
+  CHECK(GetTagFromPointer(p) == 0);
+  return __sanitizer::ShadowBounds.shadow_limit <= p &&
+ p <= __sanitizer::GetMaxUserVirtualAddress();
+}
+
+// Not implemented because Fuchsia does not use signal handlers.
+void HwasanOnDeadlySignal(int signo, void *info, void *context) {}
+
+// Not implemented because Fuchsia does not use interceptors.
+void InitializeInterceptors() {}
+
+// Not implemented because this is only relevant for Android.
+void AndroidTestTlsSlot() {}
+
+// TSD was normally used on linux as a means of calling the hwasan thread exit
+// handler passed to pthread_key_create. This is not needed on Fuchsia because
+// we will be using __sanitizer_thread_exit_hook.
+void HwasanTSDInit() {}
+void HwasanTSDThreadInit() {}
+
+// On linux, this just would call `atexit(HwasanAtExit)`. The functions in
+// HwasanAtExit are unimplemented for Fuchsia and effectively no-ops, so this
+// function is unneeded.
+void InstallAtExitHandler() {}
+
+}  // namespace __hwasan
+
+#endif  // SANITIZER_FUCHSIA
Index: compiler-rt/lib/hwasan/CMakeLists.txt
===
--- compiler-rt/lib/hwasan/CMakeLists.txt
+++ compiler-rt/lib/hwasan/CMakeLists.txt
@@ -7,6 +7,7 @@
   hwasan_allocation_functions.cpp
   hwasan_dynamic_shadow.cpp
   hwasan_exceptions.cpp
+  hwasan_fuchsia.cpp
   hwasan_globals.cpp
   hwasan_interceptors.cpp
   hwasan_interceptors_vfork.S


Index: compiler-rt/lib/hwasan/hwasan_fuchsia.cpp
===
--- /dev/null
+++ compiler-rt/lib/hwasan/hwasan_fuchsia.cpp
@@ -0,0 +1,69 @@
+//===-- hwasan_fuchsia.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
+//
+//===--===//
+///
+/// \file
+/// This file is a part of HWAddressSanitizer and contains Fuchsia-specific
+/// code.
+///
+//===--===//
+
+#include "sanitizer_common/sanitizer_fuchsia.h"
+#if SANITIZER_FUCHSIA
+
+#include "hwasan.h"
+#include "hwasan_interface_internal.h"
+#include "hwasan_report.h"
+#include "hwasan_thread.h"
+#include "hwasan_thread_list.h"
+
+namespace __hwasan {
+
+// This is used by the hwasan allocator when page aliasing on x86 is enabled,
+// but should always remain zero on non-x86 implementations.
+uptr kAliasRegionStart = 0;
+
+bool InitShadow() {
+  __hwasan_shadow_memory_dynamic_address = 0;
+
+  // Call this explicitly to set the ShadowBounds global so we can reference it
+  // now. Otherwise, ShadowBounds will be a zero-initialized global.
+  ShadowBounds = __sanitizer_shadow_bounds();
+  CHECK_NE(__sanitizer::ShadowBounds.shadow_limit, 0);
+
+  return true;
+}
+
+bool MemIsApp(uptr p) {
+  CHECK(GetTagFromPointer(p) == 0);
+  return __sanitizer::ShadowBounds.shadow_limit <= p &&
+ p <= 

[PATCH] D101479: [Driver] Support libc++ in MSVC

2021-06-11 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D101479#2813797 , @phosek wrote:

> In D101479#2813724 , @mstorsjo 
> wrote:
>
>> Couldn’t this commit have been kept in, and just reverting the one for using 
>> it in the fuchsia cmake cache? (I’m not using this particular commit myself, 
>> just observing.)
>
> The problem is that there's no way to configure the default libc++ on a 
> per-target basis. We want to use libc++ as a default for all targets that 
> support it, so for example even if you're compiling on Windows but targeting 
> Fuchsia or Linux. Unfortunately, with this change that triggers D103947 
>  when compiling compiler-rt and I don't 
> know how to work around it.
>
> I'd point out that we have the same problem for other defaults, for example 
> if you set lld as the default linker on Darwin, it causes issues because 
> Clang tries to use `lld.ld64` which is not yet usable. We still want to use 
> lld for all other targets, but there's no way to specify that in CMake today 
> which is something we may want to address.

Ah, I see, thanks for explaining - the link between those wasn’t obvious to me.

Yes, that’s indeed a problem with the mechanism of overriding the default 
choices. (FWIW, in llvm-mingw I work around this issue by having small wrapper 
scripts, like -clang, that set the cross target and the defaults I when 
invoking clang - but that’s not very elegant either.)

Clang does have the concept of a config file, named the same a the target 
triple plus “.cfg”, iirc, located next to the compiler binary, that might work 
for setting different defaults per cross target. I haven’t really used that 
much though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101479

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


[PATCH] D103087: [clang-tidy] performances-unnecessary-* checks: Extend isOnlyUsedAsConst to expressions and catch const methods returning non-const references/pointers.

2021-06-11 Thread Felix Berger via Phabricator via cfe-commits
flx added a comment.

In D103087#2793673 , @ymandel wrote:

> I have some concerns about the cost of this checks as it used matching over 
> entire contexts quite extensively.  At this point, the facilities involved 
> seem quite close to doing dataflow analysis and I wonder if you might be 
> better off with a very different implementation. Regardless, have you done 
> any perfomance testing to see the impact on real code?

That's a fair point. Is there prior art in terms of dataflow analysis in 
ClangTidy or LLVM I could take a look at?

In terms of measuring performance, do you have suggestions how to measure this? 
I can add a counter that counts the recursion depth that is reached to see how 
often this happens in practice.

Another idea is to not count const methods from returning mutable pointer or 
reference types as const access. Standard types std::vector and absl::StatusOr 
would not be affected by this restriction, their const accessors return const 
references as well.

I'll hold off on this change until I see more false positives.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103087

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks accepted this revision.
aeubanks added a comment.
This revision is now accepted and ready to land.

Ah, sorry I missed where you mentioned LSR.

If this pass is causing regressions in multiple places, even on X86, then I 
think it does make sense to remove it.
I've added some people that may care about this pass more than me. Maybe wait a 
bit for their feedback, if they have any.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D104136: [analyzer] Add better tracking for RetainCountChecker leak warnings

2021-06-11 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

RetainCountChecker models a group of calls that are interpreted as
"identity" functions.  bugreporter::Tracker couldn't see through
such calls and pick the right argument for tracking.

This commit introduces a new tag that helps to keep this information
from the actual analysis and reuse it later for tracking purposes.

So, in short, when we see a call `foo(x)` that we model as
"identity", we now add a tag that is saying that the result of
`foo(x)` is essentially `x`.  When the tracker, later on, tries to
track value from `foo(x)`, we point out that it should track `x`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104136

Files:
  clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/test/Analysis/Inputs/expected-plists/retain-release.m.objc.plist
  clang/test/Analysis/Inputs/expected-plists/retain-release.m.objcpp.plist
  clang/test/Analysis/osobject-retain-release.cpp

Index: clang/test/Analysis/osobject-retain-release.cpp
===
--- clang/test/Analysis/osobject-retain-release.cpp
+++ clang/test/Analysis/osobject-retain-release.cpp
@@ -536,6 +536,7 @@
 
 void check_dynamic_cast_alias() {
   OSObject *originalPtr = OSObject::generateObject(1);   // expected-note {{Call to method 'OSObject::generateObject' returns an OSObject}}
+ // expected-note@-1 {{'originalPtr' initialized here}}
   OSArray *newPtr = OSDynamicCast(OSArray, originalPtr); // expected-note {{'newPtr' initialized to the value of 'originalPtr'}}
   if (newPtr) {  // expected-note {{'newPtr' is non-null}}
  // expected-note@-1 {{Taking true branch}}
@@ -548,6 +549,7 @@
 
 void check_dynamic_cast_alias_cond() {
   OSObject *originalPtr = OSObject::generateObject(1); // expected-note {{Call to method 'OSObject::generateObject' returns an OSObject}}
+   // expected-note@-1 {{'originalPtr' initialized here}}
   OSArray *newPtr = 0;
   if ((newPtr = OSDynamicCast(OSArray, originalPtr))) { // expected-note {{The value of 'originalPtr' is assigned to 'newPtr'}}
 // expected-note@-1 {{'newPtr' is non-null}}
@@ -561,7 +563,8 @@
 
 void check_dynamic_cast_alias_intermediate() {
   OSObject *originalPtr = OSObject::generateObject(1); // expected-note {{Call to method 'OSObject::generateObject' returns an OSObject of type 'OSObject' with a +1 retain count}}
-  OSObject *intermediate = originalPtr;// TODO: add note here as well
+   // expected-note@-1 {{'originalPtr' initialized here}}
+  OSObject *intermediate = originalPtr;// expected-note {{'intermediate' initialized to the value of 'originalPtr'}}
   OSArray *newPtr = 0;
   if ((newPtr = OSDynamicCast(OSArray, intermediate))) { // expected-note {{The value of 'intermediate' is assigned to 'newPtr'}}
  // expected-note@-1 {{'newPtr' is non-null}}
@@ -575,7 +578,8 @@
 
 void check_dynamic_cast_alias_intermediate_2() {
   OSObject *originalPtr = OSObject::generateObject(1); // expected-note {{Call to method 'OSObject::generateObject' returns an OSObject of type 'OSObject' with a +1 retain count}}
-  OSObject *intermediate = originalPtr;// TODO: add note here as well
+   // expected-note@-1 {{'originalPtr' initialized here}}
+  OSObject *intermediate = originalPtr;// expected-note {{'intermediate' initialized to the value of 'originalPtr'}}
   OSArray *newPtr = 0;
   if ((newPtr = OSDynamicCast(OSArray, intermediate))) { // expected-note {{Value assigned to 'newPtr'}}
  // expected-note@-1 {{'newPtr' is non-null}}
Index: clang/test/Analysis/Inputs/expected-plists/retain-release.m.objcpp.plist
===
--- clang/test/Analysis/Inputs/expected-plists/retain-release.m.objcpp.plist
+++ clang/test/Analysis/Inputs/expected-plists/retain-release.m.objcpp.plist
@@ -25282,6 +25282,35 @@
  message
  Call to function CFCreateSomething returns a Core Foundation object of type CFTypeRef 

[PATCH] D104076: [clang-cl][sanitizer] Add -fsanitize-address-use-after-return to clang.

2021-06-11 Thread Kevin Athey via Phabricator via cfe-commits
kda added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp:2973
   IRBuilder<> IRB(*C);
-  switch (ClUseAfterReturn) {
-  case AsanDetectStackUseAfterReturnMode::Always:
-for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
-  std::string Suffix = itostr(i);
-  AsanStackMallocFunc[i] = M.getOrInsertFunction(
-  kAsanStackMallocAlwaysNameTemplate + Suffix, IntptrTy, IntptrTy);
-  AsanStackFreeFunc[i] =
-  M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
-IRB.getVoidTy(), IntptrTy, IntptrTy);
-}
-break;
-  case AsanDetectStackUseAfterReturnMode::Runtime:
-for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
-  std::string Suffix = itostr(i);
-  AsanStackMallocFunc[i] = M.getOrInsertFunction(
-  kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
-  AsanStackFreeFunc[i] =
-  M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
-IRB.getVoidTy(), IntptrTy, IntptrTy);
-}
-break;
-  case AsanDetectStackUseAfterReturnMode::Never:
-// Do Nothing
-break;
-  case AsanDetectStackUseAfterReturnMode::Invalid:
-// Do Nothing
-break;
+  const char *kMallocNameTemplate = kAsanStackMallocNameTemplate;
+  if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always) {

vitalybuka wrote:
> vitalybuka wrote:
> > vitalybuka wrote:
> > > it looks like unrelated patch
> > could you please fix clang-tidy: warnings
> now we insert functions also for Never and Invalid?
I was trying to only have one loop, since only one thing changes between the 
two.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104076

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


[PATCH] D104076: [clang-cl][sanitizer] Add -fsanitize-address-use-after-return to clang.

2021-06-11 Thread Kevin Athey via Phabricator via cfe-commits
kda updated this revision to Diff 351505.
kda marked 9 inline comments as done.
kda added a comment.

- fixed up conflicting command line parameters.
- only emit asan_stack_malloc calls when needed.
- trimmed namespace ('llvm').
- improved tests.
- Changed default parameters from Never to Runtime.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104076

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/Sanitizers.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/Basic/Sanitizers.cpp
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/asan-use-after-return.cpp
  clang/test/Driver/cl-options.c
  clang/test/Driver/fsanitize-use-after-return.c
  llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -633,17 +633,24 @@
 struct AddressSanitizer {
   AddressSanitizer(Module , const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
-   bool UseAfterScope = false)
+   bool UseAfterScope = false,
+   AsanDetectStackUseAfterReturnMode UseAfterReturn =
+   AsanDetectStackUseAfterReturnMode::Runtime)
   : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
 : CompileKernel),
 Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
-UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
+UseAfterScope(UseAfterScope || ClUseAfterScope),
+UseAfterReturn(ClUseAfterReturn.getNumOccurrences() ? ClUseAfterReturn
+: UseAfterReturn),
+GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
 TargetTriple = Triple(M.getTargetTriple());
 
 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
+
+assert(this->UseAfterReturn != AsanDetectStackUseAfterReturnMode::Invalid);
   }
 
   uint64_t getAllocaSizeInBytes(const AllocaInst ) const {
@@ -727,6 +734,7 @@
   bool CompileKernel;
   bool Recover;
   bool UseAfterScope;
+  AsanDetectStackUseAfterReturnMode UseAfterReturn;
   Type *IntptrTy;
   ShadowMapping Mapping;
   FunctionCallee AsanHandleNoReturnFunc;
@@ -754,11 +762,13 @@
 public:
   static char ID;
 
-  explicit AddressSanitizerLegacyPass(bool CompileKernel = false,
-  bool Recover = false,
-  bool UseAfterScope = false)
+  explicit AddressSanitizerLegacyPass(
+  bool CompileKernel = false, bool Recover = false,
+  bool UseAfterScope = false,
+  AsanDetectStackUseAfterReturnMode UseAfterReturn =
+  AsanDetectStackUseAfterReturnMode::Runtime)
   : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
-UseAfterScope(UseAfterScope) {
+UseAfterScope(UseAfterScope), UseAfterReturn(UseAfterReturn) {
 initializeAddressSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
   }
 
@@ -777,7 +787,7 @@
 const TargetLibraryInfo *TLI =
 ().getTLI(F);
 AddressSanitizer ASan(*F.getParent(), , CompileKernel, Recover,
-  UseAfterScope);
+  UseAfterScope, UseAfterReturn);
 return ASan.instrumentFunction(F, TLI);
   }
 
@@ -785,6 +795,7 @@
   bool CompileKernel;
   bool Recover;
   bool UseAfterScope;
+  AsanDetectStackUseAfterReturnMode UseAfterReturn;
 };
 
 class ModuleAddressSanitizer {
@@ -1227,10 +1238,11 @@
   return GlobalsMetadata(M);
 }
 
-AddressSanitizerPass::AddressSanitizerPass(bool CompileKernel, bool Recover,
-   bool UseAfterScope)
+AddressSanitizerPass::AddressSanitizerPass(
+bool CompileKernel, bool Recover, bool UseAfterScope,
+AsanDetectStackUseAfterReturnMode UseAfterReturn)
 : CompileKernel(CompileKernel), Recover(Recover),
-  UseAfterScope(UseAfterScope) {}
+  UseAfterScope(UseAfterScope), UseAfterReturn(UseAfterReturn) {}
 
 PreservedAnalyses AddressSanitizerPass::run(Function ,
 AnalysisManager ) {
@@ -1238,7 +1250,8 @@
   Module  = *F.getParent();
   if (auto *R = MAMProxy.getCachedResult(M)) {
 const TargetLibraryInfo *TLI = (F);
-AddressSanitizer Sanitizer(M, R, CompileKernel, Recover, UseAfterScope);
+AddressSanitizer Sanitizer(M, R, 

[PATCH] D104135: [analyzer] Decouple NoteTag from its Factory

2021-06-11 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This allows us to create other types of tags that carry useful
bits of information alongside.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104135

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/StaticAnalyzer/Core/CoreEngine.cpp

Index: clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
@@ -219,13 +219,14 @@
   // and we're taking the path that skips virtual base constructors.
   if (L.getSrc()->getTerminator().isVirtualBaseBranch() &&
   L.getDst() == *L.getSrc()->succ_begin()) {
-ProgramPoint P = L.withTag(getNoteTags().makeNoteTag(
+ProgramPoint P = L.withTag(getDataTags().make(
 [](BugReporterContext &, PathSensitiveBugReport &) -> std::string {
   // TODO: Just call out the name of the most derived class
   // when we know it.
   return "Virtual base initialization skipped because "
  "it has already been handled by the most derived class";
-}, /*IsPrunable=*/true));
+},
+/*IsPrunable=*/true));
 // Perform the transition.
 ExplodedNodeSet Dst;
 NodeBuilder Bldr(Pred, Dst, BuilderCtx);
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -428,8 +428,7 @@
   SymbolManager () { return SymMgr; }
   MemRegionManager () { return MRMgr; }
 
-  NoteTag::Factory () { return Engine.getNoteTags(); }
-
+  DataTag::Factory () { return Engine.getDataTags(); }
 
   // Functions for external checking of whether we have unfinished work
   bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -96,9 +96,10 @@
   /// (This data is owned by AnalysisConsumer.)
   FunctionSummariesTy *FunctionSummaries;
 
-  /// Add path note tags along the path when we see that something interesting
-  /// is happening. This field is the allocator for such tags.
-  NoteTag::Factory NoteTags;
+  /// Add path tags with some useful data along the path when we see that
+  /// something interesting is happening. This field is the allocator for such
+  /// tags.
+  DataTag::Factory DataTags;
 
   void generateNode(const ProgramPoint ,
 ProgramStateRef State,
@@ -200,7 +201,7 @@
   /// Enqueue a single node created as a result of statement processing.
   void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx);
 
-  NoteTag::Factory () { return NoteTags; }
+  DataTag::Factory () { return DataTags; }
 };
 
 // TODO: Turn into a class.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -255,7 +255,7 @@
   ///to omit the note from the report if it would make the displayed
   ///bug path significantly shorter.
   const NoteTag *getNoteTag(NoteTag::Callback &, bool IsPrunable = false) {
-return Eng.getNoteTags().makeNoteTag(std::move(Cb), IsPrunable);
+return Eng.getDataTags().make(std::move(Cb), IsPrunable);
   }
 
   /// A shorthand version of getNoteTag that doesn't require you to accept
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -725,14 +725,43 @@
   }
 };
 
+/// The tag that carries some information with it.
+///
+/// It can be valuable to produce tags with some bits of information and later
+/// reuse them for a better diagnostic.
+///
+/// Please make sure that derived class' constuctor is 

[PATCH] D101479: [Driver] Support libc++ in MSVC

2021-06-11 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

In D101479#2813724 , @mstorsjo wrote:

> Couldn’t this commit have been kept in, and just reverting the one for using 
> it in the fuchsia cmake cache? (I’m not using this particular commit myself, 
> just observing.)

The problem is that there's no way to configure the default libc++ on a 
per-target basis. We want to use libc++ as a default for all targets that 
support it, so for example even if you're compiling on Windows but targeting 
Fuchsia or Linux. Unfortunately, with this change that triggers D103947 
 when compiling compiler-rt and I don't know 
how to work around it.

I'd point out that we have the same problem for other defaults, for example if 
you set lld as the default linker on Darwin, it causes issues because Clang 
tries to use `lld.ld64` which is not yet usable. We still want to use lld for 
all other targets, but there's no way to specify that in CMake today which is 
something we may want to address.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101479

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


[PATCH] D104044: [clang-format] Fix the issue of no empty line after namespace

2021-06-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

My point being there is inconsistency between how different types of blocks of 
code are handled, and rather than trying to fix another corner case maybe we 
should take a more holistic approach, all these KeepEmptyLines and 
EmptyLineAfterXXX options and what you'll need in order to fix this issue are 
all addressing what is effectively the same issue, and that is that the 
addition and/or removal of empty lines is a little hit or miss depending on 
your combination and permutation of settings and the type of block

I personally would prefer we took a step back and asked ourselves if we are 
really facing a bug here or just different people desiring different 
functionality?

Whatever the rules are for an inner class, I don't particularly see they are 
much different for a class in a namespace (which I why I picked that example to 
demonstrate the point), we won't resolve that inconsistency in a way that will 
satisfy everyone without having a more powerful mechanism.

If you are thinking you want to just fix your bug then I'd be saying that it 
SHOULD remove the empty lines (including the one prior to the } // namespace 
MyLibrary, having said that I'm slightly struggling to understand why

  class Foo {
  
  
  
  
  class Bar {};
  };

isn't conforming to the setting of MaxEmptyLinesToKeep if I set it to 1 where

  namespace MyLibrary {
  
  class Tool {};
  }  // namespace MyLibrary

is

i.e. set MaxEmptyLinesToKeep  to 0 and

it gets formatted as:

  namespace MyLibrary {
  class Tool {};
  }  // namespace MyLibrary

We don't normally just review tests, but what were you thinking the fix should 
be?


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D104044

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D104099#2813743 , @aeubanks wrote:

> Which pass that comes after SpeculateAroundPHIs in the X86 pipeline (either 
> in the optimization or codegen) would undo its effects?

As i have wrote in some other review, the pass i saw as causing problems is LSR.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D88174: [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread Chris Hamilton 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 rGce44fe199bbf: [Sema] Address-space sensitive check for 
unbounded arrays (v2) (authored by chrish_ericsson_atx).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88174

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/const-eval.c
  clang/test/Sema/unbounded-array-bounds.c
  clang/test/SemaCXX/constant-expression-cxx14.cpp

Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1027,8 +1027,9 @@
 }
 
 constexpr void PR28739(int n) { // expected-error {{never produces a constant}}
-  int *p = 
+  int *p =   // expected-note {{array 'p' declared here}}
   p += (__int128)(unsigned long)-1; // expected-note {{cannot refer to element 18446744073709551615 of non-array object in a constant expression}}
+  // expected-warning@-1 {{the pointer incremented by 18446744073709551615 refers past the last possible element for an array in 64-bit address space containing 32-bit (4-byte) elements (max possible 4611686018427387904 elements)}}
 }
 
 constexpr void Void(int n) {
Index: clang/test/Sema/unbounded-array-bounds.c
===
--- /dev/null
+++ clang/test/Sema/unbounded-array-bounds.c
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-X86-ADDR64 %s  \
+// RUN:  --implicit-check-not 'past the last possible element'
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu   -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-I386-ADDR32 %s \
+// RUN:  --implicit-check-not 'past the last possible element'
+// RUN: %clang_cc1 -triple avr-pc-linux-gnu-fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-AVR-ADDR16 %s  \
+// RUN:  --implicit-check-not 'past the last possible element'
+
+struct S {
+  long long a;
+  char b;
+  long long c;
+  short d;
+};
+
+struct S s[];
+
+void f1() {
+  ++s[3].a;
+  ++s[7073650413200313099].b;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: array index 7073650413200313099 refers past the last possible element for an array in 64-bit address space containing 256-bit (32-byte) elements (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 178956970 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+  ++s[7073650].c;
+  // CHECK-AVR-ADDR16:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+}
+
+long long ll[];
+
+void f2() {
+  ++ll[3];
+  ++ll[2705843009213693952];
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 64-bit {{.*}} (max possible 2305843009213693952 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 536870912 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 8192 elements)
+  ++ll[847073650];
+  // CHECK-I386-ADDR32: :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 536870912 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 8192 elements)
+}
+
+void f3(struct S p[]) {
+  ++p[3].a;
+  ++p[7073650413200313099].b;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 64-bit {{.*}} (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 178956970 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+  ++p[7073650].c;
+  // CHECK-AVR-ADDR16:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+}
+
+void f4(struct S *p) {
+  p += 3;
+  p += 7073650413200313099;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:3: warning: the pointer incremented by 7073650413200313099 refers past the last possible element for an array in 64-bit address space containing 256-bit (32-byte) elements (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:3: warning: {{.*}} past the last possible element {{.*}} 

[clang] ce44fe1 - [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread via cfe-commits

Author: eahcmrh
Date: 2021-06-11T19:34:03+02:00
New Revision: ce44fe199bbfd4b5a44764b678c431fdc117116a

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

LOG: [Sema] Address-space sensitive check for unbounded arrays (v2)

Check applied to unbounded (incomplete) arrays and pointers to spot
cases where the computed address is beyond the largest possible
addressable extent of the array, based on the address space in which the
array is delcared, or which the pointer refers to.

Check helps to avoid cases of nonsense pointer math and array indexing
which could lead to linker failures or runtime exceptions.  Of
particular interest when building for embedded systems with small
address spaces.

This is version 2 of this patch -- version 1 had some testing issues
due to a sign error in existing code.  That error is corrected and
lit test for this chagne is extended to verify the fix.

Originally reviewed/accepted by: aaron.ballman
Original revision: https://reviews.llvm.org/D86796

Reviewed By: aaron.ballman, ebevhan

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

Added: 
clang/test/Sema/unbounded-array-bounds.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/const-eval.c
clang/test/SemaCXX/constant-expression-cxx14.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index af242cffbe7de..c07e6f9d7421a 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9176,6 +9176,14 @@ def warn_array_index_precedes_bounds : Warning<
 def warn_array_index_exceeds_bounds : Warning<
   "array index %0 is past the end of the array (which contains %1 "
   "element%s2)">, InGroup;
+def warn_ptr_arith_exceeds_max_addressable_bounds : Warning<
+  "the pointer incremented by %0 refers past the last possible element for an 
array in %1-bit "
+  "address space containing %2-bit (%3-byte) elements (max possible %4 
element%s5)">,
+  InGroup;
+def warn_array_index_exceeds_max_addressable_bounds : Warning<
+  "array index %0 refers past the last possible element for an array in %1-bit 
"
+  "address space containing %2-bit (%3-byte) elements (max possible %4 
element%s5)">,
+  InGroup;
 def note_array_declared_here : Note<
   "array %0 declared here">;
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 91498293d60e2..a9915cb6d720e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14536,11 +14536,11 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   const ConstantArrayType *ArrayTy =
   Context.getAsConstantArrayType(BaseExpr->getType());
 
-  if (!ArrayTy)
-return;
-
-  const Type *BaseType = ArrayTy->getElementType().getTypePtr();
-  if (EffectiveType->isDependentType() || BaseType->isDependentType())
+  const Type *BaseType =
+  ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
+  bool IsUnboundedArray = (BaseType == nullptr);
+  if (EffectiveType->isDependentType() ||
+  (!IsUnboundedArray && BaseType->isDependentType()))
 return;
 
   Expr::EvalResult Result;
@@ -14548,8 +14548,10 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
 return;
 
   llvm::APSInt index = Result.Val.getInt();
-  if (IndexNegated)
+  if (IndexNegated) {
+index.setIsUnsigned(false);
 index = -index;
+  }
 
   const NamedDecl *ND = nullptr;
   if (const DeclRefExpr *DRE = dyn_cast(BaseExpr))
@@ -14557,6 +14559,69 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   if (const MemberExpr *ME = dyn_cast(BaseExpr))
 ND = ME->getMemberDecl();
 
+  if (IsUnboundedArray) {
+if (index.isUnsigned() || !index.isNegative()) {
+  const auto  = getASTContext();
+  unsigned AddrBits =
+  ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
+  EffectiveType->getCanonicalTypeInternal()));
+  if (index.getBitWidth() < AddrBits)
+index = index.zext(AddrBits);
+  CharUnits ElemCharUnits = ASTC.getTypeSizeInChars(EffectiveType);
+  llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits.getQuantity());
+  // If index has more active bits than address space, we already know
+  // we have a bounds violation to warn about.  Otherwise, compute
+  // address of (index + 1)th element, and warn about bounds violation
+  // only if that address exceeds address space.
+  if (index.getActiveBits() <= AddrBits) {
+bool Overflow;
+llvm::APInt Product(index);
+Product += 1;
+Product = Product.umul_ov(ElemBytes, 

[PATCH] D103184: [AArch64] handle -Wa,-march=

2021-06-11 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

In D103184#2804241 , @jcai19 wrote:

> In D103184#2803768 , @thakis wrote:
>
>> FWIW the failure goes away locally if I revert this change here, so it's 
>> definitely due to this change here.
>>
>> Things have been red for a while, probably good to revert while you 
>> investigate by this point.
>
> Sorry for the delay but my macbook had some issues so I just finished 
> building LLVM, but I can't seem to reproduce the test failure locally 
> (neither by running the test directly with llvm-lit nor with `ninja 
> check-clang`). In fact I don't quite understand why this test failed.  Like 
> @nickdesaulniers mentioned the build failure should have been fixed in 
> https://reviews.llvm.org/rG76d9bc72784d88f4dd57b9939e52c73739438af5 for a 
> different patch. Do you mind sharing the instructions you used to reproduce 
> the test failure? Thanks.

Did you try on a mac with a m1 processor?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103184

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

Which pass that comes after SpeculateAroundPHIs in the X86 pipeline (either in 
the optimization or codegen) would undo its effects?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D88174: [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread Chris Hamilton via Phabricator via cfe-commits
chrish_ericsson_atx updated this revision to Diff 351491.
chrish_ericsson_atx added a comment.

Corrected APSInt.toString() usage to comply with intervening change 
61cdaf66fe22be2b5 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88174

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/const-eval.c
  clang/test/Sema/unbounded-array-bounds.c
  clang/test/SemaCXX/constant-expression-cxx14.cpp

Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1027,8 +1027,9 @@
 }
 
 constexpr void PR28739(int n) { // expected-error {{never produces a constant}}
-  int *p = 
+  int *p =   // expected-note {{array 'p' declared here}}
   p += (__int128)(unsigned long)-1; // expected-note {{cannot refer to element 18446744073709551615 of non-array object in a constant expression}}
+  // expected-warning@-1 {{the pointer incremented by 18446744073709551615 refers past the last possible element for an array in 64-bit address space containing 32-bit (4-byte) elements (max possible 4611686018427387904 elements)}}
 }
 
 constexpr void Void(int n) {
Index: clang/test/Sema/unbounded-array-bounds.c
===
--- /dev/null
+++ clang/test/Sema/unbounded-array-bounds.c
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-X86-ADDR64 %s  \
+// RUN:  --implicit-check-not 'past the last possible element'
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu   -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-I386-ADDR32 %s \
+// RUN:  --implicit-check-not 'past the last possible element'
+// RUN: %clang_cc1 -triple avr-pc-linux-gnu-fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-AVR-ADDR16 %s  \
+// RUN:  --implicit-check-not 'past the last possible element'
+
+struct S {
+  long long a;
+  char b;
+  long long c;
+  short d;
+};
+
+struct S s[];
+
+void f1() {
+  ++s[3].a;
+  ++s[7073650413200313099].b;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: array index 7073650413200313099 refers past the last possible element for an array in 64-bit address space containing 256-bit (32-byte) elements (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 178956970 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+  ++s[7073650].c;
+  // CHECK-AVR-ADDR16:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+}
+
+long long ll[];
+
+void f2() {
+  ++ll[3];
+  ++ll[2705843009213693952];
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 64-bit {{.*}} (max possible 2305843009213693952 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 536870912 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 8192 elements)
+  ++ll[847073650];
+  // CHECK-I386-ADDR32: :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 536870912 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 8192 elements)
+}
+
+void f3(struct S p[]) {
+  ++p[3].a;
+  ++p[7073650413200313099].b;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 64-bit {{.*}} (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 178956970 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+  ++p[7073650].c;
+  // CHECK-AVR-ADDR16:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+}
+
+void f4(struct S *p) {
+  p += 3;
+  p += 7073650413200313099;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:3: warning: the pointer incremented by 7073650413200313099 refers past the last possible element for an array in 64-bit address space containing 256-bit (32-byte) elements (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:3: warning: {{.*}} past the last possible element {{.*}} in 

[PATCH] D101479: [Driver] Support libc++ in MSVC

2021-06-11 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

Couldn’t this commit have been kept in, and just reverting the one for using it 
in the fuchsia cmake cache? (I’m not using this particular commit myself, just 
observing.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101479

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


[PATCH] D103928: [IR] make -warn-frame-size into a module attr

2021-06-11 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

FWIW, it was pointed out to me that the commit message doesn't precisely match 
the actual attribute name. The actual attribute name is `warn-stack-size`, but 
the commit message uses `-warn-frame-size`. Oh well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103928

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D104099#2813713 , @aeubanks wrote:

> Some backends don't run SimplifyCFG, e.g. X86. I believe the pass was 
> originally created specifically for X86 (the header has some X86 examples) 
> and may or may not extend to other targets (I'm not very familiar with the 
> pass itself).
>
> I'm not opposed to landing this and seeing who complains, but if somebody 
> does, we can make this pass X86-specific by adding it to 
> X86TargetMachine::registerPassBuilderCallbacks() (which doesn't exist yet).

I am complaining about X86 side of things :)
It needs to be *at least* a late IR pass in codegen pipeline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

Some backends don't run SimplifyCFG, e.g. X86. I believe the pass was 
originally created specifically for X86 (the header has some X86 examples) and 
may or may not extend to other targets (I'm not very familiar with the pass 
itself).

I'm not opposed to landing this and seeing who complains, but if somebody does, 
we can make this pass X86-specific by adding it to 
X86TargetMachine::registerPassBuilderCallbacks() (which doesn't exist yet).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D104044: [clang-format] Fix the issue of no empty line after namespace

2021-06-11 Thread Darwin Xu via Phabricator via cfe-commits
darwin added a comment.

In D104044#2813491 , @MyDeveloperDay 
wrote:

> Devils advocate how is this any different from
>
>   class Foo {
>   
>   class Bar {} ;
>   }
>   
>   };
>
> This would become
>
>   class Foo {
>  class Bar {};
>   };
>
> i.e. its going to remove the extra lines, just asking so we can understand if 
> the removal of the line is the error or the fact it doesn't remove the line 
> in the first place?

It is different, the issue I mentioned is about the empty lines in namespace.

As for class, clang-format always removes the empty lines in class:

  darwin@Darwins-iMac temp % cat f.cpp 
  class Foo {
  
  class Bar {} ;
  
  };
  darwin@Darwins-iMac temp % clang-format f.cpp -style="{BasedOnStyle: google, 
BreakBeforeBraces: Custom, BraceWrapping: {AfterClass: true}}" 
  class Foo
  {
class Bar
{
};
  };
  darwin@Darwins-iMac temp % clang-format f.cpp -style="{BasedOnStyle: google, 
BreakBeforeBraces: Custom, BraceWrapping: {AfterClass: false}}"
  class Foo {
class Bar {};
  };

Except for when `KeepEmptyLinesAtTheStartOfBlocks` is true:

  darwin@Darwins-iMac temp % clang-format f.cpp -style="{BasedOnStyle: google, 
BreakBeforeBraces: Custom, BraceWrapping: {AfterClass: false}, 
KeepEmptyLinesAtTheStartOfBlocks: true}"
  class Foo {
  
class Bar {};
  };


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D104044

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


[PATCH] D103750: [analyzer] Handle std::make_unique for SmartPtrModeling

2021-06-11 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 351485.
RedDocMD added a comment.

Removed un-necessary check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103750

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/smart-ptr-text-output.cpp

Index: clang/test/Analysis/smart-ptr-text-output.cpp
===
--- clang/test/Analysis/smart-ptr-text-output.cpp
+++ clang/test/Analysis/smart-ptr-text-output.cpp
@@ -1,3 +1,8 @@
+// RUN: %clang_analyze_cc1\
+// RUN:  -analyzer-checker=core,cplusplus.Move,alpha.cplusplus.SmartPtr\
+// RUN:  -analyzer-config cplusplus.SmartPtrModeling:ModelSmartPtrDereference=true\
+// RUN:  -analyzer-output=text -std=c++20 %s -verify=expected
+
 // RUN: %clang_analyze_cc1\
 // RUN:  -analyzer-checker=core,cplusplus.Move,alpha.cplusplus.SmartPtr\
 // RUN:  -analyzer-config cplusplus.SmartPtrModeling:ModelSmartPtrDereference=true\
@@ -313,3 +318,27 @@
 // expected-note@-1{{Dereference of null smart pointer 'P'}}
   }
 }
+
+void makeUniqueReturnsNonNullUniquePtr() {
+  auto P = std::make_unique();
+  if (!P) {   // expected-note {{Taking false branch}}
+P->foo(); // should have no warning here, path is impossible
+  }
+  P.reset(); // expected-note {{Smart pointer 'P' reset using a null value}}
+  // Now P is null
+  if (!P) {
+// expected-note@-1 {{Taking true branch}}
+P->foo(); // expected-warning {{Dereference of null smart pointer 'P' [alpha.cplusplus.SmartPtr]}}
+// expected-note@-1{{Dereference of null smart pointer 'P'}}
+  }
+}
+
+#if __cplusplus >= 202002L
+
+void makeUniqueForOverwriteReturnsNullUniquePtr() {
+  auto P = std::make_unique_for_overwrite(); // expected-note {{std::unique_ptr 'P' constructed by std::make_unique_for_overwrite is null}}
+  *P;   // expected-warning {{Dereference of null smart pointer 'P' [alpha.cplusplus.SmartPtr]}}
+  // expected-note@-1{{Dereference of null smart pointer 'P'}}
+}
+
+#endif
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -978,6 +978,17 @@
 void swap(unique_ptr , unique_ptr ) noexcept {
   x.swap(y);
 }
+
+template 
+unique_ptr make_unique(Args &&...args);
+
+#if __cplusplus >= 202002L
+
+template 
+unique_ptr make_unique_for_overwrite();
+
+#endif
+
 } // namespace std
 #endif
 
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -35,6 +35,7 @@
 using namespace ento;
 
 namespace {
+
 class SmartPtrModeling
 : public Checker {
@@ -76,6 +77,9 @@
   {{"release"}, ::handleRelease},
   {{"swap", 1}, ::handleSwap},
   {{"get"}, ::handleGet}};
+  const CallDescription StdMakeUniqueCall{{"std", "make_unique"}};
+  const CallDescription StdMakeUniqueForOverwriteCall{
+  {"std", "make_unique_for_overwrite"}};
 };
 } // end of anonymous namespace
 
@@ -137,12 +141,8 @@
 
 // Helper method to get the inner pointer type of specialized smart pointer
 // Returns empty type if not found valid inner pointer type.
-static QualType getInnerPointerType(const CallEvent , CheckerContext ) {
-  const auto *MethodDecl = dyn_cast_or_null(Call.getDecl());
-  if (!MethodDecl || !MethodDecl->getParent())
-return {};
-
-  const auto *RecordDecl = MethodDecl->getParent();
+static QualType getInnerPointerType(const CXXRecordDecl *RecordDecl,
+CheckerContext ) {
   if (!RecordDecl || !RecordDecl->isInStdNamespace())
 return {};
 
@@ -157,6 +157,17 @@
   return C.getASTContext().getPointerType(InnerValueType.getCanonicalType());
 }
 
+// Helper method to get the inner pointer type of specialized smart pointer
+// Returns empty type if not found valid inner pointer type.
+static QualType getInnerPointerType(const CallEvent , CheckerContext ) {
+  const auto *MethodDecl = dyn_cast_or_null(Call.getDecl());
+  if (!MethodDecl->getParent())
+return {};
+
+  const auto *RecordDecl = MethodDecl->getParent();
+  return getInnerPointerType(RecordDecl, C);
+}
+
 // Helper method to pretty print region and avoid extra spacing.
 static void checkAndPrettyPrintRegion(llvm::raw_ostream ,
   const MemRegion *Region) {
@@ -177,7 +188,63 @@
 
 bool SmartPtrModeling::evalCall(const CallEvent ,
 CheckerContext ) const {
+
   ProgramStateRef State = C.getState();
+
+  if (Call.isCalled(StdMakeUniqueCall)) {
+const Optional ThisRegionOpt = 

[PATCH] D104096: [Clang-Format] Add ReferenceAlignment directive

2021-06-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

A new nits but I'd say it was pretty good.




Comment at: clang/lib/Format/Format.cpp:1356
   Style.PointerAlignment = FormatStyle::PAS_Left;
+  Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
   Style.SpaceBeforeCpp11BracedList = true;

if we are inheriting from LLVM we only need this in the LLVM base tyle



Comment at: clang/unittests/Format/FormatTest.cpp:1243
+  verifyFormat("int *f1(int ) const & = 0;", Style);
+  verifyFormat("int *a = f1();\nint  = f2();\nint & = f3();", Style);
+  Style.PointerAlignment = FormatStyle::PAS_Left;

could you put each line on its own line. makes it easier to reason about



Comment at: clang/unittests/Format/FormatTest.cpp:1250
+  verifyFormat("int* f1(int& a) const& = 0;", Style);
+  verifyFormat("int* a = f1();\nint& b = f2();\nint&& c = f3();", Style);
+  Style.PointerAlignment = FormatStyle::PAS_Right;

ditto



Comment at: clang/unittests/Format/FormatTest.cpp:1256
+  verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
+  verifyFormat("int *a = f1();\nint& b = f2();\nint&& c = f3();", Style);
+  Style.PointerAlignment = FormatStyle::PAS_Left;

ditto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104096

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


[PATCH] D104062: [HIP] Fix --hip-version flag with 0 as component

2021-06-11 Thread Aaron Enye Shi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf2cc0427b13e: [HIP] Fix --hip-version flag with 0 as 
component (authored by ashi1).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104062

Files:
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/test/Driver/hip-version.hip


Index: clang/test/Driver/hip-version.hip
===
--- clang/test/Driver/hip-version.hip
+++ clang/test/Driver/hip-version.hip
@@ -36,6 +36,16 @@
 
 // SPECIFIED2: Found HIP installation: {{.*Driver}}, version 3.7.0
 
+// RUN: %clang -v --rocm-path=%S --hip-version=4.0.21025 2>&1 \
+// RUN:   | FileCheck -check-prefixes=SPECIFIED3 %s
+
+// SPECIFIED3: Found HIP installation: {{.*Driver}}, version 4.0.21025
+
+// RUN: %clang -v --rocm-path=%S --hip-version=4 2>&1 \
+// RUN:   | FileCheck -check-prefixes=SPECIFIED4 %s
+
+// SPECIFIED4: Found HIP installation: {{.*Driver}}, version 4.0.0
+
 // RUN: not %clang -v --rocm-path=%S --hip-version=x.y 2>&1 \
 // RUN:   | FileCheck -check-prefixes=INVALID %s
 
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -316,8 +316,8 @@
   HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);
   if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {
 HIPVersionArg = A->getValue();
-unsigned Major = 0;
-unsigned Minor = 0;
+unsigned Major = ~0U;
+unsigned Minor = ~0U;
 SmallVector Parts;
 HIPVersionArg.split(Parts, '.');
 if (Parts.size())
@@ -328,7 +328,9 @@
   VersionPatch = Parts[2].str();
 if (VersionPatch.empty())
   VersionPatch = "0";
-if (Major == 0 || Minor == 0)
+if (Major != ~0U && Minor == ~0U)
+  Minor = 0;
+if (Major == ~0U || Minor == ~0U)
   D.Diag(diag::err_drv_invalid_value)
   << A->getAsString(Args) << HIPVersionArg;
 


Index: clang/test/Driver/hip-version.hip
===
--- clang/test/Driver/hip-version.hip
+++ clang/test/Driver/hip-version.hip
@@ -36,6 +36,16 @@
 
 // SPECIFIED2: Found HIP installation: {{.*Driver}}, version 3.7.0
 
+// RUN: %clang -v --rocm-path=%S --hip-version=4.0.21025 2>&1 \
+// RUN:   | FileCheck -check-prefixes=SPECIFIED3 %s
+
+// SPECIFIED3: Found HIP installation: {{.*Driver}}, version 4.0.21025
+
+// RUN: %clang -v --rocm-path=%S --hip-version=4 2>&1 \
+// RUN:   | FileCheck -check-prefixes=SPECIFIED4 %s
+
+// SPECIFIED4: Found HIP installation: {{.*Driver}}, version 4.0.0
+
 // RUN: not %clang -v --rocm-path=%S --hip-version=x.y 2>&1 \
 // RUN:   | FileCheck -check-prefixes=INVALID %s
 
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -316,8 +316,8 @@
   HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);
   if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {
 HIPVersionArg = A->getValue();
-unsigned Major = 0;
-unsigned Minor = 0;
+unsigned Major = ~0U;
+unsigned Minor = ~0U;
 SmallVector Parts;
 HIPVersionArg.split(Parts, '.');
 if (Parts.size())
@@ -328,7 +328,9 @@
   VersionPatch = Parts[2].str();
 if (VersionPatch.empty())
   VersionPatch = "0";
-if (Major == 0 || Minor == 0)
+if (Major != ~0U && Minor == ~0U)
+  Minor = 0;
+if (Major == ~0U || Minor == ~0U)
   D.Diag(diag::err_drv_invalid_value)
   << A->getAsString(Args) << HIPVersionArg;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f2cc042 - [HIP] Fix --hip-version flag with 0 as component

2021-06-11 Thread Aaron En Ye Shi via cfe-commits

Author: Aaron En Ye Shi
Date: 2021-06-11T16:25:03Z
New Revision: f2cc0427b13ef10e67eed6eab9eefb58e8aef3d9

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

LOG: [HIP] Fix --hip-version flag with 0 as component

Allow the usage of minor version 0, for hip versions
such as 4.0. Change the default values when performing
version checks.

Reviewed By: yaxunl

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/test/Driver/hip-version.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index ea3a4b4a8fd1..2e92be51f69e 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -316,8 +316,8 @@ RocmInstallationDetector::RocmInstallationDetector(
   HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);
   if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {
 HIPVersionArg = A->getValue();
-unsigned Major = 0;
-unsigned Minor = 0;
+unsigned Major = ~0U;
+unsigned Minor = ~0U;
 SmallVector Parts;
 HIPVersionArg.split(Parts, '.');
 if (Parts.size())
@@ -328,7 +328,9 @@ RocmInstallationDetector::RocmInstallationDetector(
   VersionPatch = Parts[2].str();
 if (VersionPatch.empty())
   VersionPatch = "0";
-if (Major == 0 || Minor == 0)
+if (Major != ~0U && Minor == ~0U)
+  Minor = 0;
+if (Major == ~0U || Minor == ~0U)
   D.Diag(diag::err_drv_invalid_value)
   << A->getAsString(Args) << HIPVersionArg;
 

diff  --git a/clang/test/Driver/hip-version.hip 
b/clang/test/Driver/hip-version.hip
index eb1295210cfc..83b8dbddf228 100644
--- a/clang/test/Driver/hip-version.hip
+++ b/clang/test/Driver/hip-version.hip
@@ -36,6 +36,16 @@
 
 // SPECIFIED2: Found HIP installation: {{.*Driver}}, version 3.7.0
 
+// RUN: %clang -v --rocm-path=%S --hip-version=4.0.21025 2>&1 \
+// RUN:   | FileCheck -check-prefixes=SPECIFIED3 %s
+
+// SPECIFIED3: Found HIP installation: {{.*Driver}}, version 4.0.21025
+
+// RUN: %clang -v --rocm-path=%S --hip-version=4 2>&1 \
+// RUN:   | FileCheck -check-prefixes=SPECIFIED4 %s
+
+// SPECIFIED4: Found HIP installation: {{.*Driver}}, version 4.0.0
+
 // RUN: not %clang -v --rocm-path=%S --hip-version=x.y 2>&1 \
 // RUN:   | FileCheck -check-prefixes=INVALID %s
 



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


[PATCH] D103849: Fix undeduced type when instanciating template member

2021-06-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I think this is reasonable, but I'd like to hear from @rsmith before landing 
this.


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

https://reviews.llvm.org/D103849

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


[PATCH] D88174: [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread Chris Hamilton via Phabricator via cfe-commits
chrish_ericsson_atx reopened this revision.
chrish_ericsson_atx added a comment.
This revision is now accepted and ready to land.

Reverted commit due to buildbot failures -- will update shortly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88174

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


[clang] 82a3b60 - Update the C status page somewhat.

2021-06-11 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-06-11T12:06:50-04:00
New Revision: 82a3b606b01d2da23a40785222f3f7d15401dda0

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

LOG: Update the C status page somewhat.

This adds implementation information for N2607,
clarifies that C17 only resolved defect reports,
and adds -std= information for the different versions.

Added: 


Modified: 
clang/www/c_status.html

Removed: 




diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 72df57a667b89..f68344c47c082 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -79,24 +79,28 @@ C Support in Clang
 C89 implementation status
 
 Clang implements all of the ISO 9899:1990 (C89) standard.
+You can use Clang in C89 mode with the -std=c89 or 
-std=c90 options.
 
 C99 implementation status
 
 Clang implements a significant portion of the ISO 9899:1999 (C99) standard, 
but the status of individual proposals is still under investigation.
+You can use Clang in C99 mode with the -std=c99 option.
 
 C11 implementation status
 
 Clang implements a significant portion of the ISO 9899:2011 (C11) standard, 
but the status of individual proposals is still under investigation.
+You can use Clang in C11 mode with the -std=c11 option (use 
-std=c1x in Clang 3.0 and earlier).
 
 C17 implementation status
 
-Clang implements a significant portion of the ISO 9899:2018 (C17) standard, 
but the status of individual proposals is still under investigation.
+There are no major changes in this edition, only technical corrections and 
clarifications that are tracked by Defect Report.
+You can use Clang in C17 mode with the -std=c17 or 
-std=c18 options (available in Clang 6 and later).
 
 C2x implementation status
 
 Clang has support for some of the features of the C standard following C17, 
informally referred to as C2x.
 
-You can use Clang in C2x mode with the -std=c2x option.
+You can use Clang in C2x mode with the -std=c2x option 
(available in Clang 9 and later).
 
 
 List of features and minimum Clang version with support
@@ -289,7 +293,7 @@ C2x implementation status
 
   Compatibility of Pointers to Arrays with Qualifiers
   http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2607.pdf;>N2607
-  Unknown
+  Yes
 
 
 



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


[PATCH] D103615: [Clang] Add option for vector compare compatibility.

2021-06-11 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp updated this revision to Diff 351467.
stefanp added a comment.

Updated the name of the option to vector-compare compat.
Added clang test lines to the test cases.
Added deprecation warnings to the current default behaviour of vector bool and
vector pixel.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103615

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/vector-compat-pixel-bool-ternary.c
  clang/test/CodeGen/vector-compat-pixel-bool.c
  clang/test/CodeGen/vector-compat-ternary.c
  clang/test/CodeGen/vector-compat.c

Index: clang/test/CodeGen/vector-compat.c
===
--- /dev/null
+++ clang/test/CodeGen/vector-compat.c
@@ -0,0 +1,162 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: not %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// RUN:   -vector-compare-compat=mixed -triple powerpc-unknown-unknown -S -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=ERROR
+// RUN: %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// RUN:   -vector-compare-compat=gcc -triple powerpc-unknown-unknown -S -emit-llvm %s -o - | FileCheck %s
+// RUN: not %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// RUN:   -vector-compare-compat=xl -triple powerpc-unknown-unknown -S -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=ERROR
+// RUN: %clang -mcpu=pwr8 -vector-compare-compat=gcc --target=powerpc-unknown-unknown -S -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang -mcpu=pwr9 -vector-compare-compat=gcc --target=powerpc-unknown-unknown -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK-LABEL: @ui8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:store <16 x i8> [[A:%.*]], <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <16 x i8> [[B:%.*]], <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <16 x i8>, <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <16 x i8>, <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <16 x i8> [[TMP0]], [[TMP1]]
+// CHECK-NEXT:[[SEXT:%.*]] = sext <16 x i1> [[CMP]] to <16 x i8>
+// CHECK-NEXT:ret <16 x i8> [[SEXT]]
+//
+// ERROR: returning 'int' from a function with incompatible result type
+vector unsigned char ui8(vector unsigned char a, vector unsigned char b) {
+  return a == b;
+}
+
+// CHECK-LABEL: @si8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:store <16 x i8> [[A:%.*]], <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <16 x i8> [[B:%.*]], <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <16 x i8>, <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <16 x i8>, <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <16 x i8> [[TMP0]], [[TMP1]]
+// CHECK-NEXT:[[SEXT:%.*]] = sext <16 x i1> [[CMP]] to <16 x i8>
+// CHECK-NEXT:ret <16 x i8> [[SEXT]]
+//
+// ERROR: returning 'int' from a function with incompatible result type
+vector signed char si8(vector signed char a, vector signed char b) {
+  return a == b;
+}
+
+// CHECK-LABEL: @ui16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:store <8 x i16> [[A:%.*]], <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <8 x i16> [[B:%.*]], <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <8 x i16>, <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <8 x i16>, <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <8 x i16> [[TMP0]], [[TMP1]]
+// CHECK-NEXT:[[SEXT:%.*]] = sext <8 x i1> [[CMP]] to <8 x i16>
+// CHECK-NEXT:ret <8 x i16> [[SEXT]]
+//
+// ERROR: returning 'int' from a function with incompatible result type
+vector unsigned short ui16(vector unsigned short a, vector unsigned short b) {
+  return a == b;
+}
+
+// CHECK-LABEL: @si16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:store <8 x i16> [[A:%.*]], <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <8 x i16> [[B:%.*]], <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <8 x i16>, <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <8 x i16>, <8 x i16>* [[B_ADDR]], align 16
+// 

[PATCH] D104044: [clang-format] Fix the issue of no empty line after namespace

2021-06-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

We should have perhaps though about this when we added 
```EmptyLineAfterAccessModifier ``` and ```EmptyLineBeforeAccessModifier ```


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D104044

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


[PATCH] D104044: [clang-format] Fix the issue of no empty line after namespace

2021-06-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Do we need a set options for when we want to insert/retain/add a newline after 
various constructs? frankly I've been mulling over the concept of adding a

  NewLinesBetweenFunctions: 1

I personally don't like code written like this as I find it hard to read, I'd 
like to be able to mandate a single line between functions

  void foo()
  {
  ...
  }
  void bar()
  {
  ...
  }
  void foobar()
  {
  ...
  }

I prefer when its written as:

  void foo()
  {
  ...
  }
  
  void bar()
  {
  ...
  }
  
  void foobar()
  {
  ...
  }

Maybe we even need a more generalised mechanism that would allow alot of 
flexibility letting people control their own specific style.

  NewLineInsertionStyle: Custom
AtferNameSpaceOpeningBrace: true
BeforeNameSpaceClosingBrace: true
BetweenFunctions: true
AfterClassOpeningBrace: true
BeforeClassClosingBrace: true


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D104044

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


[PATCH] D104125: [PowerPC] Moving defineXLCompatMacros() definition

2021-06-11 Thread Quinn Pham via Phabricator via cfe-commits
quinnp created this revision.
Herald added subscribers: shchenz, kbarton, nemanjai.
quinnp requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

[NFC] Moving the definition of the defineXLCompatMacros function from
the header file clang/lib/Basic/Targets/PPC.h to the source file
clang/lib/Basic/Targets/PPC.cpp.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104125

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h


Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -350,24 +350,6 @@
   bool isSPRegName(StringRef RegName) const override {
 return RegName.equals("r1") || RegName.equals("x1");
   }
-
-  void defineXLCompatMacros(MacroBuilder ) const {
-Builder.defineMacro("__popcntb", "__builtin_ppc_popcntb");
-Builder.defineMacro("__eieio", "__builtin_ppc_eieio");
-Builder.defineMacro("__iospace_eieio", "__builtin_ppc_iospace_eieio");
-Builder.defineMacro("__isync", "__builtin_ppc_isync");
-Builder.defineMacro("__lwsync", "__builtin_ppc_lwsync");
-Builder.defineMacro("__iospace_lwsync", "__builtin_ppc_iospace_lwsync");
-Builder.defineMacro("__sync", "__builtin_ppc_sync");
-Builder.defineMacro("__iospace_sync", "__builtin_ppc_iospace_sync");
-Builder.defineMacro("__dcbfl", "__builtin_ppc_dcbfl");
-Builder.defineMacro("__dcbflp", "__builtin_ppc_dcbflp");
-Builder.defineMacro("__dcbst", "__builtin_ppc_dcbst");
-Builder.defineMacro("__dcbt", "__builtin_ppc_dcbt");
-Builder.defineMacro("__dcbtst", "__builtin_ppc_dcbtst");
-Builder.defineMacro("__dcbz", "__builtin_ppc_dcbz");
-Builder.defineMacro("__icbt", "__builtin_ppc_icbt");
-  }
 };
 
 class LLVM_LIBRARY_VISIBILITY PPC32TargetInfo : public PPCTargetInfo {
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -81,6 +81,24 @@
   return true;
 }
 
+static void defineXLCompatMacros(MacroBuilder ) {
+  Builder.defineMacro("__popcntb", "__builtin_ppc_popcntb");
+  Builder.defineMacro("__eieio", "__builtin_ppc_eieio");
+  Builder.defineMacro("__iospace_eieio", "__builtin_ppc_iospace_eieio");
+  Builder.defineMacro("__isync", "__builtin_ppc_isync");
+  Builder.defineMacro("__lwsync", "__builtin_ppc_lwsync");
+  Builder.defineMacro("__iospace_lwsync", "__builtin_ppc_iospace_lwsync");
+  Builder.defineMacro("__sync", "__builtin_ppc_sync");
+  Builder.defineMacro("__iospace_sync", "__builtin_ppc_iospace_sync");
+  Builder.defineMacro("__dcbfl", "__builtin_ppc_dcbfl");
+  Builder.defineMacro("__dcbflp", "__builtin_ppc_dcbflp");
+  Builder.defineMacro("__dcbst", "__builtin_ppc_dcbst");
+  Builder.defineMacro("__dcbt", "__builtin_ppc_dcbt");
+  Builder.defineMacro("__dcbtst", "__builtin_ppc_dcbtst");
+  Builder.defineMacro("__dcbz", "__builtin_ppc_dcbz");
+  Builder.defineMacro("__icbt", "__builtin_ppc_icbt");
+}
+
 /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific
 /// #defines that are not tied to a specific subtarget.
 void PPCTargetInfo::getTargetDefines(const LangOptions ,


Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -350,24 +350,6 @@
   bool isSPRegName(StringRef RegName) const override {
 return RegName.equals("r1") || RegName.equals("x1");
   }
-
-  void defineXLCompatMacros(MacroBuilder ) const {
-Builder.defineMacro("__popcntb", "__builtin_ppc_popcntb");
-Builder.defineMacro("__eieio", "__builtin_ppc_eieio");
-Builder.defineMacro("__iospace_eieio", "__builtin_ppc_iospace_eieio");
-Builder.defineMacro("__isync", "__builtin_ppc_isync");
-Builder.defineMacro("__lwsync", "__builtin_ppc_lwsync");
-Builder.defineMacro("__iospace_lwsync", "__builtin_ppc_iospace_lwsync");
-Builder.defineMacro("__sync", "__builtin_ppc_sync");
-Builder.defineMacro("__iospace_sync", "__builtin_ppc_iospace_sync");
-Builder.defineMacro("__dcbfl", "__builtin_ppc_dcbfl");
-Builder.defineMacro("__dcbflp", "__builtin_ppc_dcbflp");
-Builder.defineMacro("__dcbst", "__builtin_ppc_dcbst");
-Builder.defineMacro("__dcbt", "__builtin_ppc_dcbt");
-Builder.defineMacro("__dcbtst", "__builtin_ppc_dcbtst");
-Builder.defineMacro("__dcbz", "__builtin_ppc_dcbz");
-Builder.defineMacro("__icbt", "__builtin_ppc_icbt");
-  }
 };
 
 class LLVM_LIBRARY_VISIBILITY PPC32TargetInfo : public PPCTargetInfo {
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -81,6 +81,24 @@
   return true;
 }
 
+static void defineXLCompatMacros(MacroBuilder ) {
+  

[PATCH] D103615: [Clang] Add option for vector compare compatibility.

2021-06-11 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp added a comment.

In D103615#2799498 , @bmahjour wrote:

> As far as I can see, there is no good reason for the special treatment of 
> vector bool/pixel going forward. Could we drop this special treatment, or at 
> least change the default to use scalar results across the board (consistent 
> with XL's behaviour and clang's current behaviour for most cases).

We can change this but I am hesitant to make the change immediately. I can 
leave the default behavior as-is for now and add a warning to say that this 
feature is going to be deprecated at a later date. After a couple of releases 
we can then change the default. I don't want to change defaults without giving 
users some kind of warning first.

As a result of this I'm going to change the name in the enum from `Default` to 
`Mixed` as it does not make sense to have it named Default if it's not going to 
be default in the long run.




Comment at: clang/include/clang/Driver/Options.td:3811
   MarshallingInfoFlag>;
+def vector_abi_compat : Joined<["-"], "vector-abi-compat=">, 
Flags<[CC1Option]>, Group,
+  HelpText<"Determines whether vector compare returns a vector or a scalar. 
Options: default, gcc, xl.">,

bmahjour wrote:
> I'm not sure the term "ABI" is really applicable. Maybe we should call it 
> "vector-compare-compat="
Sure. I can change the name to `vector-compare-compat`.



Comment at: clang/test/CodeGen/vector-compat-pixel-bool-ternary.c:6
+// RUN:   -vector-abi-compat=gcc -triple powerpc-unknown-unknown -S -emit-llvm 
%s -o - 2>&1| FileCheck %s --check-prefix=ERROR
+// RUN: %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// RUN:   -vector-abi-compat=xl -triple powerpc-unknown-unknown -S -emit-llvm 
%s -o - | FileCheck %s

bmahjour wrote:
> I only see the clang FE interface being tested. Does this have to be 
> specified through `-Xclang -vector-abi-compat=...` or is there a clang driver 
> option for it as well? I think we should have a clang driver option and have 
> at least one test for it.
This option works when it is passed immediately to clang.
I will add a couple of RUN lines to test this as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103615

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


[PATCH] D104044: [clang-format] Fix the issue of no empty line after namespace

2021-06-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Devils advocate how is this any different from

  class Foo {
  
  class Bar {} ;
  }
  
  };

This would become

  class Foo {
 class Bar {};
  };

i.e. its going to remove the extra lines, just asking so we can understand if 
the removal of the line is the error or the fact it doesn't remove the line in 
the first place?


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D104044

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


[PATCH] D104124: [IR] Simplify createReplacementInstr

2021-06-11 Thread Jay Foad via Phabricator via cfe-commits
foad added reviewers: yaxunl, robertlytton.
foad added a comment.

Given how simple createReplacementInstr is now, this does make me wonder if it 
was really worth creating ReplaceConstant.{cpp,h} in the first place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104124

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


[PATCH] D104124: [IR] Simplify createReplacementInstr

2021-06-11 Thread Jay Foad via Phabricator via cfe-commits
foad created this revision.
Herald added subscribers: dexonsmith, hiraditya.
foad requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

NFCI, although the test change shows that ConstantExpr::getAsInstruction
is better than the old implementation of createReplacementInstr because
it propagates things like the sdiv "exact" flag.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104124

Files:
  clang/test/CodeGenCUDA/managed-var.cu
  llvm/lib/IR/ReplaceConstant.cpp


Index: llvm/lib/IR/ReplaceConstant.cpp
===
--- llvm/lib/IR/ReplaceConstant.cpp
+++ llvm/lib/IR/ReplaceConstant.cpp
@@ -20,53 +20,9 @@
 // Replace a constant expression by instructions with equivalent operations at
 // a specified location.
 Instruction *createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
-  IRBuilder Builder(Instr);
-  unsigned OpCode = CE->getOpcode();
-  switch (OpCode) {
-  case Instruction::GetElementPtr: {
-SmallVector CEOpVec(CE->operands());
-ArrayRef CEOps(CEOpVec);
-return dyn_cast(
-
Builder.CreateInBoundsGEP(cast(CE)->getSourceElementType(),
-  CEOps[0], CEOps.slice(1)));
-  }
-  case Instruction::Add:
-  case Instruction::Sub:
-  case Instruction::Mul:
-  case Instruction::UDiv:
-  case Instruction::SDiv:
-  case Instruction::FDiv:
-  case Instruction::URem:
-  case Instruction::SRem:
-  case Instruction::FRem:
-  case Instruction::Shl:
-  case Instruction::LShr:
-  case Instruction::AShr:
-  case Instruction::And:
-  case Instruction::Or:
-  case Instruction::Xor:
-return dyn_cast(
-Builder.CreateBinOp((Instruction::BinaryOps)OpCode, CE->getOperand(0),
-CE->getOperand(1), CE->getName()));
-  case Instruction::Trunc:
-  case Instruction::ZExt:
-  case Instruction::SExt:
-  case Instruction::FPToUI:
-  case Instruction::FPToSI:
-  case Instruction::UIToFP:
-  case Instruction::SIToFP:
-  case Instruction::FPTrunc:
-  case Instruction::FPExt:
-  case Instruction::PtrToInt:
-  case Instruction::IntToPtr:
-  case Instruction::BitCast:
-  case Instruction::AddrSpaceCast:
-return dyn_cast(
-Builder.CreateCast((Instruction::CastOps)OpCode, CE->getOperand(0),
-   CE->getType(), CE->getName()));
-  default:
-llvm_unreachable("Unhandled constant expression!\n");
-  }
+  auto *CEInstr = CE->getAsInstruction();
+  CEInstr->insertBefore(Instr);
+  return CEInstr;
 }
 
 void convertConstantExprsToInstructions(Instruction *I, ConstantExpr *CE,
Index: clang/test/CodeGenCUDA/managed-var.cu
===
--- clang/test/CodeGenCUDA/managed-var.cu
+++ clang/test/CodeGenCUDA/managed-var.cu
@@ -146,7 +146,7 @@
 // HOST:  %3 = getelementptr inbounds [100 x %struct.vec], [100 x 
%struct.vec]* %2, i64 0, i64 1, i32 1
 // HOST:  %4 = ptrtoint float* %3 to i64
 // HOST:  %5 = sub i64 %4, %1
-// HOST:  %6 = sdiv i64 %5, 4
+// HOST:  %6 = sdiv exact i64 %5, 4
 // HOST:  %7 = sitofp i64 %6 to float
 // HOST:  ret float %7
 float addr_taken2() {


Index: llvm/lib/IR/ReplaceConstant.cpp
===
--- llvm/lib/IR/ReplaceConstant.cpp
+++ llvm/lib/IR/ReplaceConstant.cpp
@@ -20,53 +20,9 @@
 // Replace a constant expression by instructions with equivalent operations at
 // a specified location.
 Instruction *createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
-  IRBuilder Builder(Instr);
-  unsigned OpCode = CE->getOpcode();
-  switch (OpCode) {
-  case Instruction::GetElementPtr: {
-SmallVector CEOpVec(CE->operands());
-ArrayRef CEOps(CEOpVec);
-return dyn_cast(
-Builder.CreateInBoundsGEP(cast(CE)->getSourceElementType(),
-  CEOps[0], CEOps.slice(1)));
-  }
-  case Instruction::Add:
-  case Instruction::Sub:
-  case Instruction::Mul:
-  case Instruction::UDiv:
-  case Instruction::SDiv:
-  case Instruction::FDiv:
-  case Instruction::URem:
-  case Instruction::SRem:
-  case Instruction::FRem:
-  case Instruction::Shl:
-  case Instruction::LShr:
-  case Instruction::AShr:
-  case Instruction::And:
-  case Instruction::Or:
-  case Instruction::Xor:
-return dyn_cast(
-Builder.CreateBinOp((Instruction::BinaryOps)OpCode, CE->getOperand(0),
-CE->getOperand(1), CE->getName()));
-  case Instruction::Trunc:
-  case Instruction::ZExt:
-  case Instruction::SExt:
-  case Instruction::FPToUI:
-  case Instruction::FPToSI:
-  case Instruction::UIToFP:
-  case Instruction::SIToFP:
-  case Instruction::FPTrunc:
-  case Instruction::FPExt:
-  case Instruction::PtrToInt:
-  case Instruction::IntToPtr:
-  case Instruction::BitCast:
-  case Instruction::AddrSpaceCast:
-return dyn_cast(
-Builder.CreateCast((Instruction::CastOps)OpCode, CE->getOperand(0),
- 

[PATCH] D99696: [clang] NRVO: Improvements and handling of more cases.

2021-06-11 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 351462.
mizvekov added a comment.

Look through AttributedType when obtaining FunctionDecl return type.

Adds a couple more test cases to cover this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99696

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCoroutine.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CodeGen/nrvo-tracking.cpp

Index: clang/test/CodeGen/nrvo-tracking.cpp
===
--- clang/test/CodeGen/nrvo-tracking.cpp
+++ clang/test/CodeGen/nrvo-tracking.cpp
@@ -29,8 +29,6 @@
 
 // CHECK-LABEL: define{{.*}} void @_Z2l3v
 // CHECK:   call {{.*}} @_ZN1XC1Ev
-// CHECK-NEXT:  call {{.*}} @_ZN1XC1EOS_
-// CHECK-NEXT:  call void @llvm.lifetime.end
 // CHECK-NEXT:  call void @llvm.lifetime.end
 // CHECK-NEXT:  ret void
 L(3, t, T);
@@ -152,7 +150,11 @@
   }; }()();\
 }
 
-//B(1, X); // Uncomment this line at your own peril ;)
+// CHECK-LABEL: define{{.*}} void @_Z2b1v
+// CHECK:   call {{.*}} @_ZN1XC1Ev
+// CHECK-NEXT:  call void @llvm.lifetime.end
+// CHECK-NEXT:  ret void
+B(1, X);
 
 // CHECK-LABEL: define{{.*}} void @_Z2b2v
 // CHECK:   call {{.*}} @_ZN1XC1Ev
@@ -164,8 +166,6 @@
 
 // CHECK-LABEL: define{{.*}} void @_Z2b3v
 // CHECK:   call {{.*}} @_ZN1XC1Ev
-// CHECK-NEXT:  call {{.*}} @_ZN1XC1EOS_
-// CHECK-NEXT:  call void @llvm.lifetime.end
 // CHECK-NEXT:  call void @llvm.lifetime.end
 // CHECK-NEXT:  ret void
 B(3, T);
@@ -187,3 +187,24 @@
 B(5, );
 
 #undef B
+
+// CHECK-LABEL: define{{.*}} void @_Z6f_attrv
+// CHECK:   call {{.*}} @_ZN1XC1Ev
+// CHECK-NEXT:  call void @llvm.lifetime.end
+// CHECK-NEXT:  ret void
+template [[gnu::cdecl]] static inline auto tf_attr() -> X {
+T t;
+return t;
+}
+void f_attr() { auto t = tf_attr(); }
+
+// CHECK-LABEL: define{{.*}} void @_Z6b_attrv
+// CHECK:   call {{.*}} @_ZN1XC1Ev
+// CHECK-NEXT:  call void @llvm.lifetime.end
+// CHECK-NEXT:  ret void
+void b_attr() {
+  auto t = []() { return ^ X () [[clang::vectorcall]] {
+  T t;
+  return t;
+  }; }()();
+}
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -23,6 +23,7 @@
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateInstCallback.h"
@@ -1085,11 +1086,30 @@
 
   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  StartingScope, InstantiatingVarTemplate);
-
   if (D->isNRVOVariable()) {
-QualType ReturnType = cast(DC)->getReturnType();
-if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
-  Var->setNRVOVariable(true);
+QualType RT;
+if (auto *F = dyn_cast(DC))
+  RT = F->getReturnType();
+else if (isa(DC))
+  RT = cast(SemaRef.getCurBlock()->FunctionType)
+   ->getReturnType();
+else
+  llvm_unreachable("Unknown context type");
+
+// This is the last chance we have of checking copy elision eligibility
+// for functions in depdendent contexts. The sema actions for building
+// the return statement during template instantiation will have no effect
+// regarding copy elision, since NRVO propagation runs on the scope exit
+// actions, and these are not run on instantiation.
+// This might run through some VarDecls which were returned from non-taken
+// 'if constexpr' branches, and these will end up being constructed on the
+// return slot even if they will never be returned, as a sort of accidental
+// 'optimization'. Notably, functions with 'auto' return types won't have it
+// deduced by this point. Coupled with the limitation described
+// previously, this makes it very hard to support copy elision for these.
+Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
+bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
+Var->setNRVOVariable(NRVO);
   }
 
   Var->setImplicit(D->isImplicit());
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3307,99 +3307,153 @@
   return new (Context) BreakStmt(BreakLoc);
 }
 
-/// Determine whether the given expression is a candidate for
-/// copy elision in either a return statement or a throw expression.
+/// Determine whether the given expression might be move-eligible or
+/// copy-elidable in either a 

[clang] 7e9822c - Revert "[Sema] Address-space sensitive check for unbounded arrays (v2)"

2021-06-11 Thread via cfe-commits

Author: eahcmrh
Date: 2021-06-11T17:44:06+02:00
New Revision: 7e9822cc55065b7c450dda254340765794e11fe3

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

LOG: Revert "[Sema] Address-space sensitive check for unbounded arrays (v2)"

This reverts commit e42a347b74400b7212ceaaea6d39562a0435df42.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/const-eval.c
clang/test/SemaCXX/constant-expression-cxx14.cpp

Removed: 
clang/test/Sema/unbounded-array-bounds.c



diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c07e6f9d7421a..af242cffbe7de 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9176,14 +9176,6 @@ def warn_array_index_precedes_bounds : Warning<
 def warn_array_index_exceeds_bounds : Warning<
   "array index %0 is past the end of the array (which contains %1 "
   "element%s2)">, InGroup;
-def warn_ptr_arith_exceeds_max_addressable_bounds : Warning<
-  "the pointer incremented by %0 refers past the last possible element for an 
array in %1-bit "
-  "address space containing %2-bit (%3-byte) elements (max possible %4 
element%s5)">,
-  InGroup;
-def warn_array_index_exceeds_max_addressable_bounds : Warning<
-  "array index %0 refers past the last possible element for an array in %1-bit 
"
-  "address space containing %2-bit (%3-byte) elements (max possible %4 
element%s5)">,
-  InGroup;
 def note_array_declared_here : Note<
   "array %0 declared here">;
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 309cb7c0b2cb4..91498293d60e2 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14536,11 +14536,11 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   const ConstantArrayType *ArrayTy =
   Context.getAsConstantArrayType(BaseExpr->getType());
 
-  const Type *BaseType =
-  ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
-  bool IsUnboundedArray = (BaseType == nullptr);
-  if (EffectiveType->isDependentType() ||
-  (!IsUnboundedArray && BaseType->isDependentType()))
+  if (!ArrayTy)
+return;
+
+  const Type *BaseType = ArrayTy->getElementType().getTypePtr();
+  if (EffectiveType->isDependentType() || BaseType->isDependentType())
 return;
 
   Expr::EvalResult Result;
@@ -14548,10 +14548,8 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
 return;
 
   llvm::APSInt index = Result.Val.getInt();
-  if (IndexNegated) {
-index.setIsUnsigned(false);
+  if (IndexNegated)
 index = -index;
-  }
 
   const NamedDecl *ND = nullptr;
   if (const DeclRefExpr *DRE = dyn_cast(BaseExpr))
@@ -14559,69 +14557,6 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   if (const MemberExpr *ME = dyn_cast(BaseExpr))
 ND = ME->getMemberDecl();
 
-  if (IsUnboundedArray) {
-if (index.isUnsigned() || !index.isNegative()) {
-  const auto  = getASTContext();
-  unsigned AddrBits =
-  ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
-  EffectiveType->getCanonicalTypeInternal()));
-  if (index.getBitWidth() < AddrBits)
-index = index.zext(AddrBits);
-  CharUnits ElemCharUnits = ASTC.getTypeSizeInChars(EffectiveType);
-  llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits.getQuantity());
-  // If index has more active bits than address space, we already know
-  // we have a bounds violation to warn about.  Otherwise, compute
-  // address of (index + 1)th element, and warn about bounds violation
-  // only if that address exceeds address space.
-  if (index.getActiveBits() <= AddrBits) {
-bool Overflow;
-llvm::APInt Product(index);
-Product += 1;
-Product = Product.umul_ov(ElemBytes, Overflow);
-if (!Overflow && Product.getActiveBits() <= AddrBits)
-  return;
-  }
-
-  // Need to compute max possible elements in address space, since that
-  // is included in diag message.
-  llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
-  MaxElems = MaxElems.zext(std::max(AddrBits + 1, 
ElemBytes.getBitWidth()));
-  MaxElems += 1;
-  ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
-  MaxElems = MaxElems.udiv(ElemBytes);
-
-  unsigned DiagID =
-  ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
-  : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
-
-  // Diag message shows element size in bits and in "bytes" (platform-
-  // dependent CharUnits)
-  

[PATCH] D99696: [clang] NRVO: Improvements and handling of more cases.

2021-06-11 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov reopened this revision.
mizvekov added a comment.
This revision is now accepted and ready to land.

Thank you @stella.stamenova and @aeubanks for reporting and reverting this.

Turns out was a silly mistake where we were not digging down through 
AttributedType nodes in order to get the function type.
My bad and will try landing one more time once I do a stage2 build locally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99696

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


[PATCH] D88174: [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread Chris Hamilton 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 rGe42a347b7440: [Sema] Address-space sensitive check for 
unbounded arrays (v2) (authored by chrish_ericsson_atx).

Changed prior to commit:
  https://reviews.llvm.org/D88174?vs=350722=351461#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88174

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/const-eval.c
  clang/test/Sema/unbounded-array-bounds.c
  clang/test/SemaCXX/constant-expression-cxx14.cpp

Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1027,8 +1027,9 @@
 }
 
 constexpr void PR28739(int n) { // expected-error {{never produces a constant}}
-  int *p = 
+  int *p =   // expected-note {{array 'p' declared here}}
   p += (__int128)(unsigned long)-1; // expected-note {{cannot refer to element 18446744073709551615 of non-array object in a constant expression}}
+  // expected-warning@-1 {{the pointer incremented by 18446744073709551615 refers past the last possible element for an array in 64-bit address space containing 32-bit (4-byte) elements (max possible 4611686018427387904 elements)}}
 }
 
 constexpr void Void(int n) {
Index: clang/test/Sema/unbounded-array-bounds.c
===
--- /dev/null
+++ clang/test/Sema/unbounded-array-bounds.c
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-X86-ADDR64 %s  \
+// RUN:  --implicit-check-not 'past the last possible element'
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu   -fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-I386-ADDR32 %s \
+// RUN:  --implicit-check-not 'past the last possible element'
+// RUN: %clang_cc1 -triple avr-pc-linux-gnu-fsyntax-only %s 2>&1 | FileCheck --check-prefix=CHECK-AVR-ADDR16 %s  \
+// RUN:  --implicit-check-not 'past the last possible element'
+
+struct S {
+  long long a;
+  char b;
+  long long c;
+  short d;
+};
+
+struct S s[];
+
+void f1() {
+  ++s[3].a;
+  ++s[7073650413200313099].b;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: array index 7073650413200313099 refers past the last possible element for an array in 64-bit address space containing 256-bit (32-byte) elements (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 178956970 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+  ++s[7073650].c;
+  // CHECK-AVR-ADDR16:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+}
+
+long long ll[];
+
+void f2() {
+  ++ll[3];
+  ++ll[2705843009213693952];
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 64-bit {{.*}} (max possible 2305843009213693952 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 536870912 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 8192 elements)
+  ++ll[847073650];
+  // CHECK-I386-ADDR32: :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 536870912 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 8192 elements)
+}
+
+void f3(struct S p[]) {
+  ++p[3].a;
+  ++p[7073650413200313099].b;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 64-bit {{.*}} (max possible 576460752303423488 elements)
+  // CHECK-I386-ADDR32: :[[@LINE-2]]:5: warning: {{.*}} past the last possible element {{.*}} in 32-bit {{.*}} (max possible 178956970 elements)
+  // CHECK-AVR-ADDR16:  :[[@LINE-3]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+  ++p[7073650].c;
+  // CHECK-AVR-ADDR16:  :[[@LINE-1]]:5: warning: {{.*}} past the last possible element {{.*}} in 16-bit {{.*}} (max possible 3276 elements)
+}
+
+void f4(struct S *p) {
+  p += 3;
+  p += 7073650413200313099;
+  // CHECK-X86-ADDR64:  :[[@LINE-1]]:3: warning: the pointer incremented by 7073650413200313099 refers past the last possible element for an array in 64-bit address space containing 256-bit (32-byte) elements (max possible 576460752303423488 elements)
+  // 

[clang] e42a347 - [Sema] Address-space sensitive check for unbounded arrays (v2)

2021-06-11 Thread via cfe-commits

Author: eahcmrh
Date: 2021-06-11T17:36:16+02:00
New Revision: e42a347b74400b7212ceaaea6d39562a0435df42

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

LOG: [Sema] Address-space sensitive check for unbounded arrays (v2)

Check applied to unbounded (incomplete) arrays and pointers to spot
cases where the computed address is beyond the largest possible
addressable extent of the array, based on the address space in which the
array is delcared, or which the pointer refers to.

Check helps to avoid cases of nonsense pointer math and array indexing
which could lead to linker failures or runtime exceptions.  Of
particular interest when building for embedded systems with small
address spaces.

This is version 2 of this patch -- version 1 had some testing issues
due to a sign error in existing code.  That error is corrected and
lit test for this chagne is extended to verify the fix.

Originally reviewed/accepted by: aaron.ballman
Original revision: https://reviews.llvm.org/D86796

Reviewed By: aaron.ballman, ebevhan

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

Added: 
clang/test/Sema/unbounded-array-bounds.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/const-eval.c
clang/test/SemaCXX/constant-expression-cxx14.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index af242cffbe7de..c07e6f9d7421a 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9176,6 +9176,14 @@ def warn_array_index_precedes_bounds : Warning<
 def warn_array_index_exceeds_bounds : Warning<
   "array index %0 is past the end of the array (which contains %1 "
   "element%s2)">, InGroup;
+def warn_ptr_arith_exceeds_max_addressable_bounds : Warning<
+  "the pointer incremented by %0 refers past the last possible element for an 
array in %1-bit "
+  "address space containing %2-bit (%3-byte) elements (max possible %4 
element%s5)">,
+  InGroup;
+def warn_array_index_exceeds_max_addressable_bounds : Warning<
+  "array index %0 refers past the last possible element for an array in %1-bit 
"
+  "address space containing %2-bit (%3-byte) elements (max possible %4 
element%s5)">,
+  InGroup;
 def note_array_declared_here : Note<
   "array %0 declared here">;
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 91498293d60e2..309cb7c0b2cb4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14536,11 +14536,11 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   const ConstantArrayType *ArrayTy =
   Context.getAsConstantArrayType(BaseExpr->getType());
 
-  if (!ArrayTy)
-return;
-
-  const Type *BaseType = ArrayTy->getElementType().getTypePtr();
-  if (EffectiveType->isDependentType() || BaseType->isDependentType())
+  const Type *BaseType =
+  ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
+  bool IsUnboundedArray = (BaseType == nullptr);
+  if (EffectiveType->isDependentType() ||
+  (!IsUnboundedArray && BaseType->isDependentType()))
 return;
 
   Expr::EvalResult Result;
@@ -14548,8 +14548,10 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
 return;
 
   llvm::APSInt index = Result.Val.getInt();
-  if (IndexNegated)
+  if (IndexNegated) {
+index.setIsUnsigned(false);
 index = -index;
+  }
 
   const NamedDecl *ND = nullptr;
   if (const DeclRefExpr *DRE = dyn_cast(BaseExpr))
@@ -14557,6 +14559,69 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   if (const MemberExpr *ME = dyn_cast(BaseExpr))
 ND = ME->getMemberDecl();
 
+  if (IsUnboundedArray) {
+if (index.isUnsigned() || !index.isNegative()) {
+  const auto  = getASTContext();
+  unsigned AddrBits =
+  ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
+  EffectiveType->getCanonicalTypeInternal()));
+  if (index.getBitWidth() < AddrBits)
+index = index.zext(AddrBits);
+  CharUnits ElemCharUnits = ASTC.getTypeSizeInChars(EffectiveType);
+  llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits.getQuantity());
+  // If index has more active bits than address space, we already know
+  // we have a bounds violation to warn about.  Otherwise, compute
+  // address of (index + 1)th element, and warn about bounds violation
+  // only if that address exceeds address space.
+  if (index.getActiveBits() <= AddrBits) {
+bool Overflow;
+llvm::APInt Product(index);
+Product += 1;
+Product = Product.umul_ov(ElemBytes, 

[PATCH] D102901: [HWASan] Add basic stack tagging support for LAM.

2021-06-11 Thread Matt Morehouse 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 rG0867edfc6438: [HWASan] Add basic stack tagging support for 
LAM. (authored by morehouse).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102901

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize.c
  compiler-rt/test/hwasan/TestCases/deep-recursion.c
  compiler-rt/test/hwasan/TestCases/longjmp.c
  compiler-rt/test/hwasan/TestCases/mem-intrinsics.c
  compiler-rt/test/hwasan/TestCases/rich-stack.c
  compiler-rt/test/hwasan/TestCases/stack-history-length.c
  compiler-rt/test/hwasan/TestCases/stack-oob.c
  compiler-rt/test/hwasan/TestCases/stack-uar-dynamic.c
  compiler-rt/test/hwasan/TestCases/stack-uar-realign.c
  compiler-rt/test/hwasan/TestCases/stack-uar.c
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
  llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-array.ll
  llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-with-calls.ll
  llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca.ll

Index: llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca.ll
@@ -0,0 +1,45 @@
+; Test alloca instrumentation.
+;
+; RUN: opt < %s -hwasan -S | FileCheck %s --check-prefixes=CHECK,NO-UAR-TAGS
+; RUN: opt < %s -hwasan -hwasan-uar-retag-to-zero=0 -S | FileCheck %s --check-prefixes=CHECK,UAR-TAGS
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use32(i32*)
+
+define void @test_alloca() sanitize_hwaddress {
+; CHECK-LABEL: @test_alloca(
+; CHECK: %[[FP:[^ ]*]] = call i8* @llvm.frameaddress.p0i8(i32 0)
+; CHECK: %[[A:[^ ]*]] = ptrtoint i8* %[[FP]] to i64
+; CHECK: %[[B:[^ ]*]] = lshr i64 %[[A]], 20
+; CHECK: %[[A_XOR_B:[^ ]*]] = xor i64 %[[A]], %[[B]]
+; CHECK: %[[BASE_TAG:[^ ]*]] = and i64 %[[A_XOR_B]], 63
+
+; CHECK: %[[X:[^ ]*]] = alloca { i32, [12 x i8] }, align 16
+; CHECK: %[[X_BC:[^ ]*]] = bitcast { i32, [12 x i8] }* %[[X]] to i32*
+; CHECK: %[[X_TAG:[^ ]*]] = xor i64 %[[BASE_TAG]], 0
+; CHECK: %[[X1:[^ ]*]] = ptrtoint i32* %[[X_BC]] to i64
+; CHECK: %[[C:[^ ]*]] = shl i64 %[[X_TAG]], 57
+; CHECK: %[[D:[^ ]*]] = or i64 %[[X1]], %[[C]]
+; CHECK: %[[X_HWASAN:[^ ]*]] = inttoptr i64 %[[D]] to i32*
+
+; CHECK: %[[X_TAG2:[^ ]*]] = trunc i64 %[[X_TAG]] to i8
+; CHECK: %[[X_I8:[^ ]*]] = bitcast i32* %[[X_BC]] to i8*
+; CHECK: call void @__hwasan_tag_memory(i8* %[[X_I8]], i8 %[[X_TAG2]], i64 16)
+
+; CHECK: call void @use32(i32* nonnull %[[X_HWASAN]])
+
+; UAR-TAGS: %[[BASE_TAG_COMPL:[^ ]*]] = xor i64 %[[BASE_TAG]], 63
+; UAR-TAGS: %[[X_TAG_UAR:[^ ]*]] = trunc i64 %[[BASE_TAG_COMPL]] to i8
+; CHECK: %[[X_I8_2:[^ ]*]] = bitcast i32* %[[X_BC]] to i8*
+; NO-UAR-TAGS: call void @__hwasan_tag_memory(i8* %[[X_I8_2]], i8 0, i64 16)
+; UAR-TAGS: call void @__hwasan_tag_memory(i8* %[[X_I8_2]], i8 %[[X_TAG_UAR]], i64 16)
+; CHECK: ret void
+
+
+entry:
+  %x = alloca i32, align 4
+  call void @use32(i32* nonnull %x)
+  ret void
+}
Index: llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-with-calls.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-with-calls.ll
@@ -0,0 +1,23 @@
+; Test alloca instrumentation when tags are generated by HWASan function.
+;
+; RUN: opt < %s -hwasan -hwasan-generate-tags-with-calls -S | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use32(i32*)
+
+define void @test_alloca() sanitize_hwaddress {
+; CHECK-LABEL: @test_alloca(
+; CHECK: %[[BC:[^ ]*]] = bitcast { i32, [12 x i8] }* %x to i32*
+; CHECK: %[[T1:[^ ]*]] = call i8 @__hwasan_generate_tag()
+; CHECK: %[[A:[^ ]*]] = zext i8 %[[T1]] to i64
+; CHECK: %[[B:[^ ]*]] = ptrtoint i32* %[[BC]] to i64
+; CHECK: %[[C:[^ ]*]] = shl i64 %[[A]], 57
+; CHECK: or i64 %[[B]], %[[C]]
+
+entry:
+  %x = alloca i32, align 4
+  call void @use32(i32* nonnull %x)
+  ret void
+}
Index: llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-array.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-array.ll
@@ -0,0 +1,15 @@
+; RUN: opt < %s -hwasan -S | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use(i8*, i8*)
+
+define void @test_alloca() sanitize_hwaddress {
+  ; CHECK: alloca { [4 x i8], [12 x i8] }, align 16
+  %x = alloca i8, i64 4
+  ; CHECK: alloca i8, i64 16, align 16
+  %y = alloca i8, i64 16
+  call void @use(i8* %x, i8* %y)
+  ret void
+}
Index: 

[PATCH] D102901: [HWASan] Add basic stack tagging support for LAM.

2021-06-11 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse updated this revision to Diff 351459.
morehouse added a comment.

- Fix clang test failure on Windows.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102901

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize.c
  compiler-rt/test/hwasan/TestCases/deep-recursion.c
  compiler-rt/test/hwasan/TestCases/longjmp.c
  compiler-rt/test/hwasan/TestCases/mem-intrinsics.c
  compiler-rt/test/hwasan/TestCases/rich-stack.c
  compiler-rt/test/hwasan/TestCases/stack-history-length.c
  compiler-rt/test/hwasan/TestCases/stack-oob.c
  compiler-rt/test/hwasan/TestCases/stack-uar-dynamic.c
  compiler-rt/test/hwasan/TestCases/stack-uar-realign.c
  compiler-rt/test/hwasan/TestCases/stack-uar.c
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
  llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-array.ll
  llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-with-calls.ll
  llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca.ll

Index: llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca.ll
@@ -0,0 +1,45 @@
+; Test alloca instrumentation.
+;
+; RUN: opt < %s -hwasan -S | FileCheck %s --check-prefixes=CHECK,NO-UAR-TAGS
+; RUN: opt < %s -hwasan -hwasan-uar-retag-to-zero=0 -S | FileCheck %s --check-prefixes=CHECK,UAR-TAGS
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use32(i32*)
+
+define void @test_alloca() sanitize_hwaddress {
+; CHECK-LABEL: @test_alloca(
+; CHECK: %[[FP:[^ ]*]] = call i8* @llvm.frameaddress.p0i8(i32 0)
+; CHECK: %[[A:[^ ]*]] = ptrtoint i8* %[[FP]] to i64
+; CHECK: %[[B:[^ ]*]] = lshr i64 %[[A]], 20
+; CHECK: %[[A_XOR_B:[^ ]*]] = xor i64 %[[A]], %[[B]]
+; CHECK: %[[BASE_TAG:[^ ]*]] = and i64 %[[A_XOR_B]], 63
+
+; CHECK: %[[X:[^ ]*]] = alloca { i32, [12 x i8] }, align 16
+; CHECK: %[[X_BC:[^ ]*]] = bitcast { i32, [12 x i8] }* %[[X]] to i32*
+; CHECK: %[[X_TAG:[^ ]*]] = xor i64 %[[BASE_TAG]], 0
+; CHECK: %[[X1:[^ ]*]] = ptrtoint i32* %[[X_BC]] to i64
+; CHECK: %[[C:[^ ]*]] = shl i64 %[[X_TAG]], 57
+; CHECK: %[[D:[^ ]*]] = or i64 %[[X1]], %[[C]]
+; CHECK: %[[X_HWASAN:[^ ]*]] = inttoptr i64 %[[D]] to i32*
+
+; CHECK: %[[X_TAG2:[^ ]*]] = trunc i64 %[[X_TAG]] to i8
+; CHECK: %[[X_I8:[^ ]*]] = bitcast i32* %[[X_BC]] to i8*
+; CHECK: call void @__hwasan_tag_memory(i8* %[[X_I8]], i8 %[[X_TAG2]], i64 16)
+
+; CHECK: call void @use32(i32* nonnull %[[X_HWASAN]])
+
+; UAR-TAGS: %[[BASE_TAG_COMPL:[^ ]*]] = xor i64 %[[BASE_TAG]], 63
+; UAR-TAGS: %[[X_TAG_UAR:[^ ]*]] = trunc i64 %[[BASE_TAG_COMPL]] to i8
+; CHECK: %[[X_I8_2:[^ ]*]] = bitcast i32* %[[X_BC]] to i8*
+; NO-UAR-TAGS: call void @__hwasan_tag_memory(i8* %[[X_I8_2]], i8 0, i64 16)
+; UAR-TAGS: call void @__hwasan_tag_memory(i8* %[[X_I8_2]], i8 %[[X_TAG_UAR]], i64 16)
+; CHECK: ret void
+
+
+entry:
+  %x = alloca i32, align 4
+  call void @use32(i32* nonnull %x)
+  ret void
+}
Index: llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-with-calls.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-with-calls.ll
@@ -0,0 +1,23 @@
+; Test alloca instrumentation when tags are generated by HWASan function.
+;
+; RUN: opt < %s -hwasan -hwasan-generate-tags-with-calls -S | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use32(i32*)
+
+define void @test_alloca() sanitize_hwaddress {
+; CHECK-LABEL: @test_alloca(
+; CHECK: %[[BC:[^ ]*]] = bitcast { i32, [12 x i8] }* %x to i32*
+; CHECK: %[[T1:[^ ]*]] = call i8 @__hwasan_generate_tag()
+; CHECK: %[[A:[^ ]*]] = zext i8 %[[T1]] to i64
+; CHECK: %[[B:[^ ]*]] = ptrtoint i32* %[[BC]] to i64
+; CHECK: %[[C:[^ ]*]] = shl i64 %[[A]], 57
+; CHECK: or i64 %[[B]], %[[C]]
+
+entry:
+  %x = alloca i32, align 4
+  call void @use32(i32* nonnull %x)
+  ret void
+}
Index: llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-array.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/X86/alloca-array.ll
@@ -0,0 +1,15 @@
+; RUN: opt < %s -hwasan -S | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use(i8*, i8*)
+
+define void @test_alloca() sanitize_hwaddress {
+  ; CHECK: alloca { [4 x i8], [12 x i8] }, align 16
+  %x = alloca i8, i64 4
+  ; CHECK: alloca i8, i64 16, align 16
+  %y = alloca i8, i64 16
+  call void @use(i8* %x, i8* %y)
+  ret void
+}
Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- 

[PATCH] D104118: [OpenCL] Use DW_LANG_OpenCL language tag for OpenCL C

2021-06-11 Thread Stuart Brady via Phabricator via cfe-commits
stuart updated this revision to Diff 351454.
stuart added a comment.

Add missing trailing commas to CHECK lines of FileCheck test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104118

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenOpenCL/debug-info-programming-language.cl


Index: clang/test/CodeGenOpenCL/debug-info-programming-language.cl
===
--- /dev/null
+++ clang/test/CodeGenOpenCL/debug-info-programming-language.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -dwarf-version=5  -emit-llvm -triple %itanium_abi_triple %s 
-o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF5 %s
+// RUN: %clang_cc1 -dwarf-version=3  -emit-llvm -triple %itanium_abi_triple %s 
-o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF3 %s
+
+kernel void empty() {}
+
+// CHECK-DWARF5: distinct !DICompileUnit(language: DW_LANG_OpenCL,
+// CHECK-DWARF3: distinct !DICompileUnit(language: DW_LANG_C99,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -576,6 +576,8 @@
   LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
   } else if (LO.ObjC) {
 LangTag = llvm::dwarf::DW_LANG_ObjC;
+  } else if (LO.OpenCL && CGM.getCodeGenOpts().DwarfVersion >= 5) {
+LangTag = llvm::dwarf::DW_LANG_OpenCL;
   } else if (LO.RenderScript) {
 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
   } else if (LO.C99) {


Index: clang/test/CodeGenOpenCL/debug-info-programming-language.cl
===
--- /dev/null
+++ clang/test/CodeGenOpenCL/debug-info-programming-language.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -dwarf-version=5  -emit-llvm -triple %itanium_abi_triple %s -o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF5 %s
+// RUN: %clang_cc1 -dwarf-version=3  -emit-llvm -triple %itanium_abi_triple %s -o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF3 %s
+
+kernel void empty() {}
+
+// CHECK-DWARF5: distinct !DICompileUnit(language: DW_LANG_OpenCL,
+// CHECK-DWARF3: distinct !DICompileUnit(language: DW_LANG_C99,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -576,6 +576,8 @@
   LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
   } else if (LO.ObjC) {
 LangTag = llvm::dwarf::DW_LANG_ObjC;
+  } else if (LO.OpenCL && CGM.getCodeGenOpts().DwarfVersion >= 5) {
+LangTag = llvm::dwarf::DW_LANG_OpenCL;
   } else if (LO.RenderScript) {
 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
   } else if (LO.C99) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D104118: [OpenCL] Use DW_LANG_OpenCL language tag for OpenCL C

2021-06-11 Thread Stuart Brady via Phabricator via cfe-commits
stuart added a comment.

Note: there is currently no DWARF language code defined for //C++ for OpenCL//, 
so we must use DW_LANG_C_plus_plus* if we wish to be able to determine whether 
output has been generated from //C++ for OpenCL// source or from //OpenCL C// 
source. I have raised DWARF issue 210514.1 
 to add a dedicated //C++ for 
OpenCL// code in the next version of DWARF, but for now I believe that it is 
best to use DW_LANG_OpenCL for //OpenCL C// only, and not for //C++ for 
OpenCL//.

I could perhaps add a note regarding this to the commit message but am 
concerned about overcomplicating the message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104118

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 351445.
lebedev.ri added a comment.

... and upload the right patch this time.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

Files:
  clang/test/CodeGen/thinlto-distributed-newpm.ll
  llvm/lib/Passes/PassBuilder.cpp
  llvm/test/Other/new-pm-defaults.ll
  llvm/test/Other/new-pm-thinlto-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
  llvm/test/Transforms/LoopUnroll/AArch64/runtime-unroll-generic.ll
  
llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
  llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll

Index: llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll
===
--- llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll
+++ llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll
@@ -104,21 +104,18 @@
 ; ROTATED_LATER_NEWPM-NEXT:br i1 [[CMP13_NOT]], label [[FOR_COND_CLEANUP:%.*]], label [[FOR_BODY_PREHEADER:%.*]]
 ; ROTATED_LATER_NEWPM:   for.body.preheader:
 ; ROTATED_LATER_NEWPM-NEXT:[[TMP0:%.*]] = add nsw i32 [[WIDTH]], -1
-; ROTATED_LATER_NEWPM-NEXT:[[INC_1:%.*]] = add nuw nsw i32 0, 1
 ; ROTATED_LATER_NEWPM-NEXT:br label [[FOR_BODY:%.*]]
 ; ROTATED_LATER_NEWPM:   for.cond.cleanup:
 ; ROTATED_LATER_NEWPM-NEXT:tail call void @f0()
 ; ROTATED_LATER_NEWPM-NEXT:tail call void @f2()
 ; ROTATED_LATER_NEWPM-NEXT:br label [[RETURN]]
 ; ROTATED_LATER_NEWPM:   for.body:
-; ROTATED_LATER_NEWPM-NEXT:[[INC_PHI:%.*]] = phi i32 [ [[INC_0:%.*]], [[FOR_BODY_FOR_BODY_CRIT_EDGE:%.*]] ], [ [[INC_1]], [[FOR_BODY_PREHEADER]] ]
+; ROTATED_LATER_NEWPM-NEXT:[[I_04:%.*]] = phi i32 [ [[INC:%.*]], [[FOR_BODY]] ], [ 0, [[FOR_BODY_PREHEADER]] ]
 ; ROTATED_LATER_NEWPM-NEXT:tail call void @f0()
 ; ROTATED_LATER_NEWPM-NEXT:tail call void @f1()
-; ROTATED_LATER_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC_PHI]], [[TMP0]]
-; ROTATED_LATER_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY_FOR_BODY_CRIT_EDGE]]
-; ROTATED_LATER_NEWPM:   for.body.for.body_crit_edge:
-; ROTATED_LATER_NEWPM-NEXT:[[INC_0]] = add nuw nsw i32 [[INC_PHI]], 1
-; ROTATED_LATER_NEWPM-NEXT:br label [[FOR_BODY]]
+; ROTATED_LATER_NEWPM-NEXT:[[INC]] = add nuw nsw i32 [[I_04]], 1
+; ROTATED_LATER_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC]], [[TMP0]]
+; ROTATED_LATER_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY]]
 ; ROTATED_LATER_NEWPM:   return:
 ; ROTATED_LATER_NEWPM-NEXT:ret void
 ;
@@ -155,21 +152,18 @@
 ; ROTATE_NEWPM-NEXT:br i1 [[CMP13_NOT]], label [[FOR_COND_CLEANUP:%.*]], label [[FOR_BODY_PREHEADER:%.*]]
 ; ROTATE_NEWPM:   for.body.preheader:
 ; ROTATE_NEWPM-NEXT:[[TMP0:%.*]] = add nsw i32 [[WIDTH]], -1
-; ROTATE_NEWPM-NEXT:[[INC_1:%.*]] = add nuw nsw i32 0, 1
 ; ROTATE_NEWPM-NEXT:br label [[FOR_BODY:%.*]]
 ; ROTATE_NEWPM:   for.cond.cleanup:
 ; ROTATE_NEWPM-NEXT:tail call void @f0()
 ; ROTATE_NEWPM-NEXT:tail call void @f2()
 ; ROTATE_NEWPM-NEXT:br label [[RETURN]]
 ; ROTATE_NEWPM:   for.body:
-; ROTATE_NEWPM-NEXT:[[INC_PHI:%.*]] = phi i32 [ [[INC_0:%.*]], [[FOR_BODY_FOR_BODY_CRIT_EDGE:%.*]] ], [ [[INC_1]], [[FOR_BODY_PREHEADER]] ]
+; ROTATE_NEWPM-NEXT:[[I_04:%.*]] = phi i32 [ [[INC:%.*]], [[FOR_BODY]] ], [ 0, [[FOR_BODY_PREHEADER]] ]
 ; ROTATE_NEWPM-NEXT:tail call void @f0()
 ; ROTATE_NEWPM-NEXT:tail call void @f1()
-; ROTATE_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC_PHI]], [[TMP0]]
-; ROTATE_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY_FOR_BODY_CRIT_EDGE]]
-; ROTATE_NEWPM:   for.body.for.body_crit_edge:
-; ROTATE_NEWPM-NEXT:[[INC_0]] = add nuw nsw i32 [[INC_PHI]], 1
-; ROTATE_NEWPM-NEXT:br label [[FOR_BODY]]
+; ROTATE_NEWPM-NEXT:[[INC]] = add nuw nsw i32 [[I_04]], 1
+; ROTATE_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC]], [[TMP0]]
+; ROTATE_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY]]
 ; ROTATE_NEWPM:   return:
 ; ROTATE_NEWPM-NEXT:ret void
 ;
Index: llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
===
--- llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
+++ llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
@@ -156,36 +156,27 @@
 ; CHECK:   vector.ph:
 ; CHECK-NEXT:[[BROADCAST_SPLATINSERT:%.*]] = insertelement <4 x float> poison, float [[X:%.*]], i32 0
 ; CHECK-NEXT:[[BROADCAST_SPLAT:%.*]] = 

[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 351444.
lebedev.ri added a comment.
Herald added a subscriber: zzheng.

Update a few more tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

Files:
  clang/test/CodeGen/thinlto-distributed-newpm.ll
  llvm/lib/Passes/PassBuilder.cpp
  llvm/test/Other/new-pm-defaults.ll
  llvm/test/Other/new-pm-thinlto-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
  llvm/test/Transforms/LoopUnroll/AArch64/runtime-unroll-generic.ll
  
llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
  llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll

Index: llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll
===
--- llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll
+++ llvm/test/Transforms/PhaseOrdering/loop-rotation-vs-common-code-hoisting.ll
@@ -107 +106,0 @@
-; ROTATED_LATER_NEWPM-NEXT:[[INC_1:%.*]] = add nuw nsw i32 0, 1
@@ -114 +113 @@
-; ROTATED_LATER_NEWPM-NEXT:[[INC_PHI:%.*]] = phi i32 [ [[INC_0:%.*]], [[FOR_BODY_FOR_BODY_CRIT_EDGE:%.*]] ], [ [[INC_1]], [[FOR_BODY_PREHEADER]] ]
+; ROTATED_LATER_NEWPM-NEXT:[[I_04:%.*]] = phi i32 [ [[INC:%.*]], [[FOR_BODY]] ], [ 0, [[FOR_BODY_PREHEADER]] ]
@@ -117,5 +116,3 @@
-; ROTATED_LATER_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC_PHI]], [[TMP0]]
-; ROTATED_LATER_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY_FOR_BODY_CRIT_EDGE]]
-; ROTATED_LATER_NEWPM:   for.body.for.body_crit_edge:
-; ROTATED_LATER_NEWPM-NEXT:[[INC_0]] = add nuw nsw i32 [[INC_PHI]], 1
-; ROTATED_LATER_NEWPM-NEXT:br label [[FOR_BODY]]
+; ROTATED_LATER_NEWPM-NEXT:[[INC]] = add nuw nsw i32 [[I_04]], 1
+; ROTATED_LATER_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC]], [[TMP0]]
+; ROTATED_LATER_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY]]
@@ -158 +154,0 @@
-; ROTATE_NEWPM-NEXT:[[INC_1:%.*]] = add nuw nsw i32 0, 1
@@ -165 +161 @@
-; ROTATE_NEWPM-NEXT:[[INC_PHI:%.*]] = phi i32 [ [[INC_0:%.*]], [[FOR_BODY_FOR_BODY_CRIT_EDGE:%.*]] ], [ [[INC_1]], [[FOR_BODY_PREHEADER]] ]
+; ROTATE_NEWPM-NEXT:[[I_04:%.*]] = phi i32 [ [[INC:%.*]], [[FOR_BODY]] ], [ 0, [[FOR_BODY_PREHEADER]] ]
@@ -168,5 +164,3 @@
-; ROTATE_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC_PHI]], [[TMP0]]
-; ROTATE_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY_FOR_BODY_CRIT_EDGE]]
-; ROTATE_NEWPM:   for.body.for.body_crit_edge:
-; ROTATE_NEWPM-NEXT:[[INC_0]] = add nuw nsw i32 [[INC_PHI]], 1
-; ROTATE_NEWPM-NEXT:br label [[FOR_BODY]]
+; ROTATE_NEWPM-NEXT:[[INC]] = add nuw nsw i32 [[I_04]], 1
+; ROTATE_NEWPM-NEXT:[[EXITCOND_NOT:%.*]] = icmp eq i32 [[INC]], [[TMP0]]
+; ROTATE_NEWPM-NEXT:br i1 [[EXITCOND_NOT]], label [[FOR_COND_CLEANUP]], label [[FOR_BODY]]
Index: llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
===
--- llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
+++ llvm/test/Transforms/PhaseOrdering/AArch64/hoisting-sinking-required-for-vectorization.ll
@@ -159,4 +158,0 @@
-; CHECK-NEXT:[[DOT0:%.*]] = getelementptr inbounds i32, i32* [[C]], i64 0
-; CHECK-NEXT:[[DOT017:%.*]] = getelementptr inbounds float, float* [[A]], i64 0
-; CHECK-NEXT:[[DOT018:%.*]] = getelementptr inbounds float, float* [[B]], i64 0
-; CHECK-NEXT:[[INDEX_NEXT_0:%.*]] = add nuw i64 0, 4
@@ -165,24 +161,19 @@
-; CHECK-NEXT:[[INDEX_NEXT_PHI:%.*]] = phi i64 [ [[INDEX_NEXT_0]], [[VECTOR_PH]] ], [ [[INDEX_NEXT_1:%.*]], [[VECTOR_BODY_VECTOR_BODY_CRIT_EDGE:%.*]] ]
-; CHECK-NEXT:[[DOTPHI:%.*]] = phi float* [ [[DOT018]], [[VECTOR_PH]] ], [ [[DOT120:%.*]], [[VECTOR_BODY_VECTOR_BODY_CRIT_EDGE]] ]
-; CHECK-NEXT:[[DOTPHI21:%.*]] = phi float* [ [[DOT017]], [[VECTOR_PH]] ], [ [[DOT119:%.*]], [[VECTOR_BODY_VECTOR_BODY_CRIT_EDGE]] ]
-; CHECK-NEXT:[[DOTPHI22:%.*]] = phi i32* [ [[DOT0]], [[VECTOR_PH]] ], [ [[DOT1:%.*]], [[VECTOR_BODY_VECTOR_BODY_CRIT_EDGE]] ]
-; CHECK-NEXT:[[TMP2:%.*]] = bitcast i32* [[DOTPHI22]] to <4 x i32>*
-; CHECK-NEXT:[[WIDE_LOAD:%.*]] = load <4 x i32>, <4 x i32>* [[TMP2]], align 4, !alias.scope !8
-; CHECK-NEXT:[[TMP3:%.*]] = icmp eq <4 x i32> [[WIDE_LOAD]], 
-; CHECK-NEXT:[[TMP4:%.*]] = bitcast float* [[DOTPHI21]] to <4 x float>*
-; CHECK-NEXT:[[WIDE_LOAD14:%.*]] = load <4 x float>, <4 x float>* [[TMP4]], align 4, !alias.scope !11
-; CHECK-NEXT:[[TMP5:%.*]] = fmul <4 x float> [[WIDE_LOAD14]], [[BROADCAST_SPLAT]]
-; CHECK-NEXT:[[TMP6:%.*]] = bitcast float* [[DOTPHI]] to <4 x float>*
-; 

[PATCH] D104118: [OpenCL] Use DW_LANG_OpenCL language tag for OpenCL C

2021-06-11 Thread Stuart Brady via Phabricator via cfe-commits
stuart created this revision.
stuart added reviewers: Anastasia, keith.walker.arm, svenvh, aprantl, SouraVX, 
shchenz, jzzheng22.
Herald added subscribers: ldrumm, yaxunl.
stuart requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104118

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenOpenCL/debug-info-programming-language.cl


Index: clang/test/CodeGenOpenCL/debug-info-programming-language.cl
===
--- /dev/null
+++ clang/test/CodeGenOpenCL/debug-info-programming-language.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -dwarf-version=5  -emit-llvm -triple %itanium_abi_triple %s 
-o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF5 %s
+// RUN: %clang_cc1 -dwarf-version=3  -emit-llvm -triple %itanium_abi_triple %s 
-o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF3 %s
+
+kernel void empty() {}
+
+// CHECK-DWARF5: distinct !DICompileUnit(language: DW_LANG_OpenCL
+// CHECK-DWARF3: distinct !DICompileUnit(language: DW_LANG_C99
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -576,6 +576,8 @@
   LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
   } else if (LO.ObjC) {
 LangTag = llvm::dwarf::DW_LANG_ObjC;
+  } else if (LO.OpenCL && CGM.getCodeGenOpts().DwarfVersion >= 5) {
+LangTag = llvm::dwarf::DW_LANG_OpenCL;
   } else if (LO.RenderScript) {
 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
   } else if (LO.C99) {


Index: clang/test/CodeGenOpenCL/debug-info-programming-language.cl
===
--- /dev/null
+++ clang/test/CodeGenOpenCL/debug-info-programming-language.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -dwarf-version=5  -emit-llvm -triple %itanium_abi_triple %s -o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF5 %s
+// RUN: %clang_cc1 -dwarf-version=3  -emit-llvm -triple %itanium_abi_triple %s -o - \
+// RUN:   -x cl -O0 -disable-llvm-passes -debug-info-kind=limited \
+// RUN: | FileCheck --check-prefix=CHECK-DWARF3 %s
+
+kernel void empty() {}
+
+// CHECK-DWARF5: distinct !DICompileUnit(language: DW_LANG_OpenCL
+// CHECK-DWARF3: distinct !DICompileUnit(language: DW_LANG_C99
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -576,6 +576,8 @@
   LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
   } else if (LO.ObjC) {
 LangTag = llvm::dwarf::DW_LANG_ObjC;
+  } else if (LO.OpenCL && CGM.getCodeGenOpts().DwarfVersion >= 5) {
+LangTag = llvm::dwarf::DW_LANG_OpenCL;
   } else if (LO.RenderScript) {
 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
   } else if (LO.C99) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D104117: [clangd] Fix highlighting for implicit ObjC property refs

2021-06-11 Thread David Goldman via Phabricator via cfe-commits
dgoldman created this revision.
dgoldman added reviewers: sammccall, kadircet.
Herald added subscribers: usaxena95, arphaman.
dgoldman requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Objective-C lets you use the `self.prop` syntax as sugar for both
`[self prop]` and `[self setProp:]`, but clangd previously did not
provide a semantic token for `prop`.

Now, we provide a semantic token, treating it like a normal property
except it's backed by a `ObjCMethodDecl` instead of a
`ObjCPropertyDecl`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D104117

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -696,11 +696,16 @@
   int $Field_decl[[_someProperty]];
 }
 @property(nonatomic, assign) int $Field_decl[[someProperty]];
+@property(readonly, class) $Class[[Foo]] 
*$Field_decl_readonly_static[[sharedInstance]];
 @end
 @implementation $Class_decl[[Foo]]
 @synthesize someProperty = _someProperty;
+- (int)$Method_decl[[otherMethod]] {
+  return 0;
+}
 - (int)$Method_decl[[doSomething]] {
-  self.$Field[[someProperty]] = self.$Field[[someProperty]] + 1;
+  $Class[[Foo]].$Field_static[[sharedInstance]].$Field[[someProperty]] 
= 1;
+  self.$Field[[someProperty]] = self.$Field[[someProperty]] + 
self.$Field[[otherMethod]] + 1;
   self->$Field[[_someProperty]] = $Field[[_someProperty]] + 1;
 }
 @end
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -556,6 +556,40 @@
 return true;
   }
 
+  // Objective-C allows you to use property syntax `self.prop` as sugar for
+  // `[self prop]` and `[self setProp:]` when there's no explicit `@property`
+  // for `prop`. We treat this like a property even though semantically it's
+  // equivalent to a method expression.
+  void highlightObjCImplicitPropertyRef(const ObjCMethodDecl *OMD,
+SourceLocation Loc) {
+auto  = H.addToken(Loc, HighlightingKind::Field)
+.addModifier(HighlightingModifier::ClassScope);
+if (OMD->isClassMethod())
+  Tok.addModifier(HighlightingModifier::Static);
+if (isDefaultLibrary(OMD))
+  Tok.addModifier(HighlightingModifier::DefaultLibrary);
+  }
+
+  bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *OPRE) {
+// We need to handle implicit properties here since they will appear to
+// reference `ObjCMethodDecl` via an implicit `ObjCMessageExpr`, so normal
+// highlighting will not work.
+if (!OPRE->isImplicitProperty())
+  return true;
+// A single property expr can reference both a getter and setter, but we 
can
+// only provide a single semantic token, so prefer the getter.
+if (OPRE->isMessagingGetter()) {
+  highlightObjCImplicitPropertyRef(OPRE->getImplicitPropertyGetter(),
+   OPRE->getLocation());
+  return true;
+}
+if (OPRE->isMessagingSetter()) {
+  highlightObjCImplicitPropertyRef(OPRE->getImplicitPropertySetter(),
+   OPRE->getLocation());
+}
+return true;
+  }
+
   bool VisitOverloadExpr(OverloadExpr *E) {
 if (!E->decls().empty())
   return true; // handled by findExplicitReferences.


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -696,11 +696,16 @@
   int $Field_decl[[_someProperty]];
 }
 @property(nonatomic, assign) int $Field_decl[[someProperty]];
+@property(readonly, class) $Class[[Foo]] *$Field_decl_readonly_static[[sharedInstance]];
 @end
 @implementation $Class_decl[[Foo]]
 @synthesize someProperty = _someProperty;
+- (int)$Method_decl[[otherMethod]] {
+  return 0;
+}
 - (int)$Method_decl[[doSomething]] {
-  self.$Field[[someProperty]] = self.$Field[[someProperty]] + 1;
+  $Class[[Foo]].$Field_static[[sharedInstance]].$Field[[someProperty]] = 1;
+  self.$Field[[someProperty]] = self.$Field[[someProperty]] + self.$Field[[otherMethod]] + 1;
   self->$Field[[_someProperty]] = 

[clang] 150f7ce - Referencing a static function defined in an opnemp clause, is

2021-06-11 Thread Zahira Ammarguellat via cfe-commits

Author: Zahira Ammarguellat
Date: 2021-06-11T06:56:01-07:00
New Revision: 150f7cedfb2e072804f4a0887d14c97a7fe3f374

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

LOG: Referencing a static function defined in an opnemp clause, is
generating an erroneous warning.

See here: https://godbolt.org/z/ajKPc36M7

Added: 
clang/test/OpenMP/declare_variant.cpp

Modified: 
clang/lib/Sema/Sema.cpp

Removed: 




diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 8fd4c680d3bff..850c189cc51a3 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -812,8 +812,21 @@ static void checkUndefinedButUsed(Sema ) {
   // FIXME: We can promote this to an error. The function or variable can't
   // be defined anywhere else, so the program must necessarily violate the
   // one definition rule.
-  S.Diag(VD->getLocation(), diag::warn_undefined_internal)
-<< isa(VD) << VD;
+  bool IsImplicitBase = false;
+  if (const auto *BaseD = dyn_cast(VD)) {
+auto *DVAttr = BaseD->getAttr();
+if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
+  llvm::omp::TraitProperty::
+  implementation_extension_disable_implicit_base)) 
{
+  const auto *Func = cast(
+  cast(DVAttr->getVariantFuncRef())->getDecl());
+  IsImplicitBase = BaseD->isImplicit() &&
+   Func->getIdentifier()->isMangledOpenMPVariantName();
+}
+  }
+  if (!S.getLangOpts().OpenMP || !IsImplicitBase)
+S.Diag(VD->getLocation(), diag::warn_undefined_internal)
+<< isa(VD) << VD;
 } else if (auto *FD = dyn_cast(VD)) {
   (void)FD;
   assert(FD->getMostRecentDecl()->isInlined() &&

diff  --git a/clang/test/OpenMP/declare_variant.cpp 
b/clang/test/OpenMP/declare_variant.cpp
new file mode 100644
index 0..86d0b5c7d81a1
--- /dev/null
+++ b/clang/test/OpenMP/declare_variant.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -verify %s
+
+namespace {
+// TODO this must be fixed. This warning shouldn't be generated.
+// expected-warning@+1{{function '(anonymous namespace)::bar' has internal 
linkage but is not defined}}
+void bar();
+} // namespace
+
+#pragma omp begin declare variant match(user = {condition(1)})
+void bar() {
+}
+#pragma omp end declare variant
+
+// expected-warning@+1{{function 'baz' has internal linkage but is not 
defined}}
+static void baz();
+#pragma omp begin declare variant match(device = {kind(nohost)})
+static void baz() {}
+#pragma omp end declare variant
+
+#pragma omp begin declare variant match(device = {kind(host)})
+static void foo() {}
+#pragma omp end declare variant
+
+int main() {
+  foo();
+  // expected-note@+1{{used here}}
+  baz();
+  // expected-note@+1{{used here}}
+  bar();
+
+  return 0;
+}



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


[PATCH] D104112: [clang-tidy] cppcoreguidelines-avoid-init-default-constructors: a new check

2021-06-11 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

What about bit filed members - their initialization is supported only in C++20.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104112

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


[PATCH] D104112: [clang-tidy] cppcoreguidelines-avoid-init-default-constructors: a new check

2021-06-11 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidInitDefaultConstructorsCheck.h:28
+  bool isLanguageVersionSupported(const LangOptions ) const override {
+return LangOpts.CPlusPlus;
+  }

Shouldn't this check be enabled in C++11 or newer?



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-avoid-init-default-constructors.rst:6
+
+This check flags constructors which are only initializing class members.
+Such constructors can be omitted, because the initialization could be

Please synchronize this statement with Release Notes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104112

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


[clang] f7bc9db - Fix Wdocumentation missing parameter warnings. NFCI.

2021-06-11 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2021-06-11T14:32:35+01:00
New Revision: f7bc9db95aba77157f10b627a4dea32c3174e148

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

LOG: Fix Wdocumentation missing parameter warnings. NFCI.

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
index 17a8e7859a54..047b2072bbcd 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -317,8 +317,7 @@ class StoreHandler {
 
   /// Handle the given store and produce the node.
   ///
-  /// \param E The expression value which we are tracking
-  /// \param N A node where the evaluation of \c E actually happens.
+  /// \param SI The information fully describing the store.
   /// \param Opts Tracking options specifying how we are tracking the value.
   ///
   /// \return the produced note, null if the handler doesn't support this kind
@@ -346,8 +345,7 @@ class TrackingBugReporterVisitor : public 
BugReporterVisitor {
 /// \param N A node "downstream" from the evaluation of the statement.
 /// \param E The expression value which we are tracking
 /// \param R The bug report to which visitors should be attached.
-/// \param EnableNullFPSuppression Whether we should employ false positive
-/// suppression (inlined defensive checks, returned null).
+/// \param Opts Tracking options specifying how we are tracking the value.
 ///
 /// \return Whether or not the function was able to add visitors for this
 /// statement. Note that returning \c true does not actually imply



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


[PATCH] D103888: [ADT] Remove APInt/APSInt toString() std::string variants

2021-06-11 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

In D103888#2811305 , @dblaikie wrote:

> Sounds OK.
>
> I wouldn't mind the places that can use op<< to use that - not sure 
> preserving the explicit radix argument is super high value. (I think people 
> would generally assume that's the default)
> Possible we could call it `to_string`, is std::to_string meant to be an ADL 
> extension point, so that other types expose a to_string in their own 
> associated namespace, etc?

We already have a llvm::to_string(V) wrapper inside ScopedPrinter.h that uses a 
temp llvm::raw_string_ostream to create the string - do you think that'd be 
good enough?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103888

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added inline comments.



Comment at: llvm/lib/Passes/PassBuilder.cpp:1449
-  // inserting redundancies into the program. This even includes SimplifyCFG.
-  OptimizePM.addPass(SpeculateAroundPHIsPass());
-

lebedev.ri wrote:
> nikic wrote:
> > As it has been in-tree for a while, I think it would be good to add a 
> > cl::opt option for people who have come to rely on it being present in some 
> > way.
> I'm not convinced that the pass can be returned into it's current position in 
> pipeline,
> that is why the diff is what it is now.
> 
Yes, there is a contradiction between the code comment and the position in the 
pipeline. I did question that here: 
https://bugs.llvm.org/show_bug.cgi?id=48821#c2



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added a comment.

Kind of the same take on this as @thopre .

I wrote https://bugs.llvm.org/show_bug.cgi?id=48821 , and proposed 
https://reviews.llvm.org/D95789 , when I noticed that this pass caused troubles 
for two reasons:

1. to avoid that others would stumble upon the same problem (getting unexpected 
regressions due to switching pass manager)
2. not that important really, but getting rid of downstream diffs is always 
nice (at least when the problem is likely to cause problems for other targets 
as well)

For the downstream target I've hacked around this a long time ago.

I do think it was a bit sneaky to get this pass by default in the pipeline as 
part of the PM switch. It might have caused lots of trouble for the new-PM 
switch in the past, and still for some downstream contributors.
So in that sense I'm all in favor. Although, a LGTM from me is a bit weak as 
I'm already using a workaround to skip this pass downstream.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D103021: [clang-tidy] performance-unnecessary-copy-initialization: Search whole function body for variable initializations.

2021-06-11 Thread Felix Berger via Phabricator via cfe-commits
flx marked an inline comment as done.
flx added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp:98-101
   auto Matches =
   match(findAll(declStmt(has(varDecl(equalsNode(
 .bind("declStmt")),
+Body, Context);

ymandel wrote:
> flx wrote:
> > ymandel wrote:
> > > Consider inspecting the `DeclContext`s instead, which should be much more 
> > > efficient than searching the entire block.  Pass the `FunctionDecl` as an 
> > > argument instead of `Body`, since it is a `DeclContext`.  e.g. `const 
> > > DeclContext `
> > > 
> > > Then, either
> > > 1. Call `Fun.containsDecl(InitializingVar)`, or
> > > 2. Search through the contexts yourself; something like:
> > > ```
> > > DeclContext* DC = InitializingVar->getDeclContext(); 
> > > while (DC != nullptr && DC != )
> > >   DC = DC->getLexicalParent();
> > > if (DC == nullptr)
> > >   // The reference or pointer is not initialized anywhere witin the 
> > > function. We
> > >   // assume its pointee is not modified then.
> > >   return true;
> > > ```
> > Are #1 and #2 equivalent? From the implementation and comment I cannot tell 
> > whether #1 would cover cases where the variable is not declared directly in 
> > the function, but in child block:
> > 
> > ```
> > void Fun() {
> >  {
> >var i;
> >{
> >  i.usedHere();
> >}  
> >  } 
> > }
> > ```
> > 
> > I'm also reading this as an optimization to more quickly determine whether 
> > we can stop here. We still need to find the matches for the next steps, but 
> > I  think I could then limit matching to the DeclContext I found here. Is 
> > this correct? For this I would actually need the DeclContext result from #2.
> A. I think you're right that #2 is more suited to what you need. I wasn't 
> sure, so included both. Agreed that the comments are ambiguous.
> B. yes, this is just an optimization. it may be premature for that matter; 
> just that match can be expensive and this seemed a more direct expression of 
> the algorithm.
I was not able to pass the (possibly more narrow) DeclContext to the match 
function as scope since match does not support DeclContexts.

I implemented  isDeclaredInFunction() which iterates through the decl contexts 
as you suggested. I'm not sure though whether we should start with 
VarDecl::getDeclContext() or VarDecl::getLexicalDeclContext()?

While looking at VarDecl::getLexicalDeclContext() I discovered is VarDecl has 
the following method:

```
  /// Returns true for local variable declarations other than parameters.   
 
  /// Note that this includes static variables inside of functions. It also 
 
  /// includes variables inside blocks. 
 
  ///   
 
  ///   void foo() { int x; static int y; extern int z; }   
 
  bool isLocalVarDecl() const;
```

I think this is exactly what we'd want here. What do you think?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103021

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


[PATCH] D104099: [NewPM] Remove SpeculateAroundPHIs pass from pipeline

2021-06-11 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre added a comment.

+1 for this change but being a downstream target only I prefer to let someone 
else approve this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104099

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


[PATCH] D103021: [clang-tidy] performance-unnecessary-copy-initialization: Search whole function body for variable initializations.

2021-06-11 Thread Felix Berger via Phabricator via cfe-commits
flx updated this revision to Diff 351425.
flx marked an inline comment as not done.
flx added a comment.

Use more efficient method to check for local variable declaration.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103021

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -1,9 +1,19 @@
 // RUN: %check_clang_tidy %s performance-unnecessary-copy-initialization %t
 
+template 
+struct Iterator {
+  void operator++();
+  const T *() const;
+  bool operator!=(const Iterator &) const;
+  typedef const T _reference;
+};
+
 struct ExpensiveToCopyType {
   ExpensiveToCopyType();
   virtual ~ExpensiveToCopyType();
   const ExpensiveToCopyType () const;
+  Iterator begin() const;
+  Iterator end() const;
   void nonConstMethod();
   bool constMethod() const;
 };
@@ -508,3 +518,41 @@
   // CHECK-FIXES: const auto& UnnecessaryCopy = Ref.reference();
   Orig.constMethod();
 }
+
+void negativeloopedOverObjectIsModified() {
+  ExpensiveToCopyType Orig;
+  for (const auto  : Orig) {
+const auto Copy = Element;
+Orig.nonConstMethod();
+Copy.constMethod();
+  }
+
+  auto Lambda = []() {
+ExpensiveToCopyType Orig;
+for (const auto  : Orig) {
+  const auto Copy = Element;
+  Orig.nonConstMethod();
+  Copy.constMethod();
+}
+  };
+}
+
+void negativeReferenceIsInitializedOutsideOfBlock() {
+  ExpensiveToCopyType Orig;
+  const auto  = Orig;
+  if (1 != 2 * 3) {
+const auto C2 = E2;
+Orig.nonConstMethod();
+C2.constMethod();
+  }
+
+  auto Lambda = []() {
+ExpensiveToCopyType Orig;
+const auto  = Orig;
+if (1 != 2 * 3) {
+  const auto C2 = E2;
+  Orig.nonConstMethod();
+  C2.constMethod();
+}
+  };
+}
Index: clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_UNNECESSARY_COPY_INITIALIZATION_H
 
 #include "../ClangTidyCheck.h"
+#include "clang/AST/Decl.h"
 
 namespace clang {
 namespace tidy {
@@ -35,11 +36,12 @@
 
 private:
   void handleCopyFromMethodReturn(const VarDecl , const Stmt ,
-  bool IssueFix, const VarDecl *ObjectArg,
+  const FunctionDecl , bool IssueFix,
+  const VarDecl *ObjectArg,
   ASTContext );
   void handleCopyFromLocalVar(const VarDecl , const VarDecl ,
-  const Stmt , bool IssueFix,
-  ASTContext );
+  const Stmt , const FunctionDecl ,
+  bool IssueFix, ASTContext );
   const std::vector AllowedTypes;
 };
 
Index: clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
@@ -12,6 +12,7 @@
 #include "../utils/FixItHintUtils.h"
 #include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
+#include "clang/AST/Decl.h"
 #include "clang/Basic/Diagnostic.h"
 
 namespace clang {
@@ -68,6 +69,16 @@
 hasOperatorName("&"), hasUnaryOperand(OldVarDeclRef;
 }
 
+bool isDeclaredInFunction(const VarDecl , const DeclContext ) {
+  const DeclContext *DC = Var.getDeclContext();
+  while (DC != nullptr) {
+if (DC == )
+  return true;
+DC = DC->getLexicalParent();
+  }
+  return false;
+}
+
 // This checks that the variable itself is only used as const, and also makes
 // sure that it does not reference another variable that could be modified in
 // the BlockStmt. It does this by checking the following:
@@ -82,6 +93,7 @@
 // object arg or variable that is referenced is immutable as well.
 static bool isInitializingVariableImmutable(const VarDecl ,
 const Stmt ,
+const FunctionDecl ,
 ASTContext ) {
   if (!isOnlyUsedAsConst(InitializingVar, BlockStmt, 

[PATCH] D104097: [analyzer] Fix calculating offset for fields with an empty type

2021-06-11 Thread Georgy Komarov via Phabricator via cfe-commits
jubnzv updated this revision to Diff 351423.

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

https://reviews.llvm.org/D104097

Files:
  clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
  clang/test/Analysis/padding_no_unique_address.cpp


Index: clang/test/Analysis/padding_no_unique_address.cpp
===
--- /dev/null
+++ clang/test/Analysis/padding_no_unique_address.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-linux-gnu 
-analyzer-checker=optin.performance -analyzer-config 
optin.performance.Padding:AllowedPad=2 -verify %s
+
+class Empty {}; // no-warning
+
+// expected-warning@+1{{Excessive padding in 'struct NoUniqueAddressWarn' (6 
padding}}
+struct NoUniqueAddressWarn {
+  char c1;
+  [[no_unique_address]] Empty empty;
+  int i;
+  char c2;
+};
+
+struct NoUniqueAddressNoWarn { // no-warning
+  char c1;
+  [[no_unique_address]] Empty empty;
+  char c2;
+};
+
Index: clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
@@ -193,6 +193,11 @@
 CharUnits PaddingSum;
 CharUnits Offset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
 for (const FieldDecl *FD : RD->fields()) {
+  // Skip field that is a subobject of zero size, marked with
+  // [[no_unique_address]] or an empty bitfield, because its address can be
+  // set the same as the other fields addresses.
+  if (FD->isZeroSize(ASTContext))
+continue;
   // This checker only cares about the padded size of the
   // field, and not the data size. If the field is a record
   // with tail padding, then we won't put that number in our
@@ -249,7 +254,7 @@
   RetVal.Field = FD;
   auto  = FD->getASTContext();
   auto Info = Ctx.getTypeInfoInChars(FD->getType());
-  RetVal.Size = Info.Width;
+  RetVal.Size = FD->isZeroSize(Ctx) ? CharUnits::Zero() : Info.Width;
   RetVal.Align = Info.Align;
   assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
   if (auto Max = FD->getMaxAlignment())


Index: clang/test/Analysis/padding_no_unique_address.cpp
===
--- /dev/null
+++ clang/test/Analysis/padding_no_unique_address.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-linux-gnu -analyzer-checker=optin.performance -analyzer-config optin.performance.Padding:AllowedPad=2 -verify %s
+
+class Empty {}; // no-warning
+
+// expected-warning@+1{{Excessive padding in 'struct NoUniqueAddressWarn' (6 padding}}
+struct NoUniqueAddressWarn {
+  char c1;
+  [[no_unique_address]] Empty empty;
+  int i;
+  char c2;
+};
+
+struct NoUniqueAddressNoWarn { // no-warning
+  char c1;
+  [[no_unique_address]] Empty empty;
+  char c2;
+};
+
Index: clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
@@ -193,6 +193,11 @@
 CharUnits PaddingSum;
 CharUnits Offset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
 for (const FieldDecl *FD : RD->fields()) {
+  // Skip field that is a subobject of zero size, marked with
+  // [[no_unique_address]] or an empty bitfield, because its address can be
+  // set the same as the other fields addresses.
+  if (FD->isZeroSize(ASTContext))
+continue;
   // This checker only cares about the padded size of the
   // field, and not the data size. If the field is a record
   // with tail padding, then we won't put that number in our
@@ -249,7 +254,7 @@
   RetVal.Field = FD;
   auto  = FD->getASTContext();
   auto Info = Ctx.getTypeInfoInChars(FD->getType());
-  RetVal.Size = Info.Width;
+  RetVal.Size = FD->isZeroSize(Ctx) ? CharUnits::Zero() : Info.Width;
   RetVal.Align = Info.Align;
   assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
   if (auto Max = FD->getMaxAlignment())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D104071: [AST] Include the TranslationUnitDecl when traversing with TraversalScope

2021-06-11 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.
Closed by commit rG6aca6032c5b6: [AST] Include the TranslationUnitDecl when 
traversing with TraversalScope (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D104071?vs=351365=351415#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104071

Files:
  clang-tools-extra/clangd/DumpAST.cpp
  clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/unittests/AST/ASTContextParentMapTest.cpp
  clang/unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp

Index: clang/unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp
===
--- clang/unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp
@@ -16,6 +16,12 @@
 public:
   Visitor(ASTContext *Context) { this->Context = Context; }
 
+  bool VisitTranslationUnitDecl(TranslationUnitDecl *D) {
+auto  = D->getParentASTContext().getSourceManager();
+Match("TU", SM.getLocForStartOfFile(SM.getMainFileID()));
+return true;
+  }
+
   bool VisitNamedDecl(NamedDecl *D) {
 if (!D->isImplicit())
   Match(D->getName(), D->getLocation());
@@ -41,6 +47,7 @@
   Ctx.setTraversalScope({});
 
   Visitor V();
+  V.ExpectMatch("TU", 1, 1);
   V.DisallowMatch("foo", 2, 8);
   V.ExpectMatch("bar", 3, 10);
   V.ExpectMatch("baz", 4, 12);
Index: clang/unittests/AST/ASTContextParentMapTest.cpp
===
--- clang/unittests/AST/ASTContextParentMapTest.cpp
+++ clang/unittests/AST/ASTContextParentMapTest.cpp
@@ -81,27 +81,31 @@
 }
 
 TEST(GetParents, RespectsTraversalScope) {
-  auto AST =
-  tooling::buildASTFromCode("struct foo { int bar; };", "foo.cpp",
-std::make_shared());
+  auto AST = tooling::buildASTFromCode(
+  "struct foo { int bar; }; struct baz{};", "foo.cpp",
+  std::make_shared());
   auto  = AST->getASTContext();
   auto  = *Ctx.getTranslationUnitDecl();
   auto  = *TU.lookup(("foo")).front();
   auto  = *cast(Foo).lookup(("bar")).front();
+  auto  = *TU.lookup(("baz")).front();
 
   // Initially, scope is the whole TU.
   EXPECT_THAT(Ctx.getParents(Bar), ElementsAre(DynTypedNode::create(Foo)));
   EXPECT_THAT(Ctx.getParents(Foo), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(Baz), ElementsAre(DynTypedNode::create(TU)));
 
   // Restrict the scope, now some parents are gone.
   Ctx.setTraversalScope({});
   EXPECT_THAT(Ctx.getParents(Bar), ElementsAre(DynTypedNode::create(Foo)));
-  EXPECT_THAT(Ctx.getParents(Foo), ElementsAre());
+  EXPECT_THAT(Ctx.getParents(Foo), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(Baz), ElementsAre());
 
   // Reset the scope, we get back the original results.
   Ctx.setTraversalScope({});
   EXPECT_THAT(Ctx.getParents(Bar), ElementsAre(DynTypedNode::create(Foo)));
   EXPECT_THAT(Ctx.getParents(Foo), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(Baz), ElementsAre(DynTypedNode::create(TU)));
 }
 
 TEST(GetParents, ImplicitLambdaNodes) {
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -192,14 +192,12 @@
   /// Return whether this visitor should traverse post-order.
   bool shouldTraversePostOrder() const { return false; }
 
-  /// Recursively visits an entire AST, starting from the top-level Decls
-  /// in the AST traversal scope (by default, the TranslationUnitDecl).
+  /// Recursively visits an entire AST, starting from the TranslationUnitDecl.
   /// \returns false if visitation was terminated early.
   bool TraverseAST(ASTContext ) {
-for (Decl *D : AST.getTraversalScope())
-  if (!getDerived().TraverseDecl(D))
-return false;
-return true;
+// Currently just an alias for TraverseDecl(TUDecl), but kept in case
+// we change the implementation again.
+return getDerived().TraverseDecl(AST.getTranslationUnitDecl());
   }
 
   /// Recursively visit a statement or expression, by
@@ -1495,12 +1493,24 @@
   TRY_TO(TraverseStmt(D->getMessage()));
 })
 
-DEF_TRAVERSE_DECL(
-TranslationUnitDecl,
-{// Code in an unnamed namespace shows up automatically in
- // decls_begin()/decls_end().  Thus we don't need to recurse on
- // D->getAnonymousNamespace().
-})
+DEF_TRAVERSE_DECL(TranslationUnitDecl, {
+  // Code in an unnamed namespace shows up automatically in

[clang] 6aca603 - [AST] Include the TranslationUnitDecl when traversing with TraversalScope

2021-06-11 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-06-11T14:29:45+02:00
New Revision: 6aca6032c5b62b5d26999da5f55779a1b08ec6a2

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

LOG: [AST] Include the TranslationUnitDecl when traversing with TraversalScope

Given `int foo, bar;`, TraverseAST reveals this tree:
  TranslationUnitDecl
   - foo
   - bar

Before this patch, with the TraversalScope set to {foo}, TraverseAST yields:
  foo

After this patch it yields:
  TranslationUnitDecl
  - foo

Also, TraverseDecl(TranslationUnitDecl) now respects the traversal scope.

---

The main effect of this today is that clang-tidy checks that match the
translationUnitDecl(), either in order to traverse it or check
parentage, should work.

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

Added: 


Modified: 
clang-tools-extra/clangd/DumpAST.cpp
clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang-tools-extra/clangd/unittests/TestTU.cpp
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/unittests/AST/ASTContextParentMapTest.cpp
clang/unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/DumpAST.cpp 
b/clang-tools-extra/clangd/DumpAST.cpp
index 30b90d2e0b548..36d61aca70fa6 100644
--- a/clang-tools-extra/clangd/DumpAST.cpp
+++ b/clang-tools-extra/clangd/DumpAST.cpp
@@ -337,12 +337,8 @@ class DumpVisitor : public 
RecursiveASTVisitor {
   // Generally, these are nodes with position information (TypeLoc, not Type).
 
   bool TraverseDecl(Decl *D) {
-return !D || isInjectedClassName(D) || traverseNode("declaration", D, [&] {
-  if (isa(D))
-Base::TraverseAST(const_cast(Ctx));
-  else
-Base::TraverseDecl(D);
-});
+return !D || isInjectedClassName(D) ||
+   traverseNode("declaration", D, [&] { Base::TraverseDecl(D); });
   }
   bool TraverseTypeLoc(TypeLoc TL) {
 return !TL || traverseNode("type", TL, [&] { Base::TraverseTypeLoc(TL); });

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
index d6a57efeeef13..a8c937a951dfc 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/AddUsing.cpp
@@ -82,7 +82,8 @@ class UsingFinder : public RecursiveASTVisitor {
 // There is no need to go deeper into nodes that do not enclose selection,
 // since "using" there will not affect selection, nor would it make a good
 // insertion point.
-if (Node->getDeclContext()->Encloses(SelectionDeclContext)) {
+if (!Node->getDeclContext() ||
+Node->getDeclContext()->Encloses(SelectionDeclContext)) {
   return RecursiveASTVisitor::TraverseDecl(Node);
 }
 return true;

diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index 4aa9cb7d66105..87f3c8737d464 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -248,13 +248,23 @@ TEST(DiagnosticsTest, ClangTidy) {
   return SQUARE($macroarg[[++]]y);
   return $doubled[[sizeof]](sizeof(int));
 }
+
+// misc-no-recursion uses a custom traversal from the TUDecl
+void foo();
+void $bar[[bar]]() {
+  foo();
+}
+void $foo[[foo]]() {
+  bar();
+}
   )cpp");
   auto TU = TestTU::withCode(Test.code());
   TU.HeaderFilename = "assert.h"; // Suppress "not found" error.
   TU.ClangTidyProvider = addTidyChecks("bugprone-sizeof-expression,"
"bugprone-macro-repeated-side-effects,"
"modernize-deprecated-headers,"
-   "modernize-use-trailing-return-type");
+   "modernize-use-trailing-return-type,"
+   "misc-no-recursion");
   EXPECT_THAT(
   *TU.build().getDiagnostics(),
   UnorderedElementsAre(
@@ -283,8 +293,12 @@ TEST(DiagnosticsTest, ClangTidy) {
   DiagSource(Diag::ClangTidy),
   DiagName("modernize-use-trailing-return-type"),
   // Verify that we don't have "[check-name]" suffix in the 
message.
-  WithFix(FixMessage(
-  "use a trailing return type for this function");
+  WithFix(
+  FixMessage("use a trailing return type for this function"))),
+  Diag(Test.range("foo"),
+   "function 'foo' is within a recursive call chain"),
+  Diag(Test.range("bar"),
+   "function 'bar' is 

[PATCH] D104071: [AST] Include the TranslationUnitDecl when traversing with TraversalScope

2021-06-11 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D104071#2812870 , @hokein wrote:

> Per https://reviews.llvm.org/harbormaster/unit/view/779496/, window test 
> seems to be failing...

Oops, there was a test I forgot to update (failed on all platforms). Fixed.

> Thanks! I think we should probably document this RAV behavior change in the 
> release note.

Happy to do this if you like, but I wouldn't be inclined - there are no in-tree 
uses of setTraversalScope apart from clangd, and in google's internal codebase 
(quite a lot of clang API usage) I only found one caller and no changes were 
needed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104071

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


[PATCH] D103888: [ADT] Remove APInt/APSInt toString() std::string variants

2021-06-11 Thread Simon Pilgrim 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 rG61cdaf66fe22: [ADT] Remove APInt/APSInt toString() 
std::string variants (authored by RKSimon).

Changed prior to commit:
  https://reviews.llvm.org/D103888?vs=350893=351414#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103888

Files:
  clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clangd/DumpAST.cpp
  clang-tools-extra/clangd/Hover.cpp
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/TemplateBase.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Analysis/ThreadSafetyCommon.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/unittests/StaticAnalyzer/RangeSetTest.cpp
  clang/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
  clang/unittests/Tooling/RecursiveASTVisitorTests/CallbacksCommon.h
  llvm/include/llvm/ADT/APInt.h
  llvm/include/llvm/ADT/APSInt.h
  llvm/include/llvm/ADT/StringExtras.h
  llvm/lib/CodeGen/GlobalISel/GISelKnownBits.cpp
  llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
  llvm/lib/Support/APInt.cpp
  llvm/lib/Target/X86/X86MCInstLower.cpp
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp
  llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp
  llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp
  llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp
  llvm/unittests/ADT/APIntTest.cpp
  llvm/unittests/ADT/StringExtrasTest.cpp

Index: llvm/unittests/ADT/StringExtrasTest.cpp
===
--- llvm/unittests/ADT/StringExtrasTest.cpp
+++ llvm/unittests/ADT/StringExtrasTest.cpp
@@ -229,3 +229,48 @@
   S = LS2;
   EXPECT_EQ(S, " ");
 }
+
+TEST(StringExtrasTest, toStringAPInt) {
+  bool isSigned;
+
+  EXPECT_EQ(toString(APInt(8, 0), 2, true, true), "0b0");
+  EXPECT_EQ(toString(APInt(8, 0), 8, true, true), "00");
+  EXPECT_EQ(toString(APInt(8, 0), 10, true, true), "0");
+  EXPECT_EQ(toString(APInt(8, 0), 16, true, true), "0x0");
+  EXPECT_EQ(toString(APInt(8, 0), 36, true, false), "0");
+
+  isSigned = false;
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 2, isSigned, true), "0b");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 8, isSigned, true), "0377");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 10, isSigned, true), "255");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 16, isSigned, true), "0xFF");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 36, isSigned, false), "73");
+
+  isSigned = true;
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 2, isSigned, true), "-0b1");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 8, isSigned, true), "-01");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 10, isSigned, true), "-1");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 16, isSigned, true), "-0x1");
+  EXPECT_EQ(toString(APInt(8, 255, isSigned), 36, isSigned, false), "-1");
+}
+
+TEST(StringExtrasTest, toStringAPSInt) {
+  bool isUnsigned;
+
+  EXPECT_EQ(toString(APSInt(APInt(8, 0), false), 2), "0");
+  EXPECT_EQ(toString(APSInt(APInt(8, 0), false), 8), "0");
+  EXPECT_EQ(toString(APSInt(APInt(8, 0), false), 10), "0");
+  EXPECT_EQ(toString(APSInt(APInt(8, 0), false), 16), "0");
+
+  isUnsigned = true;
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 2), "");
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 8), "377");
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 10), "255");
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 16), "FF");
+
+  isUnsigned = false;
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 2), "-1");
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 8), "-1");
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 10), "-1");
+  EXPECT_EQ(toString(APSInt(APInt(8, 255), isUnsigned), 16), "-1");
+}
\ No newline at end of file
Index: llvm/unittests/ADT/APIntTest.cpp
===
--- 

[clang-tools-extra] 61cdaf6 - [ADT] Remove APInt/APSInt toString() std::string variants

2021-06-11 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2021-06-11T13:19:15+01:00
New Revision: 61cdaf66fe22be2b5942ddee4f46a998b4f3ee29

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

LOG: [ADT] Remove APInt/APSInt toString() std::string variants

 is currently the highest impact header in a clang+llvm build:

https://commondatastorage.googleapis.com/chromium-browser-clang/llvm-include-analysis.html

One of the most common places this is being included is the APInt.h header, 
which needs it for an old toString() implementation that returns std::string - 
an inefficient method compared to the SmallString versions that it actually 
wraps.

This patch replaces these APInt/APSInt methods with a pair of llvm::toString() 
helpers inside StringExtras.h, adjusts users accordingly and removes the 
 from APInt.h - I was hoping that more of these users could be 
converted to use the SmallString methods, but it appears that most end up 
creating a std::string anyhow. I avoided trying to use the raw_ostream << 
operators as well as I didn't want to lose having the integer radix explicit in 
the code.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
clang-tools-extra/clangd/DumpAST.cpp
clang-tools-extra/clangd/Hover.cpp
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/AST/ASTDiagnostic.cpp
clang/lib/AST/ASTStructuralEquivalence.cpp
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/StmtPrinter.cpp
clang/lib/AST/TemplateBase.cpp
clang/lib/AST/TextNodeDumper.cpp
clang/lib/Analysis/ThreadSafetyCommon.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Frontend/InitPreprocessor.cpp
clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
clang/lib/Lex/PPExpressions.cpp
clang/lib/Sema/SemaCast.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaInit.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaStmtAsm.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaType.cpp
clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
clang/unittests/StaticAnalyzer/RangeSetTest.cpp
clang/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
clang/unittests/Tooling/RecursiveASTVisitorTests/CallbacksCommon.h
llvm/include/llvm/ADT/APInt.h
llvm/include/llvm/ADT/APSInt.h
llvm/include/llvm/ADT/StringExtras.h
llvm/lib/CodeGen/GlobalISel/GISelKnownBits.cpp
llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
llvm/lib/Support/APInt.cpp
llvm/lib/Target/X86/X86MCInstLower.cpp
llvm/lib/Transforms/IPO/OpenMPOpt.cpp
llvm/tools/llvm-exegesis/lib/BenchmarkResult.cpp
llvm/tools/llvm-pdbutil/MinimalSymbolDumper.cpp
llvm/tools/llvm-pdbutil/MinimalTypeDumper.cpp
llvm/unittests/ADT/APIntTest.cpp
llvm/unittests/ADT/StringExtrasTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp 
b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
index 125812f4f3a81..84c7a9fa92471 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp
@@ -208,7 +208,7 @@ stripFloatLiteralFraction(const MatchFinder::MatchResult 
,
   if (const auto *LitFloat = llvm::dyn_cast())
 // Attempt to simplify a `Duration` factory call with a literal argument.
 if (llvm::Optional IntValue = truncateIfIntegral(*LitFloat))
-  return IntValue->toString(/*radix=*/10);
+  return toString(*IntValue, /*radix=*/10);
 
   return llvm::None;
 }

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
index 1826e955f6a93..450b56135a78b 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -99,7 +99,7 @@ void ProBoundsConstantArrayIndexCheck::check(
 
   if (Index->isSigned() && Index->isNegative()) {
 diag(Matched->getExprLoc(), "std::array<> index %0 is negative")
-<< Index->toString(10);
+<< toString(*Index, 10);
 return;
   }
 
@@ -118,7 +118,7 @@ void ProBoundsConstantArrayIndexCheck::check(
 diag(Matched->getExprLoc(),
  

  1   2   >