[Differential] D83970: [ASTImporter] Refactor ASTImporter to support custom downstream tests

2020-07-21 Thread Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG20157410862d: [ASTImporter] Refactor ASTImporter to support 
custom downstream tests (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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


  https://reviews.llvm.org/D83970

Files:
  clang/unittests/AST/ASTImporterFixtures.h
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -18,7 +18,6 @@
 #include "gtest/gtest.h"
 
 #include "ASTImporterFixtures.h"
-#include "MatchVerifier.h"
 
 namespace clang {
 namespace ast_matchers {
@@ -27,230 +26,6 @@
 using internal::BindableMatcher;
 using llvm::StringMap;
 
-// Base class for those tests which use the family of `testImport` functions.
-class TestImportBase
-: public CompilerOptionSpecificTest,
-  public ::testing::WithParamInterface> {
-
-  template 
-  llvm::Expected importNode(ASTUnit *From, ASTUnit *To,
-  ASTImporter &Importer, NodeType Node) {
-ASTContext &ToCtx = To->getASTContext();
-
-// Add 'From' file to virtual file system so importer can 'find' it
-// while importing SourceLocations. It is safe to add same file multiple
-// times - it just isn't replaced.
-StringRef FromFileName = From->getMainFileName();
-createVirtualFileIfNeeded(To, FromFileName,
-  From->getBufferForFile(FromFileName));
-
-auto Imported = Importer.Import(Node);
-
-if (Imported) {
-  // This should dump source locations and assert if some source locations
-  // were not imported.
-  SmallString<1024> ImportChecker;
-  llvm::raw_svector_ostream ToNothing(ImportChecker);
-  ToCtx.getTranslationUnitDecl()->print(ToNothing);
-
-  // This traverses the AST to catch certain bugs like poorly or not
-  // implemented subtrees.
-  (*Imported)->dump(ToNothing);
-}
-
-return Imported;
-  }
-
-  template 
-  testing::AssertionResult
-  testImport(const std::string &FromCode,
- const std::vector &FromArgs,
- const std::string &ToCode, const std::vector &ToArgs,
- MatchVerifier &Verifier,
- const BindableMatcher &SearchMatcher,
- const BindableMatcher &VerificationMatcher) {
-const char *const InputFileName = "input.cc";
-const char *const OutputFileName = "output.cc";
-
-std::unique_ptr FromAST = tooling::buildASTFromCodeWithArgs(
- FromCode, FromArgs, InputFileName),
- ToAST = tooling::buildASTFromCodeWithArgs(
- ToCode, ToArgs, OutputFileName);
-
-ASTContext &FromCtx = FromAST->getASTContext(),
-   &ToCtx = ToAST->getASTContext();
-
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromAST->getFileManager(), false);
-
-auto FoundNodes = match(SearchMatcher, FromCtx);
-if (FoundNodes.size() != 1)
-  return testing::AssertionFailure()
- << "Multiple potential nodes were found!";
-
-auto ToImport = selectFirst(DeclToImportID, FoundNodes);
-if (!ToImport)
-  return testing::AssertionFailure() << "Node type mismatch!";
-
-// Sanity check: the node being imported should match in the same way as
-// the result node.
-BindableMatcher WrapperMatcher(VerificationMatcher);
-EXPECT_TRUE(Verifier.match(ToImport, WrapperMatcher));
-
-auto Imported = importNode(FromAST.get(), ToAST.get(), Importer, ToImport);
-if (!Imported) {
-  std::string ErrorText;
-  handleAllErrors(
-  Imported.takeError(),
-  [&ErrorText](const ImportError &Err) { ErrorText = Err.message(); });
-  return testing::AssertionFailure()
- << "Import failed, error: \"" << ErrorText << "\"!";
-}
-
-return Verifier.match(*Imported, WrapperMatcher);
-  }
-
-  template 
-  testing::AssertionResult
-  testImport(const std::string &FromCode,
- const std::vector &FromArgs,
- const std::string &ToCode, const std::vector &ToArgs,
- MatchVerifier &Verifier,
- const BindableMatcher &VerificationMatcher) {
-return testImport(
-FromCode, FromArgs, ToCode, ToArgs, Verifier,
-translationUnitDecl(
-has(namedDecl(hasName(DeclToImportID)).bind(DeclToImportID))),
-VerificationMatcher);
-  }
-
-protected:
-  std::vector getExtraArgs() const override { return GetParam(); }
-
-public:
-
-  /// Test how AST node named "declToImport" located in the transla

[PATCH] D83992: [ASTImporter] Add Visitor for TypedefNameDecl's

2020-07-28 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf761acfb1a73: [ASTImporter] Add Visitor for 
TypedefNameDecl's (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83992

Files:
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/test/Analysis/Inputs/ctu-import.c
  clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
  clang/test/Analysis/ctu-implicit.c


Index: clang/test/Analysis/ctu-implicit.c
===
--- /dev/null
+++ clang/test/Analysis/ctu-implicit.c
@@ -0,0 +1,20 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: mkdir -p %t/ctudir2
+// RUN: %clang_cc1  \
+// RUN:   -emit-pch -o %t/ctudir2/ctu-import.c.ast %S/Inputs/ctu-import.c
+// RUN: cp %S/Inputs/ctu-import.c.externalDefMap.ast-dump.txt 
%t/ctudir2/externalDefMap.txt
+// RUN: %clang_cc1 -analyze \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config  display-ctu-progress=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir2 \
+// RUN:   -verify %s
+
+void clang_analyzer_eval(int);
+
+int testStaticImplicit(void);
+int func(void) {
+  int ret = testStaticImplicit();
+  clang_analyzer_eval(ret == 4); // expected-warning{{TRUE}}
+  return testStaticImplicit();
+}
Index: clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
@@ -0,0 +1 @@
+c:@F@testStaticImplicit ctu-import.c.ast
Index: clang/test/Analysis/Inputs/ctu-import.c
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-import.c
@@ -0,0 +1,15 @@
+
+// Use an internal, implicitly defined type, called by
+// a function imported for CTU. This should not crash.
+int foo(void);
+int foobar(int skip) {
+  __NSConstantString str = {.flags = 1};
+
+  if (str.flags >= 0)
+str.flags = 0;
+  return 4;
+}
+
+int testStaticImplicit(void) {
+  return foobar(3);
+}
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -22,6 +22,20 @@
 struct Builder : RecursiveASTVisitor {
   ASTImporterLookupTable <
   Builder(ASTImporterLookupTable <) : LT(LT) {}
+
+  bool VisitTypedefNameDecl(TypedefNameDecl *D) {
+QualType Ty = D->getUnderlyingType();
+Ty = Ty.getCanonicalType();
+if (const auto *RTy = dyn_cast(Ty)) {
+  LT.add(RTy->getAsRecordDecl());
+  // iterate over the field decls, adding them
+  for (auto *it : RTy->getAsRecordDecl()->fields()) {
+LT.add(it);
+  }
+}
+return true;
+  }
+
   bool VisitNamedDecl(NamedDecl *D) {
 LT.add(D);
 return true;


Index: clang/test/Analysis/ctu-implicit.c
===
--- /dev/null
+++ clang/test/Analysis/ctu-implicit.c
@@ -0,0 +1,20 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: mkdir -p %t/ctudir2
+// RUN: %clang_cc1  \
+// RUN:   -emit-pch -o %t/ctudir2/ctu-import.c.ast %S/Inputs/ctu-import.c
+// RUN: cp %S/Inputs/ctu-import.c.externalDefMap.ast-dump.txt %t/ctudir2/externalDefMap.txt
+// RUN: %clang_cc1 -analyze \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config  display-ctu-progress=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir2 \
+// RUN:   -verify %s
+
+void clang_analyzer_eval(int);
+
+int testStaticImplicit(void);
+int func(void) {
+  int ret = testStaticImplicit();
+  clang_analyzer_eval(ret == 4); // expected-warning{{TRUE}}
+  return testStaticImplicit();
+}
Index: clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-import.c.externalDefMap.ast-dump.txt
@@ -0,0 +1 @@
+c:@F@testStaticImplicit ctu-import.c.ast
Index: clang/test/Analysis/Inputs/ctu-import.c
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-import.c
@@ -0,0 +1,15 @@
+
+// Use an internal, implicitly defined type, called by
+// a function imported for CTU. This should not crash.
+int foo(void);
+int foobar(int skip) {
+  __NSConstantString str = {.flags = 1};
+
+  if (str.flags >= 0)
+str.flags = 0;
+  return 4;
+}
+
+int testStaticImplicit(void) {
+  return foobar(3);
+}
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++

[PATCH] D85157: [Sema] Add casting check for fixed to fixed point conversions

2020-08-07 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG351aac098543: [Sema] Add casting check for fixed to fixed 
point conversions (authored by vabridgers, committed by einvbri 
).

Changed prior to commit:
  https://reviews.llvm.org/D85157?vs=283858&id=283887#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85157

Files:
  clang/lib/Sema/SemaCast.cpp
  clang/test/Sema/warn-bad-function-cast.c


Index: clang/test/Sema/warn-bad-function-cast.c
===
--- clang/test/Sema/warn-bad-function-cast.c
+++ clang/test/Sema/warn-bad-function-cast.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wbad-function-cast 
-triple x86_64-unknown-unknown -verify
+// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wbad-function-cast 
-ffixed-point -triple x86_64-unknown-unknown -verify
 // rdar://9103192
 
 void vf(void);
@@ -12,15 +12,20 @@
 _Bool bf(void);
 char *pf1(void);
 int *pf2(void);
+_Fract ff1(void);
 
 void
 foo(void)
 {
+
+  /* default, no cast, should always be ok */
+  ff1();
   /* Casts to void types are always OK.  */
   (void)vf();
   (void)if1();
   (void)cf();
   (const void)bf();
+  (void)ff1();
   /* Casts to the same type or similar types are OK.  */
   (int)if1();
   (long)if2();
@@ -32,6 +37,7 @@
   (_Bool)bf();
   (void *)pf1();
   (char *)pf2();
+  (_Fract) ff1();
   /* All following casts issue warning */
   (float)if1(); /* expected-warning {{cast from function call of type 'int' to 
non-matching type 'float'}} */
   (double)if2(); /* expected-warning {{cast from function call of type 'char' 
to non-matching type 'double'}} */
@@ -43,5 +49,7 @@
   (int)bf(); /* expected-warning {{cast from function call of type '_Bool' to 
non-matching type 'int'}} */
   (__SIZE_TYPE__)pf1(); /* expected-warning {{cast from function call of type 
'char *' to non-matching type 'unsigned long'}} */
   (__PTRDIFF_TYPE__)pf2(); /* expected-warning {{cast from function call of 
type 'int *' to non-matching type 'long'}} */
+  (_Fract) if1();  /* expected-warning{{cast from function call of 
type 'int' to non-matching type '_Fract'}} */
+  (int)ff1();  /* expected-warning{{cast from function call of 
type '_Fract' to non-matching type 'int'}} */
 }
 
Index: clang/lib/Sema/SemaCast.cpp
===
--- clang/lib/Sema/SemaCast.cpp
+++ clang/lib/Sema/SemaCast.cpp
@@ -2657,6 +2657,8 @@
 return;
   if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
 return;
+  if (SrcType->isFixedPointType() && DestType->isFixedPointType())
+return;
 
   Self.Diag(SrcExpr.get()->getExprLoc(),
 diag::warn_bad_function_cast)


Index: clang/test/Sema/warn-bad-function-cast.c
===
--- clang/test/Sema/warn-bad-function-cast.c
+++ clang/test/Sema/warn-bad-function-cast.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wbad-function-cast -triple x86_64-unknown-unknown -verify
+// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wbad-function-cast -ffixed-point -triple x86_64-unknown-unknown -verify
 // rdar://9103192
 
 void vf(void);
@@ -12,15 +12,20 @@
 _Bool bf(void);
 char *pf1(void);
 int *pf2(void);
+_Fract ff1(void);
 
 void
 foo(void)
 {
+
+  /* default, no cast, should always be ok */
+  ff1();
   /* Casts to void types are always OK.  */
   (void)vf();
   (void)if1();
   (void)cf();
   (const void)bf();
+  (void)ff1();
   /* Casts to the same type or similar types are OK.  */
   (int)if1();
   (long)if2();
@@ -32,6 +37,7 @@
   (_Bool)bf();
   (void *)pf1();
   (char *)pf2();
+  (_Fract) ff1();
   /* All following casts issue warning */
   (float)if1(); /* expected-warning {{cast from function call of type 'int' to non-matching type 'float'}} */
   (double)if2(); /* expected-warning {{cast from function call of type 'char' to non-matching type 'double'}} */
@@ -43,5 +49,7 @@
   (int)bf(); /* expected-warning {{cast from function call of type '_Bool' to non-matching type 'int'}} */
   (__SIZE_TYPE__)pf1(); /* expected-warning {{cast from function call of type 'char *' to non-matching type 'unsigned long'}} */
   (__PTRDIFF_TYPE__)pf2(); /* expected-warning {{cast from function call of type 'int *' to non-matching type 'long'}} */
+  (_Fract) if1();  /* expected-warning{{cast from function call of type 'int' to non-matching type '_Fract'}} */
+  (int)ff1();  /* expected-warning{{cast from function call of type '_Fract' to non-matching type 'int'}} */
 }
 
Index: clang/lib/Sema/SemaCast.cpp
===
--- clang/lib/Sema/SemaCast.cpp
+++ clang/lib/Sema/SemaCast.cpp
@@ -2657,6 +2657,8 @@
 return;
   if (SrcType->isCom

[PATCH] D85016: [clang-format] Add space between method modifier and a tuple return type in C#

2020-08-10 Thread 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 rG5f104a809983: [clang-format] Add space between method 
modifier and a tuple return type in C# (authored by lbk, committed by Jonathan 
Coe ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85016

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestCSharp.cpp


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -777,6 +777,20 @@
   verifyFormat(R"(private float[ , ] Values;)", Style);
   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
   verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style);
+
+  // Method returning tuple
+  verifyFormat(R"(public (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(private (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(protected (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(virtual (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(extern (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(static (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(internal (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(abstract (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(sealed (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(override (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(async (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(unsafe (string name, int age) methodTuple() {})", Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNullableTypes) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3115,6 +3115,16 @@
Keywords.kw_lock))
 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements 
||
spaceRequiredBeforeParens(Right);
+
+// space between method modifier and opening parenthesis of a tuple return
+// type
+if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
+ tok::kw_virtual, tok::kw_extern, tok::kw_static,
+ Keywords.kw_internal, Keywords.kw_abstract,
+ Keywords.kw_sealed, Keywords.kw_override,
+ Keywords.kw_async, Keywords.kw_unsafe) &&
+Right.is(tok::l_paren))
+  return true;
   } else if (Style.Language == FormatStyle::LK_JavaScript) {
 if (Left.is(TT_JsFatArrow))
   return true;


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -777,6 +777,20 @@
   verifyFormat(R"(private float[ , ] Values;)", Style);
   verifyFormat(R"(string dirPath = args?[ 0 ];)", Style);
   verifyFormat(R"(char[ ,, ] rawCharArray = MakeCharacterGrid();)", Style);
+
+  // Method returning tuple
+  verifyFormat(R"(public (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(private (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(protected (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(virtual (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(extern (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(static (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(internal (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(abstract (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(sealed (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(override (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(async (string name, int age) methodTuple() {})", Style);
+  verifyFormat(R"(unsafe (string name, int age) methodTuple() {})", Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpNullableTypes) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3115,6 +3115,16 @@
Keywords.kw_lock))
 return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements ||
spaceRequiredBeforeParens(Right);
+
+// space between method modifier and opening parenthesis of a tuple return
+// type
+if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
+ 

Re: [PATCH] D24307: calculate extent size for memory regions allocated by C++ new expression

2016-09-19 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL281934: [analyzer] Calculate extent size for memory regions 
allocated by new expression. (authored by xazax).

Changed prior to commit:
  https://reviews.llvm.org/D24307?vs=70821&id=71874#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24307

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  cfe/trunk/test/Analysis/out-of-bounds-new.cpp

Index: cfe/trunk/test/Analysis/out-of-bounds-new.cpp
===
--- cfe/trunk/test/Analysis/out-of-bounds-new.cpp
+++ cfe/trunk/test/Analysis/out-of-bounds-new.cpp
@@ -0,0 +1,150 @@
+// RUN: %clang_cc1 -std=c++11 -Wno-array-bounds -analyze -analyzer-checker=unix,core,alpha.security.ArrayBoundV2 -verify %s
+
+// Tests doing an out-of-bounds access after the end of an array using:
+// - constant integer index
+// - constant integer size for buffer
+void test1(int x) {
+  int *buf = new int[100];
+  buf[100] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+void test1_ok(int x) {
+  int *buf = new int[100];
+  buf[99] = 1; // no-warning
+}
+
+// Tests doing an out-of-bounds access after the end of an array using:
+// - indirect pointer to buffer
+// - constant integer index
+// - constant integer size for buffer
+void test1_ptr(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p[101] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+void test1_ptr_ok(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p[99] = 1; // no-warning
+}
+
+// Tests doing an out-of-bounds access before the start of an array using:
+// - indirect pointer to buffer, manipulated using simple pointer arithmetic
+// - constant integer index
+// - constant integer size for buffer
+void test1_ptr_arith(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p = p + 100;
+  p[0] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+void test1_ptr_arith_ok(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p = p + 99;
+  p[0] = 1; // no-warning
+}
+
+void test1_ptr_arith_bad(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p = p + 99;
+  p[1] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+void test1_ptr_arith_ok2(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p = p + 99;
+  p[-1] = 1; // no-warning
+}
+
+// Tests doing an out-of-bounds access before the start of an array using:
+// - constant integer index
+// - constant integer size for buffer
+void test2(int x) {
+  int *buf = new int[100];
+  buf[-1] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests doing an out-of-bounds access before the start of an array using:
+// - indirect pointer to buffer
+// - constant integer index
+// - constant integer size for buffer
+void test2_ptr(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  p[-1] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests doing an out-of-bounds access before the start of an array using:
+// - indirect pointer to buffer, manipulated using simple pointer arithmetic
+// - constant integer index
+// - constant integer size for buffer
+void test2_ptr_arith(int x) {
+  int *buf = new int[100];
+  int *p = buf;
+  --p;
+  p[0] = 1; // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+}
+
+// Tests under-indexing
+// of a multi-dimensional array
+void test2_multi(int x) {
+  auto buf = new int[100][100];
+  buf[0][-1] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests under-indexing
+// of a multi-dimensional array
+void test2_multi_b(int x) {
+  auto buf = new int[100][100];
+  buf[-1][0] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests over-indexing
+// of a multi-dimensional array
+void test2_multi_c(int x) {
+  auto buf = new int[100][100];
+  buf[100][0] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests over-indexing
+// of a multi-dimensional array
+void test2_multi_2(int x) {
+  auto buf = new int[100][100];
+  buf[99][100] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests normal access of
+// a multi-dimensional array
+void test2_multi_ok(int x) {
+  auto buf = new int[100][100];
+  buf[0][0] = 1; // no-warning
+}
+
+// Tests over-indexing using different types
+// array
+void test_diff_types(int x) {
+  int *buf = new int[10]; //10*sizeof(int) Bytes allocated
+  char *cptr = (char *)buf;
+  cptr[sizeof(int) * 9] = 1;  // no-warning
+  cptr[sizeof(int) * 10] = 1; // expected-warning{{Out of bound memory access}}
+}
+
+// Tests over-indexing
+//if the allocated area is non-array
+void test_non_array(int x) {
+  int *ip = new int;
+  ip[0] = 1; // no-warning
+  ip[1] = 2; // expected-warning{{Out of bound memory access}}
+}
+
+//Tests over-indexing
+//if the allocated area size is a runtime parameter
+void test_dynamic_size

Re: [PATCH] D21506: [analyzer] Block in critical section

2016-09-20 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282011: [analyzer] Add a checker that detects blocks in 
critical sections (authored by zaks).

Changed prior to commit:
  https://reviews.llvm.org/D21506?vs=71375&id=71977#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D21506

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
  cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
  cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  cfe/trunk/test/Analysis/block-in-critical-section.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -436,6 +436,10 @@
   HelpText<"Check for misuses of stream APIs">,
   DescFile<"SimpleStreamChecker.cpp">;
 
+def BlockInCriticalSectionChecker : Checker<"BlockInCriticalSection">,
+  HelpText<"Check for calls to blocking functions inside a critical section">,
+  DescFile<"BlockInCriticalSectionChecker.cpp">;
+
 } // end "alpha.unix"
 
 let ParentPackage = CString in {
Index: cfe/trunk/test/Analysis/block-in-critical-section.cpp
===
--- cfe/trunk/test/Analysis/block-in-critical-section.cpp
+++ cfe/trunk/test/Analysis/block-in-critical-section.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.unix.BlockInCriticalSection -std=c++11 -verify %s
+
+void sleep(int x) {}
+
+namespace std {
+struct mutex {
+  void lock() {}
+  void unlock() {}
+};
+}
+
+void testBlockInCriticalSection() {
+  std::mutex m;
+  m.lock();
+  sleep(3); // expected-warning {{A blocking function %s is called inside a critical section}}
+  m.unlock();
+}
+
+void testBlockInCriticalSectionWithNestedMutexes() {
+  std::mutex m, n, k;
+  m.lock();
+  n.lock();
+  k.lock();
+  sleep(3); // expected-warning {{A blocking function %s is called inside a critical section}}
+  k.unlock();
+  sleep(5); // expected-warning {{A blocking function %s is called inside a critical section}}
+  n.unlock();
+  sleep(3); // expected-warning {{A blocking function %s is called inside a critical section}}
+  m.unlock();
+  sleep(3); // no-warning
+}
+
+void f() {
+  sleep(1000); // expected-warning {{A blocking function %s is called inside a critical section}}
+}
+
+void testBlockInCriticalSectionInterProcedural() {
+  std::mutex m;
+  m.lock();
+  f();
+  m.unlock();
+}
+
+void testBlockInCriticalSectionUnexpectedUnlock() {
+  std::mutex m;
+  m.unlock();
+  sleep(1); // no-warning
+  m.lock();
+  sleep(1); // expected-warning {{A blocking function %s is called inside a critical section}}
+}
Index: cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -0,0 +1,109 @@
+//===-- BlockInCriticalSectionChecker.cpp ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// Defines a checker for blocks in critical sections. This checker should find
+// the calls to blocking functions (for example: sleep, getc, fgets, read,
+// recv etc.) inside a critical section. When sleep(x) is called while a mutex
+// is held, other threades cannot lock the same mutex. This might take some
+// time, leading to bad performance or even deadlock.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class BlockInCriticalSectionChecker : public Checker {
+
+  CallDescription LockFn, UnlockFn, SleepFn, GetcFn, FgetsFn, ReadFn, RecvFn;
+
+  std::unique_ptr BlockInCritSectionBugType;
+
+  void reportBlockInCritSection(SymbolRef FileDescSym,
+const CallEvent &call,
+CheckerContext &C) const;
+
+public:
+  BlockInCriticalSectionChecker();
+
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
+
+  /// Process unlock.
+  /// Process lock.
+  /// Process blocking functions (sleep, getc, fgets, read, recv)
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+
+};
+
+} // end anonymous namespace
+
+REGISTER_TRAIT_WITH_PROGRAMST

Re: [PATCH] D24881: [clang-tidy] Cleaning up language options.

2016-09-23 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282319: [clang-tidy] Cleaning up language options. (authored 
by xazax).

Changed prior to commit:
  https://reviews.llvm.org/D24881?vs=72341&id=72387#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24881

Files:
  clang-tools-extra/trunk/clang-tidy/cert/StrToNumCheck.cpp
  
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.cpp
  clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
  clang-tools-extra/trunk/clang-tidy/google/ExplicitConstructorCheck.cpp
  clang-tools-extra/trunk/clang-tidy/llvm/TwineLocalCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/AssertSideEffectCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/InaccurateEraseCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/InefficientAlgorithmCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/StringIntegerAssignmentCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/SuspiciousStringCompareCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/UnusedAliasDeclsCheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/UnusedRAIICheck.cpp
  clang-tools-extra/trunk/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/RawStringLiteralCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/RedundantVoidArgCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/ShrinkToFitCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/UseOverrideCheck.cpp
  clang-tools-extra/trunk/clang-tidy/mpi/TypeMismatchCheck.cpp
  clang-tools-extra/trunk/clang-tidy/readability/AvoidConstParamsInDecls.cpp
  clang-tools-extra/trunk/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  clang-tools-extra/trunk/clang-tidy/readability/NamespaceCommentCheck.cpp
  clang-tools-extra/trunk/clang-tidy/readability/RedundantControlFlowCheck.cpp
  clang-tools-extra/trunk/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
  clang-tools-extra/trunk/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  
clang-tools-extra/trunk/clang-tidy/readability/StaticDefinitionInAnonymousNamespaceCheck.cpp
  clang-tools-extra/trunk/clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp

Index: clang-tools-extra/trunk/clang-tidy/llvm/TwineLocalCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/llvm/TwineLocalCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/llvm/TwineLocalCheck.cpp
@@ -45,8 +45,7 @@
 if (VD->getType()->getCanonicalTypeUnqualified() ==
 C->getType()->getCanonicalTypeUnqualified()) {
   SourceLocation EndLoc = Lexer::getLocForEndOfToken(
-  VD->getInit()->getLocEnd(), 0, *Result.SourceManager,
-  Result.Context->getLangOpts());
+  VD->getInit()->getLocEnd(), 0, *Result.SourceManager, getLangOpts());
   Diag << FixItHint::CreateReplacement(TypeRange, "std::string")
<< FixItHint::CreateInsertion(VD->getInit()->getLocStart(), "(")
<< FixItHint::CreateInsertion(EndLoc, ").str()");
Index: clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.cpp
@@ -68,7 +68,7 @@
   CharSourceRange::getTokenRange(
   MatchedCast->getLParenLoc().getLocWithOffset(1),
   MatchedCast->getRParenLoc().getLocWithOffset(-1)),
-  *Result.SourceManager, Result.Context->getLangOpts());
+  *Result.SourceManager, getLangOpts());
 
   auto diag_builder = diag(
   MatchedCast->getLocStart(),
@@ -82,8 +82,7 @@
 CastText.push_back('(');
 diag_builder << FixItHint::CreateInsertion(
 Lexer::getLocForEndOfToken(SubExpr->getLocEnd(), 0,
-   *Result.SourceManager,
-   Result.Context->getLangOpts()),
+   *Result.SourceManager, getLangOpts()),
 ")");
   }
   auto ParenRange = CharSourceRange::getTokenRange(
Index: clang-tools-extra/trunk/clang-tidy/cert/StrToNumCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/cert/StrToNumCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/cert/StrToNumCheck.cpp
@@ -214,7 +214,7 @@
 
 // Formatted input functions need further checking of the format string to
 // determine whether a problematic conversion may be happening.
-Conversion = ClassifyFormatString(FmtStr, Result.Context->getLangOpts(),
+Conversion = ClassifyFormatString(FmtStr, getLangOpts(),
   Result.Context->getTarge

Re: [PATCH] D24820: Add -stats-stats option

2016-09-26 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282426: CC1: Add -save-stats option (authored by matze).

Changed prior to commit:
  https://reviews.llvm.org/D24820?vs=72376&id=72532#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24820

Files:
  cfe/trunk/docs/CommandGuide/clang.rst
  cfe/trunk/include/clang/Basic/DiagnosticFrontendKinds.td
  cfe/trunk/include/clang/Driver/CC1Options.td
  cfe/trunk/include/clang/Driver/Options.td
  cfe/trunk/include/clang/Frontend/FrontendOptions.h
  cfe/trunk/lib/Driver/Tools.cpp
  cfe/trunk/lib/Frontend/CompilerInstance.cpp
  cfe/trunk/lib/Frontend/CompilerInvocation.cpp
  cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  cfe/trunk/test/Driver/save-stats.c
  cfe/trunk/test/Frontend/stats-file.c
  cfe/trunk/test/Misc/warning-flags.c

Index: cfe/trunk/include/clang/Driver/Options.td
===
--- cfe/trunk/include/clang/Driver/Options.td
+++ cfe/trunk/include/clang/Driver/Options.td
@@ -1876,6 +1876,11 @@
 def save_temps : Flag<["-", "--"], "save-temps">, Flags<[DriverOption]>,
   Alias, AliasArgs<["cwd"]>,
   HelpText<"Save intermediate compilation results">;
+def save_stats_EQ : Joined<["-", "--"], "save-stats=">, Flags<[DriverOption]>,
+  HelpText<"Save llvm statistics.">;
+def save_stats : Flag<["-", "--"], "save-stats">, Flags<[DriverOption]>,
+  Alias, AliasArgs<["cwd"]>,
+  HelpText<"Save llvm statistics.">;
 def via_file_asm : Flag<["-", "--"], "via-file-asm">, InternalDebugOpt,
   HelpText<"Write assembly to file for input to assemble jobs">;
 def sectalign : MultiArg<["-"], "sectalign", 3>;
Index: cfe/trunk/include/clang/Driver/CC1Options.td
===
--- cfe/trunk/include/clang/Driver/CC1Options.td
+++ cfe/trunk/include/clang/Driver/CC1Options.td
@@ -509,6 +509,8 @@
 
 def print_stats : Flag<["-"], "print-stats">,
   HelpText<"Print performance metrics and statistics">;
+def stats_file : Joined<["-"], "stats-file=">,
+  HelpText<"Filename to write statistics to">;
 def fdump_record_layouts : Flag<["-"], "fdump-record-layouts">,
   HelpText<"Dump record layout information">;
 def fdump_record_layouts_simple : Flag<["-"], "fdump-record-layouts-simple">,
Index: cfe/trunk/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- cfe/trunk/include/clang/Basic/DiagnosticFrontendKinds.td
+++ cfe/trunk/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -107,6 +107,8 @@
 "unable to open CC_PRINT_HEADERS file: %0 (using stderr)">;
 def warn_fe_cc_log_diagnostics_failure : Warning<
 "unable to open CC_LOG_DIAGNOSTICS file: %0 (using stderr)">;
+def warn_fe_unable_to_open_stats_file : Warning<
+"unable to open statistics output file '%0': '%1'">;
 def err_fe_no_pch_in_dir : Error<
 "no suitable precompiled header file found in directory '%0'">;
 def err_fe_action_not_available : Error<
Index: cfe/trunk/include/clang/Frontend/FrontendOptions.h
===
--- cfe/trunk/include/clang/Frontend/FrontendOptions.h
+++ cfe/trunk/include/clang/Frontend/FrontendOptions.h
@@ -273,6 +273,9 @@
   // included by this file.
   std::string FindPchSource;
 
+  /// Filename to write statistics to.
+  std::string StatsFile;
+
 public:
   FrontendOptions() :
 DisableFree(false), RelocatablePCH(false), ShowHelp(false),
Index: cfe/trunk/test/Misc/warning-flags.c
===
--- cfe/trunk/test/Misc/warning-flags.c
+++ cfe/trunk/test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (84):
+CHECK: Warnings without flags (85):
 CHECK-NEXT:   ext_excess_initializers
 CHECK-NEXT:   ext_excess_initializers_in_char_array_initializer
 CHECK-NEXT:   ext_expected_semi_decl_list
@@ -66,6 +66,7 @@
 CHECK-NEXT:   warn_fe_cc_log_diagnostics_failure
 CHECK-NEXT:   warn_fe_cc_print_header_failure
 CHECK-NEXT:   warn_fe_macro_contains_embedded_newline
+CHECK-NEXT:   warn_fe_unable_to_open_stats_file
 CHECK-NEXT:   warn_file_asm_volatile
 CHECK-NEXT:   warn_ignoring_ftabstop_value
 CHECK-NEXT:   warn_implements_nscopying
Index: cfe/trunk/test/Driver/save-stats.c
===
--- cfe/trunk/test/Driver/save-stats.c
+++ cfe/trunk/test/Driver/save-stats.c
@@ -0,0 +1,20 @@
+// RUN: %clang -target x86_64-apple-darwin -save-stats %s -### 2>&1 | FileCheck %s
+// RUN: %clang -target x86_64-apple-darwin -save-stats=cwd %s -### 2>&1 | FileCheck %s
+// CHECK: "-stats-file=save-stats.stats"
+// CHECK: "{{.*}}save-stats.c"
+
+// RUN: %clang -target x86_64-apple-darwin -S %s -### 2>&1 | FileCheck %s -check-prefix=NO-STATS
+// NO-STATS-NO: -stats-file
+// NO-STATS: "{{.*}}save-stats.c"
+// NO-STATS-NO: -stat

Re: [PATCH] D24984: [libunwind] Add support for a single-threaded libunwind build

2016-09-28 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282575: [libunwind] Add support for a single-threaded 
libunwind build (authored by asiri).

Changed prior to commit:
  https://reviews.llvm.org/D24984?vs=72698&id=72798#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24984

Files:
  libunwind/trunk/CMakeLists.txt
  libunwind/trunk/src/CMakeLists.txt
  libunwind/trunk/src/UnwindCursor.hpp
  libunwind/trunk/src/Unwind_AppleExtras.cpp
  libunwind/trunk/src/config.h

Index: libunwind/trunk/CMakeLists.txt
===
--- libunwind/trunk/CMakeLists.txt
+++ libunwind/trunk/CMakeLists.txt
@@ -107,6 +107,7 @@
 option(LIBUNWIND_ENABLE_STATIC "Build libunwind as a static library." ON)
 option(LIBUNWIND_ENABLE_CROSS_UNWINDING "Enable cross-platform unwinding support." OFF)
 option(LIBUNWIND_ENABLE_ARM_WMMX "Enable unwinding support for ARM WMMX registers." OFF)
+option(LIBUNWIND_ENABLE_THREADS "Build libunwind with threading support." ON)
 
 set(LIBUNWIND_TARGET_TRIPLE "" CACHE STRING "Target triple for cross compiling.")
 set(LIBUNWIND_GCC_TOOLCHAIN "" CACHE PATH "GCC toolchain for cross compiling.")
@@ -242,6 +243,11 @@
   list(APPEND LIBUNWIND_COMPILE_FLAGS -D_LIBUNWIND_IS_NATIVE_ONLY)
 endif()
 
+# Threading-support
+if (NOT LIBUNWIND_ENABLE_THREADS)
+  list(APPEND LIBUNWIND_COMPILE_FLAGS -D_LIBUNWIND_HAS_NO_THREADS)
+endif()
+
 # ARM WMMX register support
 if (LIBUNWIND_ENABLE_ARM_WMMX)
   # __ARM_WMMX is a compiler pre-define (as per the ACLE 2.0). Clang does not
Index: libunwind/trunk/src/Unwind_AppleExtras.cpp
===
--- libunwind/trunk/src/Unwind_AppleExtras.cpp
+++ libunwind/trunk/src/Unwind_AppleExtras.cpp
@@ -185,21 +185,29 @@
 
 #if !defined(FOR_DYLD) && _LIBUNWIND_BUILD_SJLJ_APIS
 
-#include 
+#ifndef _LIBUNWIND_HAS_NO_THREADS
+  #include 
+#else
+  _Unwind_FunctionContext *fc_ = nullptr;
+#endif
 
 // Accessors to get get/set linked list of frames for sjlj based execeptions.
 _LIBUNWIND_HIDDEN
 struct _Unwind_FunctionContext *__Unwind_SjLj_GetTopOfFunctionStack() {
+#ifndef _LIBUNWIND_HAS_NO_THREADS
   return (struct _Unwind_FunctionContext *)
 _pthread_getspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key);
+#else
+  return fc_;
+#endif
 }
 
 _LIBUNWIND_HIDDEN
 void __Unwind_SjLj_SetTopOfFunctionStack(struct _Unwind_FunctionContext *fc) {
+#ifndef _LIBUNWIND_HAS_NO_THREADS
   _pthread_setspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key, fc);
+#else
+  fc_ = fc;
+#endif
 }
 #endif
-
-
-
-
Index: libunwind/trunk/src/config.h
===
--- libunwind/trunk/src/config.h
+++ libunwind/trunk/src/config.h
@@ -85,13 +85,20 @@
   } while (0)
 #define _LIBUNWIND_LOG(msg, ...) fprintf(stderr, "libunwind: " msg "\n", __VA_ARGS__)
 
+#if defined(_LIBUNWIND_HAS_NO_THREADS)
+  // only used with pthread calls, not needed for the single-threaded builds
+  #define _LIBUNWIND_LOG_NON_ZERO(x)
+#endif
+
 // Macros that define away in non-Debug builds
 #ifdef NDEBUG
   #define _LIBUNWIND_DEBUG_LOG(msg, ...)
   #define _LIBUNWIND_TRACE_API(msg, ...)
   #define _LIBUNWIND_TRACING_UNWINDING 0
   #define _LIBUNWIND_TRACE_UNWINDING(msg, ...)
-  #define _LIBUNWIND_LOG_NON_ZERO(x) x
+  #ifndef _LIBUNWIND_LOG_NON_ZERO
+#define _LIBUNWIND_LOG_NON_ZERO(x) x
+  #endif
 #else
   #ifdef __cplusplus
 extern "C" {
@@ -102,12 +109,14 @@
 }
   #endif
   #define _LIBUNWIND_DEBUG_LOG(msg, ...)  _LIBUNWIND_LOG(msg, __VA_ARGS__)
-  #define _LIBUNWIND_LOG_NON_ZERO(x) \
-do { \
-  int _err = x; \
-  if ( _err != 0 ) \
-_LIBUNWIND_LOG("" #x "=%d in %s", _err, __FUNCTION__); \
- } while (0)
+  #ifndef _LIBUNWIND_LOG_NON_ZERO
+#define _LIBUNWIND_LOG_NON_ZERO(x) \
+  do { \
+int _err = x; \
+if ( _err != 0 ) \
+  _LIBUNWIND_LOG("" #x "=%d in %s", _err, __FUNCTION__); \
+   } while (0)
+  #endif
   #define _LIBUNWIND_TRACE_API(msg, ...) \
 do { \
   if ( logAPIs() ) _LIBUNWIND_LOG(msg, __VA_ARGS__); \
Index: libunwind/trunk/src/UnwindCursor.hpp
===
--- libunwind/trunk/src/UnwindCursor.hpp
+++ libunwind/trunk/src/UnwindCursor.hpp
@@ -16,7 +16,9 @@
 #include 
 #include 
 #include 
-#include 
+#ifndef _LIBUNWIND_HAS_NO_THREADS
+  #include 
+#endif
 #include 
 
 #ifdef __APPLE__
@@ -60,7 +62,9 @@
 
   // These fields are all static to avoid needing an initializer.
   // There is only one instance of this class per process.
+#ifndef _LIBUNWIND_HAS_NO_THREADS
   static pthread_rwlock_t _lock;
+#endif
 #ifdef __APPLE__
   static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
   static bool _registeredForDyldUnloads;
@@ -87,8 +91,10 @@
 template 
 typename DwarfFDECache::entry DwarfFDE

[PATCH] D24278: [analyzer] Extend bug reports with extra notes.

2016-10-04 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL283092: [analyzer] Extend bug reports with extra notes 
(authored by dergachev).

Changed prior to commit:
  https://reviews.llvm.org/D24278?vs=72519&id=73406#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24278

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
  cfe/trunk/lib/Rewrite/HTMLRewrite.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
@@ -266,6 +266,9 @@
   /// \sa shouldWidenLoops
   Optional WidenLoops;
 
+  /// \sa shouldDisplayNotesAsEvents
+  Optional DisplayNotesAsEvents;
+
   /// A helper function that retrieves option for a given full-qualified
   /// checker name.
   /// Options for checkers can be specified via 'analyzer-config' command-line
@@ -534,6 +537,14 @@
   /// This is controlled by the 'widen-loops' config option.
   bool shouldWidenLoops();
 
+  /// Returns true if the bug reporter should transparently treat extra note
+  /// diagnostic pieces as event diagnostic pieces. Useful when the diagnostic
+  /// consumer doesn't support the extra note pieces.
+  ///
+  /// This is controlled by the 'notes-as-events' option, which defaults
+  /// to false when unset.
+  bool shouldDisplayNotesAsEvents();
+
 public:
   AnalyzerOptions() :
 AnalysisStoreOpt(RegionStoreModel),
Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
@@ -336,7 +336,7 @@
 
 class PathDiagnosticPiece : public RefCountedBaseVPTR {
 public:
-  enum Kind { ControlFlow, Event, Macro, Call };
+  enum Kind { ControlFlow, Event, Macro, Call, Note };
   enum DisplayHint { Above, Below };
 
 private:
@@ -452,7 +452,8 @@
   void Profile(llvm::FoldingSetNodeID &ID) const override;
 
   static bool classof(const PathDiagnosticPiece *P) {
-return P->getKind() == Event || P->getKind() == Macro;
+return P->getKind() == Event || P->getKind() == Macro ||
+   P->getKind() == Note;
   }
 };
 
@@ -710,6 +711,23 @@
   void Profile(llvm::FoldingSetNodeID &ID) const override;
 };
 
+class PathDiagnosticNotePiece: public PathDiagnosticSpotPiece {
+public:
+  PathDiagnosticNotePiece(const PathDiagnosticLocation &Pos, StringRef S,
+   bool AddPosRange = true)
+  : PathDiagnosticSpotPiece(Pos, S, Note, AddPosRange) {}
+
+  ~PathDiagnosticNotePiece() override;
+
+  static inline bool classof(const PathDiagnosticPiece *P) {
+return P->getKind() == Note;
+  }
+
+  void dump() const override;
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override;
+};
+
 /// PathDiagnostic - PathDiagnostic objects represent a single path-sensitive
 ///  diagnostic.  It represents an ordered-collection of PathDiagnosticPieces,
 ///  each which represent the pieces of the path.
Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -66,6 +66,8 @@
   typedef SmallVector, 8> VisitorList;
   typedef VisitorList::iterator visitor_iterator;
   typedef SmallVector ExtraTextList;
+  typedef SmallVector, 4>
+  NoteList;
 
 protected:
   friend class BugReporter;
@@ -82,7 +84,8 @@
   const ExplodedNode *ErrorNode;
   SmallVector Ranges;
   ExtraTextList ExtraText;
-  
+  NoteList Notes;
+
   typedef llvm::DenseSet Symbols;
   typedef llvm::DenseSet Regions;
 
@@ -177,6 +180,18 @@
   const BugType& getBugType() const { return BT; }
   BugType& getBugType() { return BT; }
 
+  /// \brief True when the report has an execution path associated with it.
+  ///
+  /// A report is said to be path-sensitive if it was thrown against a
+  /// particular exploded node in the path-sensitive analysis graph.
+  /// Path-sensitive reports have their intermediate path diagnostics
+  /// auto-generated, perhaps with the help of checker-defined visitors,
+  /// and may contain extra notes.
+  /// Path-insensitive reports consist

[PATCH] D24916: [analyzer] Extend bug reports with extra notes - CloneChecker

2016-10-04 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL283094: [analyzer] Improve CloneChecker diagnostics 
(authored by dergachev).

Changed prior to commit:
  https://reviews.llvm.org/D24916?vs=72991&id=73408#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24916

Files:
  cfe/trunk/include/clang/Analysis/CloneDetection.h
  cfe/trunk/lib/Analysis/CloneDetection.cpp
  cfe/trunk/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
  cfe/trunk/test/Analysis/copypaste/blocks.cpp
  cfe/trunk/test/Analysis/copypaste/function-try-block.cpp
  cfe/trunk/test/Analysis/copypaste/functions.cpp
  cfe/trunk/test/Analysis/copypaste/macro-complexity.cpp
  cfe/trunk/test/Analysis/copypaste/macros.cpp
  cfe/trunk/test/Analysis/copypaste/objc-methods.m
  cfe/trunk/test/Analysis/copypaste/plist-diagnostics-notes-as-events.cpp
  cfe/trunk/test/Analysis/copypaste/plist-diagnostics.cpp
  cfe/trunk/test/Analysis/copypaste/sub-sequences.cpp
  cfe/trunk/test/Analysis/copypaste/suspicious-clones.cpp
  cfe/trunk/test/Analysis/copypaste/text-diagnostics.cpp

Index: cfe/trunk/lib/Analysis/CloneDetection.cpp
===
--- cfe/trunk/lib/Analysis/CloneDetection.cpp
+++ cfe/trunk/lib/Analysis/CloneDetection.cpp
@@ -82,6 +82,10 @@
 
 SourceLocation StmtSequence::getEndLoc() const { return back()->getLocEnd(); }
 
+SourceRange StmtSequence::getSourceRange() const {
+  return SourceRange(getStartLoc(), getEndLoc());
+}
+
 namespace {
 
 /// \brief Analyzes the pattern of the referenced variables in a statement.
@@ -91,11 +95,11 @@
   struct VariableOccurence {
 /// The index of the associated VarDecl in the Variables vector.
 size_t KindID;
-/// The source range in the code where the variable was referenced.
-SourceRange Range;
+/// The statement in the code where the variable was referenced.
+const Stmt *Mention;
 
-VariableOccurence(size_t KindID, SourceRange Range)
-: KindID(KindID), Range(Range) {}
+VariableOccurence(size_t KindID, const Stmt *Mention)
+: KindID(KindID), Mention(Mention) {}
   };
 
   /// All occurences of referenced variables in the order of appearance.
@@ -107,19 +111,19 @@
   /// \brief Adds a new variable referenced to this pattern.
   /// \param VarDecl The declaration of the variable that is referenced.
   /// \param Range The SourceRange where this variable is referenced.
-  void addVariableOccurence(const VarDecl *VarDecl, SourceRange Range) {
+  void addVariableOccurence(const VarDecl *VarDecl, const Stmt *Mention) {
 // First check if we already reference this variable
 for (size_t KindIndex = 0; KindIndex < Variables.size(); ++KindIndex) {
   if (Variables[KindIndex] == VarDecl) {
 // If yes, add a new occurence that points to the existing entry in
 // the Variables vector.
-Occurences.emplace_back(KindIndex, Range);
+Occurences.emplace_back(KindIndex, Mention);
 return;
   }
 }
 // If this variable wasn't already referenced, add it to the list of
 // referenced variables and add a occurence that points to this new entry.
-Occurences.emplace_back(Variables.size(), Range);
+Occurences.emplace_back(Variables.size(), Mention);
 Variables.push_back(VarDecl);
   }
 
@@ -134,7 +138,7 @@
 // Check if S is a reference to a variable. If yes, add it to the pattern.
 if (auto D = dyn_cast(S)) {
   if (auto VD = dyn_cast(D->getDecl()->getCanonicalDecl()))
-addVariableOccurence(VD, D->getSourceRange());
+addVariableOccurence(VD, D);
 }
 
 // Recursively check all children of the given statement.
@@ -208,7 +212,7 @@
   // Store information about the first clone.
   FirstMismatch->FirstCloneInfo =
   CloneDetector::SuspiciousClonePair::SuspiciousCloneInfo(
-  Variables[ThisOccurence.KindID], ThisOccurence.Range,
+  Variables[ThisOccurence.KindID], ThisOccurence.Mention,
   FirstSuggestion);
 
   // Same as above but with the other clone. We do this for both clones as
@@ -221,7 +225,7 @@
   // Store information about the second clone.
   FirstMismatch->SecondCloneInfo =
   CloneDetector::SuspiciousClonePair::SuspiciousCloneInfo(
-  Variables[ThisOccurence.KindID], OtherOccurence.Range,
+  Other.Variables[OtherOccurence.KindID], OtherOccurence.Mention,
   SecondSuggestion);
 
   // SuspiciousClonePair guarantees that the first clone always has a
Index: cfe/trunk/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
@@ -16,8 +16,10 @@
 #include "ClangSACheckers.h"
 #include "clang/Analysis/CloneDetection.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/StaticAnalyzer/Core/BugReporter

[PATCH] D24915: [analyzer] Extend bug reports with extra notes - ObjCDeallocChecker

2016-10-04 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL283093: [analyzer] Add extra notes to ObjCDeallocChecker 
(authored by dergachev).

Changed prior to commit:
  https://reviews.llvm.org/D24915?vs=72520&id=73407#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24915

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
  cfe/trunk/test/Analysis/DeallocMissingRelease.m
  cfe/trunk/test/Analysis/PR2978.m
  cfe/trunk/test/Analysis/properties.m

Index: cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
@@ -107,6 +107,9 @@
   std::unique_ptr ExtraReleaseBugType;
   std::unique_ptr MistakenDeallocBugType;
 
+  static constexpr const char *MsgDeclared = "Property is declared here";
+  static constexpr const char *MsgSynthesized = "Property is synthesized here";
+
 public:
   ObjCDeallocChecker();
 
@@ -128,6 +131,9 @@
   void checkEndFunction(CheckerContext &Ctx) const;
 
 private:
+  void addNoteForDecl(std::unique_ptr &BR, StringRef Msg,
+   const Decl *D) const;
+
   void diagnoseMissingReleases(CheckerContext &C) const;
 
   bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
@@ -489,6 +495,18 @@
   return State;
 }
 
+/// Add an extra note piece describing a declaration that is important
+/// for understanding the bug report.
+void ObjCDeallocChecker::addNoteForDecl(std::unique_ptr &BR,
+ StringRef Msg,
+ const Decl *D) const {
+  ASTContext &ACtx = D->getASTContext();
+  SourceManager &SM = ACtx.getSourceManager();
+  PathDiagnosticLocation Pos = PathDiagnosticLocation::createBegin(D, SM);
+  if (Pos.isValid() && Pos.asLocation().isValid())
+BR->addNote(Msg, Pos, D->getSourceRange());
+}
+
 /// Report any unreleased instance variables for the current instance being
 /// dealloced.
 void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
@@ -586,6 +604,9 @@
 std::unique_ptr BR(
 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
 
+addNoteForDecl(BR, MsgDeclared, PropDecl);
+addNoteForDecl(BR, MsgSynthesized, PropImpl);
+
 C.emitReport(std::move(BR));
   }
 
@@ -689,11 +710,12 @@
  );
 
   const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
-  OS << "The '" << *PropImpl->getPropertyIvarDecl()
- << "' ivar in '" << *Container;
+  const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
+  OS << "The '" << *IvarDecl << "' ivar in '" << *Container;
 
+  bool ReleasedByCIFilterDealloc = isReleasedByCIFilterDealloc(PropImpl);
 
-  if (isReleasedByCIFilterDealloc(PropImpl)) {
+  if (ReleasedByCIFilterDealloc) {
 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
   } else {
 OS << "' was synthesized for ";
@@ -710,6 +732,10 @@
   new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
   BR->addRange(M.getOriginExpr()->getSourceRange());
 
+  addNoteForDecl(BR, MsgDeclared, PropDecl);
+  if (!ReleasedByCIFilterDealloc)
+addNoteForDecl(BR, MsgSynthesized, PropImpl);
+
   C.emitReport(std::move(BR));
 
   return true;
Index: cfe/trunk/test/Analysis/PR2978.m
===
--- cfe/trunk/test/Analysis/PR2978.m
+++ cfe/trunk/test/Analysis/PR2978.m
@@ -29,22 +29,22 @@
   id _nonPropertyIvar;
 }
 @property(retain) id X;
-@property(retain) id Y;
-@property(assign) id Z;
+@property(retain) id Y; // expected-note{{Property is declared here}}
+@property(assign) id Z; // expected-note{{Property is declared here}}
 @property(assign) id K;
 @property(weak) id L;
 @property(readonly) id N;
 @property(retain) id M;
 @property(weak) id P;
-@property(weak) id Q;
+@property(weak) id Q; // expected-note{{Property is declared here}}
 @property(retain) id R;
-@property(weak, readonly) id S;
+@property(weak, readonly) id S; // expected-note{{Property is declared here}}
 
 @property(assign, readonly) id T; // Shadowed in class extension
 @property(assign) id U;
 
 @property(retain) id V;
-@property(retain) id W;
+@property(retain) id W; // expected-note{{Property is declared here}}
 -(id) O;
 -(void) setO: (id) arg;
 @end
@@ -56,16 +56,16 @@
 
 @implementation MyClass
 @synthesize X = _X;
-@synthesize Y = _Y;
-@synthesize Z = _Z;
+@synthesize Y = _Y; // expected-note{{Property is synthesized here}}
+@synthesize Z = _Z; // expected-note{{Property is synthesized here}}
 @synthesize K = _K;
 @synthesize L = _L;
 @synthesize N = _N;
 @synthesize M = _M;
-@synthesize Q = _Q;
+@synthesize Q = _Q; // expected-note{{Property is synthesized here}}
 @synthesize R = _R;
 @synthesize V = _V;
-@synthesize W = _W;
+@synthesize W = _W; // expected-note{{Property is s

[PATCH] D22227: [ubsan] Disable bounds-check for flexible array ivars

2016-10-04 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL283249: [ubsan] Disable bounds-check for flexible array 
ivars (authored by vedantk).

Changed prior to commit:
  https://reviews.llvm.org/D7?vs=73508&id=73547#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D7

Files:
  cfe/trunk/lib/CodeGen/CGExpr.cpp
  cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m


Index: cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m
===
--- cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m
+++ cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m
@@ -0,0 +1,59 @@
+// RUN: %clang_cc1 -x objective-c -emit-llvm -triple 
x86_64-apple-macosx10.10.0 -Wno-objc-root-class -fsanitize=array-bounds %s -o - 
| FileCheck %s
+
+@interface FlexibleArray1 {
+@public
+  char chars[0];
+}
+@end
+@implementation FlexibleArray1
+@end
+
+// CHECK-LABEL: test_FlexibleArray1
+char test_FlexibleArray1(FlexibleArray1 *FA1) {
+  // CHECK-NOT: !nosanitize
+  return FA1->chars[1];
+  // CHECK: }
+}
+
+@interface FlexibleArray2 {
+@public
+  char chars[0];
+}
+@end
+@implementation FlexibleArray2 {
+@public
+  char chars2[0];
+}
+@end
+
+// CHECK-LABEL: test_FlexibleArray2_1
+char test_FlexibleArray2_1(FlexibleArray2 *FA2) {
+  // CHECK: !nosanitize
+  return FA2->chars[1];
+  // CHECK: }
+}
+
+// CHECK-LABEL: test_FlexibleArray2_2
+char test_FlexibleArray2_2(FlexibleArray2 *FA2) {
+  // CHECK-NOT: !nosanitize
+  return FA2->chars2[1];
+  // CHECK: }
+}
+
+@interface FlexibleArray3 {
+@public
+  char chars[0];
+}
+@end
+@implementation FlexibleArray3 {
+@public
+  int i;
+}
+@end
+
+// CHECK-LABEL: test_FlexibleArray3
+char test_FlexibleArray3(FlexibleArray3 *FA3) {
+  // CHECK: !nosanitize
+  return FA3->chars[1];
+  // CHECK: }
+}
Index: cfe/trunk/lib/CodeGen/CGExpr.cpp
===
--- cfe/trunk/lib/CodeGen/CGExpr.cpp
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp
@@ -708,6 +708,8 @@
   DeclContext::decl_iterator(const_cast(FD)));
   return ++FI == FD->getParent()->field_end();
 }
+  } else if (const auto *IRE = dyn_cast(E)) {
+return IRE->getDecl()->getNextIvar() == nullptr;
   }
 
   return false;


Index: cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m
===
--- cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m
+++ cfe/trunk/test/CodeGenObjC/ubsan-array-bounds.m
@@ -0,0 +1,59 @@
+// RUN: %clang_cc1 -x objective-c -emit-llvm -triple x86_64-apple-macosx10.10.0 -Wno-objc-root-class -fsanitize=array-bounds %s -o - | FileCheck %s
+
+@interface FlexibleArray1 {
+@public
+  char chars[0];
+}
+@end
+@implementation FlexibleArray1
+@end
+
+// CHECK-LABEL: test_FlexibleArray1
+char test_FlexibleArray1(FlexibleArray1 *FA1) {
+  // CHECK-NOT: !nosanitize
+  return FA1->chars[1];
+  // CHECK: }
+}
+
+@interface FlexibleArray2 {
+@public
+  char chars[0];
+}
+@end
+@implementation FlexibleArray2 {
+@public
+  char chars2[0];
+}
+@end
+
+// CHECK-LABEL: test_FlexibleArray2_1
+char test_FlexibleArray2_1(FlexibleArray2 *FA2) {
+  // CHECK: !nosanitize
+  return FA2->chars[1];
+  // CHECK: }
+}
+
+// CHECK-LABEL: test_FlexibleArray2_2
+char test_FlexibleArray2_2(FlexibleArray2 *FA2) {
+  // CHECK-NOT: !nosanitize
+  return FA2->chars2[1];
+  // CHECK: }
+}
+
+@interface FlexibleArray3 {
+@public
+  char chars[0];
+}
+@end
+@implementation FlexibleArray3 {
+@public
+  int i;
+}
+@end
+
+// CHECK-LABEL: test_FlexibleArray3
+char test_FlexibleArray3(FlexibleArray3 *FA3) {
+  // CHECK: !nosanitize
+  return FA3->chars[1];
+  // CHECK: }
+}
Index: cfe/trunk/lib/CodeGen/CGExpr.cpp
===
--- cfe/trunk/lib/CodeGen/CGExpr.cpp
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp
@@ -708,6 +708,8 @@
   DeclContext::decl_iterator(const_cast(FD)));
   return ++FI == FD->getParent()->field_end();
 }
+  } else if (const auto *IRE = dyn_cast(E)) {
+return IRE->getDecl()->getNextIvar() == nullptr;
   }
 
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D25092: [analyzer] Add "Assuming..." diagnostic pieces for short-circuit logical operators.

2016-10-05 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL283302: [analyzer] Improve "Assuming..." diagnostic pieces 
for logical operators. (authored by dergachev).

Changed prior to commit:
  https://reviews.llvm.org/D25092?vs=73472&id=73601#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25092

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  cfe/trunk/test/Analysis/conditional-path-notes.c
  cfe/trunk/test/Analysis/edges-new.mm

Index: cfe/trunk/test/Analysis/conditional-path-notes.c
===
--- cfe/trunk/test/Analysis/conditional-path-notes.c
+++ cfe/trunk/test/Analysis/conditional-path-notes.c
@@ -64,11 +64,12 @@
   }
 }
 
-void testNonDiagnosableBranchLogical(int a, int b) {
+void testDiagnosableBranchLogical(int a, int b) {
   if (a && b) {
-// expected-note@-1 {{Assuming the condition is true}}
+// expected-note@-1 {{Assuming 'a' is not equal to 0}}
 // expected-note@-2 {{Left side of '&&' is true}}
-// expected-note@-3 {{Taking true branch}}
+// expected-note@-3 {{Assuming 'b' is not equal to 0}}
+// expected-note@-4 {{Taking true branch}}
 *(volatile int *)0 = 1; // expected-warning{{Dereference of null pointer}}
 // expected-note@-1 {{Dereference of null pointer}}
   }
@@ -1343,6 +1344,35 @@
 // CHECK-NEXT:   
 // CHECK-NEXT: 
 // CHECK-NEXT: 
+// CHECK-NEXT:  kindevent
+// CHECK-NEXT:  location
+// CHECK-NEXT:  
+// CHECK-NEXT:   line68
+// CHECK-NEXT:   col7
+// CHECK-NEXT:   file0
+// CHECK-NEXT:  
+// CHECK-NEXT:  ranges
+// CHECK-NEXT:  
+// CHECK-NEXT:
+// CHECK-NEXT: 
+// CHECK-NEXT:  line68
+// CHECK-NEXT:  col7
+// CHECK-NEXT:  file0
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT:  line68
+// CHECK-NEXT:  col7
+// CHECK-NEXT:  file0
+// CHECK-NEXT: 
+// CHECK-NEXT:
+// CHECK-NEXT:  
+// CHECK-NEXT:  depth0
+// CHECK-NEXT:  extended_message
+// CHECK-NEXT:  Assuming 'a' is not equal to 0
+// CHECK-NEXT:  message
+// CHECK-NEXT:  Assuming 'a' is not equal to 0
+// CHECK-NEXT: 
+// CHECK-NEXT: 
 // CHECK-NEXT:  kindcontrol
 // CHECK-NEXT:  edges
 // CHECK-NEXT:   
@@ -1377,53 +1407,19 @@
 // CHECK-NEXT:   
 // CHECK-NEXT: 
 // CHECK-NEXT: 
-// CHECK-NEXT:  kindcontrol
-// CHECK-NEXT:  edges
-// CHECK-NEXT:   
-// CHECK-NEXT:
-// CHECK-NEXT: start
-// CHECK-NEXT:  
-// CHECK-NEXT:   
-// CHECK-NEXT:line68
-// CHECK-NEXT:col12
-// CHECK-NEXT:file0
-// CHECK-NEXT:   
-// CHECK-NEXT:   
-// CHECK-NEXT:line68
-// CHECK-NEXT:col12
-// CHECK-NEXT:file0
-// CHECK-NEXT:   
-// CHECK-NEXT:  
-// CHECK-NEXT: end
-// CHECK-NEXT:  
-// CHECK-NEXT:   
-// CHECK-NEXT:line68
-// CHECK-NEXT:col7
-// CHECK-NEXT:file0
-// CHECK-NEXT:   
-// CHECK-NEXT:   
-// CHECK-NEXT:line68
-// CHECK-NEXT:col7
-// CHECK-NEXT:file0
-// CHECK-NEXT:   
-// CHECK-NEXT:  
-// CHECK-NEXT:
-// CHECK-NEXT:   
-// CHECK-NEXT: 
-// CHECK-NEXT: 
 // CHECK-NEXT:  kindevent
 // CHECK-NEXT:  location
 // CHECK-NEXT:  
 // CHECK-NEXT:   line68
-// CHECK-NEXT:   col7
+// CHECK-NEXT:   col12
 // CHECK-NEXT:   file0
 // CHECK-NEXT:  
 // CHECK-NEXT:  ranges
 // CHECK-NEXT:  
 // CHECK-NEXT:
 // CHECK-NEXT: 
 // CHECK-NEXT:  line68
-// CHECK-NEXT:  col7
+// CHECK-NEXT:  col12
 // CHECK-NEXT:  file0
 // CHECK-NEXT: 
 // CHECK-NEXT: 
@@ -1435,9 +1431,9 @@
 // CHECK-NEXT:  
 // CHECK-NEXT:  depth0
 // CHECK-NEXT:  extended_message
-// CHECK-NEXT:  Assuming the condition is true
+// CHECK-NEXT:  Assuming 'b' is not equal to 0
 // CHECK-NEXT:  message
-// CHECK-NEXT:  Assuming the condition is true
+// CHECK-NEXT:  Assuming 'b' is not equal to 0
 // CHECK-NEXT: 
 // CHECK-NEXT: 
 // CHECK-NEXT:  kindcontrol
@@ -1448,24 +1444,24 @@
 // CHECK-NEXT:  
 // CHECK-NEXT:   
 // CHECK-NEXT:line68
-// CHECK-NEXT:col7
+// CHECK-NEXT:col12
 // CHECK-NEXT:file0
 // CHECK-NEXT:   
 // CHECK-NEXT:   
 // CHECK-NEXT:line68
-// CHECK-NEXT:col7
+// CHECK-NEXT:col12
 // CHECK-NEXT:file0
 // CHECK-NEXT:   
 // CHECK-NEXT:  
 // CHECK-NEXT: end
 // CHECK-NEXT:  
 // CHECK-NEXT:   
-// CHECK-NEXT:line72
+// CHECK-NEXT:line73
 // CHECK-NEXT:col5
 // CHECK-NEXT:file0
 // 

[PATCH] D21021: [Clang][AVX512][BuiltIn]Adding intrinsics move_{sd|ss} to clang

2016-10-05 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL283314: [Clang][AVX512][BuiltIn]Adding missing intrinsics 
move_{sd|ss} to clang (authored by mzuckerm).

Changed prior to commit:
  https://reviews.llvm.org/D21021?vs=59720&id=73638#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D21021

Files:
  cfe/trunk/include/clang/Basic/BuiltinsX86.def
  cfe/trunk/lib/Headers/avx512fintrin.h
  cfe/trunk/test/CodeGen/avx512f-builtins.c


Index: cfe/trunk/include/clang/Basic/BuiltinsX86.def
===
--- cfe/trunk/include/clang/Basic/BuiltinsX86.def
+++ cfe/trunk/include/clang/Basic/BuiltinsX86.def
@@ -2021,6 +2021,8 @@
 TARGET_BUILTIN(__builtin_ia32_expandsf512_mask, "V16fV16fV16fUs","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_expandsi512_mask, "V16iV16iV16iUs","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_cvtps2pd512_mask, "V8dV8fV8dUcIi","","avx512f")
+TARGET_BUILTIN(__builtin_ia32_movss_mask, "V4fV4fV4fV4fUc","","avx512f")
+TARGET_BUILTIN(__builtin_ia32_movsd_mask, "V2dV2dV2dV2dUc","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_compressstoredf512_mask, 
"vV8d*V8dUc","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_compressstoredi512_mask, 
"vV8LLi*V8LLiUc","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_compressstoresf512_mask, 
"vV16f*V16fUs","","avx512f")
Index: cfe/trunk/test/CodeGen/avx512f-builtins.c
===
--- cfe/trunk/test/CodeGen/avx512f-builtins.c
+++ cfe/trunk/test/CodeGen/avx512f-builtins.c
@@ -7863,6 +7863,34 @@
   return _mm512_setzero_pd();
 }
 
+__m128 test_mm_mask_move_ss (__m128 __W, __mmask8 __U, __m128 __A, __m128 __B)
+{
+  // CHECK-LABEL: @test_mm_mask_move_ss
+  // CHECK: @llvm.x86.avx512.mask.move.ss
+  return _mm_mask_move_ss ( __W,  __U,  __A,  __B);
+}
+
+__m128 test_mm_maskz_move_ss (__mmask8 __U, __m128 __A, __m128 __B)
+{
+  // CHECK-LABEL: @test_mm_maskz_move_ss
+  // CHECK: @llvm.x86.avx512.mask.move.ss
+  return _mm_maskz_move_ss (__U, __A, __B);
+}
+
+__m128d test_mm_mask_move_sd (__m128 __W, __mmask8 __U, __m128d __A, __m128d 
__B)
+{
+  // CHECK-LABEL: @test_mm_mask_move_sd
+  // CHECK: @llvm.x86.avx512.mask.move.sd
+  return _mm_mask_move_sd ( __W,  __U,  __A,  __B);
+}
+
+__m128d test_mm_maskz_move_sd (__mmask8 __U, __m128d __A, __m128d __B)
+{
+  // CHECK-LABEL: @test_mm_maskz_move_sd
+  // CHECK: @llvm.x86.avx512.mask.move.sd
+  return _mm_maskz_move_sd (__U, __A, __B);
+}
+
 __m512d test_mm512_abs_pd(__m512d a){
   // CHECK-LABEL: @test_mm512_abs_pd
   // CHECK: and <8 x i64> 
Index: cfe/trunk/lib/Headers/avx512fintrin.h
===
--- cfe/trunk/lib/Headers/avx512fintrin.h
+++ cfe/trunk/lib/Headers/avx512fintrin.h
@@ -9140,6 +9140,40 @@
  (__v16sf)_mm512_setzero_ps());
 }
 
+static __inline__ __m128 __DEFAULT_FN_ATTRS
+_mm_mask_move_ss (__m128 __W, __mmask8 __U, __m128 __A, __m128 __B)
+{
+  return (__m128) __builtin_ia32_movss_mask ((__v4sf) __A, (__v4sf) __B,
+   (__v4sf) __W,
+   (__mmask8) __U);
+}
+
+static __inline__ __m128 __DEFAULT_FN_ATTRS
+_mm_maskz_move_ss (__mmask8 __U, __m128 __A, __m128 __B)
+{
+  return (__m128) __builtin_ia32_movss_mask ((__v4sf) __A, (__v4sf) __B,
+   (__v4sf)
+   _mm_setzero_si128(),
+   (__mmask8) __U);
+}
+
+static __inline__ __m128d __DEFAULT_FN_ATTRS
+_mm_mask_move_sd (__m128d __W, __mmask8 __U, __m128d __A, __m128d __B)
+{
+  return (__m128d) __builtin_ia32_movsd_mask ((__v2df) __A, (__v2df) __B,
+   (__v2df) __W,
+   (__mmask8) __U);
+}
+
+static __inline__ __m128d __DEFAULT_FN_ATTRS
+_mm_maskz_move_sd (__mmask8 __U, __m128d __A, __m128d __B)
+{
+  return (__m128d) __builtin_ia32_movsd_mask ((__v2df) __A, (__v2df) __B,
+   (__v2df)
+   _mm_setzero_pd (),
+   (__mmask8) __U);
+}
+
 #define _mm512_shuffle_epi32(A, I) __extension__ ({ \
   (__m512i)__builtin_shufflevector((__v16si)(__m512i)(A), \
(__v16si)_mm512_undefined_epi32(), \


Index: cfe/trunk/include/clang/Basic/BuiltinsX86.def
===
--- cfe/trunk/include/clang/Basic/BuiltinsX86.def
+++ cfe/trunk/include/clang/Basic/BuiltinsX86.def
@@ -2021,6 +2021,8 @@
 TARGET_BUILTIN(__builtin_ia32_expandsf512_mask, "V16fV16fV16fUs","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_expandsi512_mask, "V16iV16iV16iUs","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_cvtps2pd512_mask, "V8dV8fV8dUcIi","","avx512f")
+TARGET_BUILTIN(__builtin_ia32_movss_mask, "V4fV4fV4fV4fUc","","avx512f")
+TARGET_BUILTIN(__builtin_ia32_movsd_mask, "V2dV2dV2dV2dUc","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_compressstoredf512_mask, "vV8d*V8dUc","","avx512f")
 TARGET_BUILTIN(__builtin_ia32_compressstoredi512_mask, "vV8LLi*V8LLiUc","","avx512f")
 TARGET_BUI

[PATCH] D25429: [analyzer] Link libStaticAnalyzerCheckers to libASTMatchers.

2016-10-13 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284112: [analyzer] Link libStaticAnalyzerCheckers to 
libASTMatchers. (authored by dergachev).

Changed prior to commit:
  https://reviews.llvm.org/D25429?vs=74109&id=74497#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25429

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt


Index: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -91,6 +91,7 @@
 
   LINK_LIBS
   clangAST
+  clangASTMatchers
   clangAnalysis
   clangBasic
   clangLex


Index: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -91,6 +91,7 @@
 
   LINK_LIBS
   clangAST
+  clangASTMatchers
   clangAnalysis
   clangBasic
   clangLex
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D24958: Test linked to D24957

2016-10-14 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284213: [x86][ms-inline-asm] use of "jmp short" in asm is 
not supported (authored by mzuckerm).

Changed prior to commit:
  https://reviews.llvm.org/D24958?vs=72624&id=74626#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24958

Files:
  cfe/trunk/test/CodeGen/ms-inline-asm.c


Index: cfe/trunk/test/CodeGen/ms-inline-asm.c
===
--- cfe/trunk/test/CodeGen/ms-inline-asm.c
+++ cfe/trunk/test/CodeGen/ms-inline-asm.c
@@ -634,6 +634,15 @@
   // CHECK: call void asm sideeffect inteldialect "jmp 
{{.*}}__MSASMLABEL_.5__dollar_label$$\0A\09{{.*}}__MSASMLABEL_.5__dollar_label$$:",
 "~{dirflag},~{fpsr},~{flags}"()
 }
 
+void label6(){
+  __asm {
+  jmp short label
+label:
+  }
+  // CHECK-LABEL: define void @label6
+  // CHECK: call void asm sideeffect inteldialect "jmp 
{{.*}}__MSASMLABEL_.6__label\0A\09{{.*}}__MSASMLABEL_.6__label:", 
"~{dirflag},~{fpsr},~{flags}"()
+}
+
 typedef union _LARGE_INTEGER {
   struct {
 unsigned int LowPart;


Index: cfe/trunk/test/CodeGen/ms-inline-asm.c
===
--- cfe/trunk/test/CodeGen/ms-inline-asm.c
+++ cfe/trunk/test/CodeGen/ms-inline-asm.c
@@ -634,6 +634,15 @@
   // CHECK: call void asm sideeffect inteldialect "jmp {{.*}}__MSASMLABEL_.5__dollar_label$$\0A\09{{.*}}__MSASMLABEL_.5__dollar_label$$:", "~{dirflag},~{fpsr},~{flags}"()
 }
 
+void label6(){
+  __asm {
+  jmp short label
+label:
+  }
+  // CHECK-LABEL: define void @label6
+  // CHECK: call void asm sideeffect inteldialect "jmp {{.*}}__MSASMLABEL_.6__label\0A\09{{.*}}__MSASMLABEL_.6__label:", "~{dirflag},~{fpsr},~{flags}"()
+}
+
 typedef union _LARGE_INTEGER {
   struct {
 unsigned int LowPart;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D25468: [libcxx] Do not declare the thread api when __external_threading is present

2016-10-14 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284232: [libcxx] Do not declare the thread api when 
__external_threading is present (authored by asiri).

Changed prior to commit:
  https://reviews.llvm.org/D25468?vs=74234&id=74668#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25468

Files:
  libcxx/trunk/include/__threading_support


Index: libcxx/trunk/include/__threading_support
===
--- libcxx/trunk/include/__threading_support
+++ libcxx/trunk/include/__threading_support
@@ -25,17 +25,16 @@
 #if defined(_LIBCPP_HAS_THREAD_API_EXTERNAL)
 #if !defined(__clang__) && (_GNUC_VER < 500)
 #include <__external_threading>
-#define _LIBCPP_EXTERNAL_THREADING
+#define _LIBCPP_HAS_EXTERNAL_THREADING_HEADER
 #elif !defined(__has_include) || __has_include(<__external_threading>)
 #include <__external_threading>
-#define _LIBCPP_EXTERNAL_THREADING
+#define _LIBCPP_HAS_EXTERNAL_THREADING_HEADER
 #endif
 #endif
 
-#if !defined(_LIBCPP_EXTERNAL_THREADING)
+#if !defined(_LIBCPP_HAS_EXTERNAL_THREADING_HEADER)
 #include 
 #include 
-#endif
 
 #if defined(_LIBCPP_HAS_THREAD_API_EXTERNAL)
 #define _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_FUNC_VIS
@@ -242,6 +241,8 @@
 
 _LIBCPP_END_NAMESPACE_STD
 
+#endif // !_LIBCPP_HAS_EXTERNAL_THREADING_HEADER
+
 #endif // _LIBCPP_HAS_NO_THREADS
 
 #endif // _LIBCPP_THREADING_SUPPORT


Index: libcxx/trunk/include/__threading_support
===
--- libcxx/trunk/include/__threading_support
+++ libcxx/trunk/include/__threading_support
@@ -25,17 +25,16 @@
 #if defined(_LIBCPP_HAS_THREAD_API_EXTERNAL)
 #if !defined(__clang__) && (_GNUC_VER < 500)
 #include <__external_threading>
-#define _LIBCPP_EXTERNAL_THREADING
+#define _LIBCPP_HAS_EXTERNAL_THREADING_HEADER
 #elif !defined(__has_include) || __has_include(<__external_threading>)
 #include <__external_threading>
-#define _LIBCPP_EXTERNAL_THREADING
+#define _LIBCPP_HAS_EXTERNAL_THREADING_HEADER
 #endif
 #endif
 
-#if !defined(_LIBCPP_EXTERNAL_THREADING)
+#if !defined(_LIBCPP_HAS_EXTERNAL_THREADING_HEADER)
 #include 
 #include 
-#endif
 
 #if defined(_LIBCPP_HAS_THREAD_API_EXTERNAL)
 #define _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_FUNC_VIS
@@ -242,6 +241,8 @@
 
 _LIBCPP_END_NAMESPACE_STD
 
+#endif // !_LIBCPP_HAS_EXTERNAL_THREADING_HEADER
+
 #endif // _LIBCPP_HAS_NO_THREADS
 
 #endif // _LIBCPP_THREADING_SUPPORT
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D25283: AvailabilityAttrs: Refactor context checking when diagnosing an availability violation

2016-10-14 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284265: [Sema] Refactor context checking for availability 
diagnostics (authored by epilk).

Changed prior to commit:
  https://reviews.llvm.org/D25283?vs=74547&id=74729#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25283

Files:
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/lib/Sema/SemaDeclAttr.cpp
  cfe/trunk/lib/Sema/SemaExpr.cpp
  cfe/trunk/test/SemaObjC/class-unavail-warning.m

Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -9889,23 +9889,16 @@
 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
   }
 
-  AvailabilityResult getCurContextAvailability() const;
-
-  /// \brief Get the verison that this context implies.
-  /// For instance, a method in an interface that is annotated with an
-  /// availability attribuite effectively has the availability of the interface.
-  VersionTuple getVersionForDecl(const Decl *Ctx) const;
-
   /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
   ///
   /// \param D The declaration to check. Note that this may be altered to point
   /// to another declaration that \c D gets it's availability from. i.e., we
   /// walk the list of typedefs to find an availability attribute.
   ///
-  /// \param ContextVersion The version to compare availability against.
-  AvailabilityResult
-  ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, VersionTuple ContextVersion,
-   std::string *Message);
+  /// \param Message If non-null, this will be populated with the message from
+  /// the availability attribute that is selected.
+  AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
+  std::string *Message);
 
   const DeclContext *getCurObjCLexicalContext() const {
 const DeclContext *DC = getCurLexicalContext();
Index: cfe/trunk/test/SemaObjC/class-unavail-warning.m
===
--- cfe/trunk/test/SemaObjC/class-unavail-warning.m
+++ cfe/trunk/test/SemaObjC/class-unavail-warning.m
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1  -fsyntax-only  -triple x86_64-apple-darwin10 -verify %s
+// RUN: %clang_cc1  -fsyntax-only -fblocks -triple x86_64-apple-darwin10 -verify %s
 // rdar://9092208
 
 __attribute__((unavailable("not available")))
@@ -98,3 +98,19 @@
 @end
 @interface UnavailSub(cat) // no error
 @end
+
+int unavail_global UNAVAILABLE;
+
+UNAVAILABLE __attribute__((objc_root_class))
+@interface TestAttrContext
+-meth;
+@end
+
+@implementation TestAttrContext
+-meth {
+  unavail_global = 2; // no warn
+  (void) ^{
+unavail_global = 4; // no warn
+  };
+}
+@end
Index: cfe/trunk/lib/Sema/SemaDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaDecl.cpp
+++ cfe/trunk/lib/Sema/SemaDecl.cpp
@@ -15615,29 +15615,3 @@
 Decl *Sema::getObjCDeclContext() const {
   return (dyn_cast_or_null(CurContext));
 }
-
-AvailabilityResult Sema::getCurContextAvailability() const {
-  const Decl *D = cast_or_null(getCurObjCLexicalContext());
-  if (!D)
-return AR_Available;
-
-  // If we are within an Objective-C method, we should consult
-  // both the availability of the method as well as the
-  // enclosing class.  If the class is (say) deprecated,
-  // the entire method is considered deprecated from the
-  // purpose of checking if the current context is deprecated.
-  if (const ObjCMethodDecl *MD = dyn_cast(D)) {
-AvailabilityResult R = MD->getAvailability();
-if (R != AR_Available)
-  return R;
-D = MD->getClassInterface();
-  }
-  // If we are within an Objective-c @implementation, it
-  // gets the same availability context as the @interface.
-  else if (const ObjCImplementationDecl *ID =
-dyn_cast(D)) {
-D = ID->getClassInterface();
-  }
-  // Recover from user error.
-  return D ? D->getAvailability() : AR_Available;
-}
Index: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
===
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp
@@ -6317,30 +6317,6 @@
   diag.Triggered = true;
 }
 
-static bool isDeclDeprecated(Decl *D) {
-  do {
-if (D->isDeprecated())
-  return true;
-// A category implicitly has the availability of the interface.
-if (const ObjCCategoryDecl *CatD = dyn_cast(D))
-  if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
-return Interface->isDeprecated();
-  } while ((D = cast_or_null(D->getDeclContext(;
-  return false;
-}
-
-static bool isDeclUnavailable(Decl *D) {
-  do {
-if (D->isUnavailable())
-  return true;
-// A category implicitly has the availability of the interface.
-if (co

[PATCH] D19854: Define Contiki OS toolchain

2016-10-14 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284278: Define Contiki OS toolchain (authored by dlkreitz).

Changed prior to commit:
  https://reviews.llvm.org/D19854?vs=70076&id=74741#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D19854

Files:
  cfe/trunk/lib/Driver/Driver.cpp
  cfe/trunk/lib/Driver/ToolChains.cpp
  cfe/trunk/lib/Driver/ToolChains.h
  cfe/trunk/test/Driver/fsanitize.c


Index: cfe/trunk/test/Driver/fsanitize.c
===
--- cfe/trunk/test/Driver/fsanitize.c
+++ cfe/trunk/test/Driver/fsanitize.c
@@ -397,6 +397,7 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=safe-stack 
-fstack-protector-all -### %s 2>&1 | FileCheck %s -check-prefix=SP
 // RUN: %clang -target arm-linux-androideabi -fsanitize=safe-stack -### %s 
2>&1 | FileCheck %s -check-prefix=NO-SP
 // RUN: %clang -target aarch64-linux-android -fsanitize=safe-stack -### %s 
2>&1 | FileCheck %s -check-prefix=NO-SP
+// RUN: %clang -target i386-contiki-unknown -fsanitize=safe-stack -### %s 2>&1 
| FileCheck %s -check-prefix=NO-SP
 // NO-SP-NOT: stack-protector
 // NO-SP: "-fsanitize=safe-stack"
 // SP: "-fsanitize=safe-stack"
Index: cfe/trunk/lib/Driver/ToolChains.h
===
--- cfe/trunk/lib/Driver/ToolChains.h
+++ cfe/trunk/lib/Driver/ToolChains.h
@@ -1249,6 +1249,14 @@
   Tool *buildLinker() const override;
 };
 
+class LLVM_LIBRARY_VISIBILITY Contiki : public Generic_ELF {
+public:
+  Contiki(const Driver &D, const llvm::Triple &Triple,
+  const llvm::opt::ArgList &Args);
+
+  SanitizerMask getSupportedSanitizers() const override;
+};
+
 } // end namespace toolchains
 } // end namespace driver
 } // end namespace clang
Index: cfe/trunk/lib/Driver/ToolChains.cpp
===
--- cfe/trunk/lib/Driver/ToolChains.cpp
+++ cfe/trunk/lib/Driver/ToolChains.cpp
@@ -5305,3 +5305,14 @@
   Res |= SanitizerKind::Vptr;
   return Res;
 }
+
+Contiki::Contiki(const Driver &D, const llvm::Triple &Triple, const ArgList 
&Args)
+: Generic_ELF(D, Triple, Args) {}
+
+SanitizerMask Contiki::getSupportedSanitizers() const {
+  const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
+  SanitizerMask Res = ToolChain::getSupportedSanitizers();
+  if (IsX86)
+Res |= SanitizerKind::SafeStack;
+  return Res;
+}
Index: cfe/trunk/lib/Driver/Driver.cpp
===
--- cfe/trunk/lib/Driver/Driver.cpp
+++ cfe/trunk/lib/Driver/Driver.cpp
@@ -3120,6 +3120,9 @@
 case llvm::Triple::PS4:
   TC = new toolchains::PS4CPU(*this, Target, Args);
   break;
+case llvm::Triple::Contiki:
+  TC = new toolchains::Contiki(*this, Target, Args);
+  break;
 default:
   // Of these targets, Hexagon is the only one that might have
   // an OS of Linux, in which case it got handled above already.


Index: cfe/trunk/test/Driver/fsanitize.c
===
--- cfe/trunk/test/Driver/fsanitize.c
+++ cfe/trunk/test/Driver/fsanitize.c
@@ -397,6 +397,7 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=safe-stack -fstack-protector-all -### %s 2>&1 | FileCheck %s -check-prefix=SP
 // RUN: %clang -target arm-linux-androideabi -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=NO-SP
 // RUN: %clang -target aarch64-linux-android -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=NO-SP
+// RUN: %clang -target i386-contiki-unknown -fsanitize=safe-stack -### %s 2>&1 | FileCheck %s -check-prefix=NO-SP
 // NO-SP-NOT: stack-protector
 // NO-SP: "-fsanitize=safe-stack"
 // SP: "-fsanitize=safe-stack"
Index: cfe/trunk/lib/Driver/ToolChains.h
===
--- cfe/trunk/lib/Driver/ToolChains.h
+++ cfe/trunk/lib/Driver/ToolChains.h
@@ -1249,6 +1249,14 @@
   Tool *buildLinker() const override;
 };
 
+class LLVM_LIBRARY_VISIBILITY Contiki : public Generic_ELF {
+public:
+  Contiki(const Driver &D, const llvm::Triple &Triple,
+  const llvm::opt::ArgList &Args);
+
+  SanitizerMask getSupportedSanitizers() const override;
+};
+
 } // end namespace toolchains
 } // end namespace driver
 } // end namespace clang
Index: cfe/trunk/lib/Driver/ToolChains.cpp
===
--- cfe/trunk/lib/Driver/ToolChains.cpp
+++ cfe/trunk/lib/Driver/ToolChains.cpp
@@ -5305,3 +5305,14 @@
   Res |= SanitizerKind::Vptr;
   return Res;
 }
+
+Contiki::Contiki(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
+: Generic_ELF(D, Triple, Args) {}
+
+SanitizerMask Contiki::getSupportedSanitizers() const {
+  const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
+  SanitizerMask Res = ToolChain::getSupportedSanitizers();
+  if (IsX86)
+Res |= SanitizerKind::SafeStack;
+  return Res

[PATCH] D25572: [Coverage] Support for C++17 if initializers

2016-10-14 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284293: [Coverage] Support for C++17 if initializers 
(authored by vedantk).

Changed prior to commit:
  https://reviews.llvm.org/D25572?vs=74559&id=74753#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25572

Files:
  cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
  cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
  cfe/trunk/test/CoverageMapping/if.c
  cfe/trunk/test/CoverageMapping/if.cpp
  cfe/trunk/test/Profile/cxx-stmt-initializers.cpp

Index: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
===
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
@@ -875,6 +875,9 @@
 
   void VisitIfStmt(const IfStmt *S) {
 extendRegion(S);
+if (S->getInit())
+  Visit(S->getInit());
+
 // Extend into the condition before we propagate through it below - this is
 // needed to handle macros that generate the "if" but not the condition.
 extendRegion(S->getCond());
Index: cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
===
--- cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
+++ cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
@@ -490,6 +490,8 @@
   void VisitIfStmt(const IfStmt *S) {
 RecordStmtCount(S);
 uint64_t ParentCount = CurrentCount;
+if (S->getInit())
+  Visit(S->getInit());
 Visit(S->getCond());
 
 // Counter tracks the "then" part of an if statement. The count for
Index: cfe/trunk/test/Profile/cxx-stmt-initializers.cpp
===
--- cfe/trunk/test/Profile/cxx-stmt-initializers.cpp
+++ cfe/trunk/test/Profile/cxx-stmt-initializers.cpp
@@ -4,6 +4,7 @@
 // RUN: FileCheck --input-file=%tgen -check-prefix=CHECK -check-prefix=PGOGEN %s
 
 // PGOGEN: @[[SIC:__profc__Z11switch_initv]] = private global [3 x i64] zeroinitializer
+// PGOGEN: @[[IIC:__profc__Z7if_initv]] = private global [3 x i64] zeroinitializer
 
 // Note: We expect counters for the function entry block, the condition in the
 // switch initializer, and the switch successor block.
@@ -15,3 +16,14 @@
   // PGOGEN: store {{.*}} @[[SIC]], i64 0, i64 2
   // PGOGEN: store {{.*}} @[[SIC]], i64 0, i64 1
 }
+
+// Note: We expect counters for the function entry block, the condition in the
+// if initializer, and the if successor block.
+//
+// CHECK-LABEL: define {{.*}}void @_Z7if_initv()
+// PGOGEN: store {{.*}} @[[IIC]], i64 0, i64 0
+void if_init() {
+  if (int i = true ? 0 : 1; i) {}
+  // PGOGEN: store {{.*}} @[[IIC]], i64 0, i64 2
+  // PGOGEN: store {{.*}} @[[IIC]], i64 0, i64 1
+}
Index: cfe/trunk/test/CoverageMapping/if.cpp
===
--- cfe/trunk/test/CoverageMapping/if.cpp
+++ cfe/trunk/test/CoverageMapping/if.cpp
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -std=c++1z -triple %itanium_abi_triple -main-file-name if.cpp %s | FileCheck %s
+
+int nop() { return 0; }
+
+// CHECK-LABEL: _Z3foov:
+void foo() {// CHECK-NEXT: [[@LINE]]:12 -> [[@LINE+5]]:2 = #0
+  if (int j = true ? nop()  // CHECK-NEXT: [[@LINE]]:22 -> [[@LINE]]:27 = #2
+   : nop(); // CHECK-NEXT: [[@LINE]]:22 -> [[@LINE]]:27 = (#0 - #2)
+  j)// CHECK-NEXT: [[@LINE]]:7 -> [[@LINE]]:8 = #0
+++j;// CHECK-NEXT: [[@LINE]]:5 -> [[@LINE]]:8 = #1
+}
+
+// CHECK-LABEL: main:
+int main() {// CHECK: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
+  int i = 0;
+// CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i == 0) i = 1; // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE]]:19 = #1
+// CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i == 1)
+i = 2;  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = #2
+// CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i == 0) { i = 1;   // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #3
+i = 2;
+  }
+// CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i != 0) {  // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #4
+i = 1;
+  } else {  // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:4 = (#0 - #4)
+i = 3;
+  }
+
+  i = i == 0?
+i + 1 : // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = #5
+i + 2;  // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = (#0 - #5)
+// CHECK-NEXT: File 0, [[@LINE+1]]:14 -> [[@LINE+1]]:20 = #6
+  i = i == 0?i + 12:i + 10; // CHECK-NEXT: File 0, [[@LINE]]:21 -> [[@LINE]]:27 = (#0 - #6)
+
+  return 0;
+}
I

[PATCH] D25539: [Coverage] Support for C++17 switch initializers

2016-10-14 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284292: [Coverage] Support for C++17 switch initializers 
(authored by vedantk).

Changed prior to commit:
  https://reviews.llvm.org/D25539?vs=74552&id=74752#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25539

Files:
  cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
  cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
  cfe/trunk/test/CoverageMapping/switch.c
  cfe/trunk/test/CoverageMapping/switch.cpp
  cfe/trunk/test/Profile/cxx-stmt-initializers.cpp

Index: cfe/trunk/test/CoverageMapping/switch.cpp
===
--- cfe/trunk/test/CoverageMapping/switch.cpp
+++ cfe/trunk/test/CoverageMapping/switch.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -std=c++1z -triple %itanium_abi_triple -main-file-name switch.cpp %s | FileCheck %s
+
+// CHECK: foo
+void foo(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+8]]:2 = #0
+  switch(i) {
+  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:10 = #2
+return;
+  case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #3
+break;
+  }
+  int x = 0;// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #1
+}
+
+int nop() { return 0; }
+
+// CHECK: bar
+void bar(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+20]]:2 = #0
+  switch (i)
+;   // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:6 = 0
+
+  switch (i) {  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+16]]:2 = #1
+  }
+
+  switch (i)// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+13]]:2 = #2
+nop();  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = 0
+
+  switch (i)// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+10]]:2 = #3
+  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #5
+nop();
+
+  switch (i) {  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:2 = #4
+nop();  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+2]]:10 = 0
+  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #7
+nop();
+  }
+  nop();// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #6
+}
+
+// CHECK: baz
+void baz() {// CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+5]]:2 = #0
+  switch (int i = true ? nop()  // CHECK-NEXT: [[@LINE]]:26 -> [[@LINE]]:31 = #2
+   : nop(); // CHECK-NEXT: [[@LINE]]:26 -> [[@LINE]]:31 = (#0 - #2)
+  i) {}
+  nop();// CHECK-NEXT: [[@LINE]]:3 -> [[@LINE+1]]:2 = #1
+}
+
+// CHECK-NEXT: main
+int main() {// CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+35]]:2 = #0
+  int i = 0;
+  switch(i) {
+  case 0:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+7]]:10 = #2
+i = 1;
+break;
+  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #3
+i = 2;
+break;
+  default:  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #4
+break;
+  }
+  switch(i) {   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+23]]:2 = #1
+  case 0:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:10 = #6
+i = 1;
+break;
+  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:10 = #7
+i = 2;
+  default:  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = (#7 + #8)
+break;
+  }
+
+  switch(i) {   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+13]]:2 = #5
+  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+5]]:11 = #10
+  case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+4]]:11 = (#10 + #11)
+i = 11;
+  case 3:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:11 = ((#10 + #11) + #12)
+  case 4:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = (((#10 + #11) + #12) + #13)
+i = 99;
+  }
+
+  foo(1);   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:11 = #9
+  bar(1);
+  baz();
+  return 0;
+}
Index: cfe/trunk/test/CoverageMapping/switch.c
===
--- cfe/trunk/test/CoverageMapping/switch.c
+++ cfe/trunk/test/CoverageMapping/switch.c
@@ -1,73 +0,0 @@
-// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name switch.c %s | FileCheck %s
-// CHECK: foo
-void foo(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+8]]:2 = #0
-  switch(i) {
-  case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:10 = #2
-return;
-  case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #3
-break;
-  }
-  int x = 0;// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #1
-}
-
-void nop() {}
-
-// CHECK: bar
-void bar(int i) {   // CHECK-NE

[PATCH] D119147: [AIX][clang][driver] Check the command string to the linker for exportlist opts

2022-08-30 Thread 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 rGfafa48e7b518: [AIX][clang][driver] Check the command string 
to the linker for exportlist opts (authored by zhijian 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119147

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Driver/Job.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-ld.c

Index: clang/test/Driver/aix-ld.c
===
--- clang/test/Driver/aix-ld.c
+++ clang/test/Driver/aix-ld.c
@@ -596,17 +596,29 @@
 // RUN:   | FileCheck --check-prefix=CHECK-LD-LIBSTDCXX %s
 // CHECK-LD-LIBSTDCXX: LLVM ERROR: linking libstdc++ unimplemented on AIX
 
-// Check powerpc64-ibm-aix7.1.0.0, 32-bit. -shared.
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared.
 // RUN: %clangxx -x c++ %s 2>&1 -### \
-// RUN:-resource-dir=%S/Inputs/resource_dir \
-// RUN:-shared \
+// RUN:-resource-dir=%S/Inputs/resource_dir -shared \
+// RUN:--target=powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:--unwindlib=libunwind \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED %s
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared (with exp option strings in other opt).
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir -shared \
 // RUN:--target=powerpc-ibm-aix7.1.0.0 \
 // RUN:--sysroot %S/Inputs/aix_ppc_tree \
 // RUN:--unwindlib=libunwind \
+// RUN:-Wl,-Z/expall/expfull/a-bE:/a-bexport:/ \
 // RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED %s
+
 // CHECK-LD32-SHARED: "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0"
 // CHECK-LD32-SHARED: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-LD32-SHARED: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-LD32-SHARED: "{{.*}}llvm-nm"
+// CHECK-LD32-SHARED: "--export-symbols"
+// CHECK-LD32-SHARED: "-X" "32"
 // CHECK-LD32-SHARED: "{{.*}}ld{{(.exe)?}}"
 // CHECK-LD32-SHARED: "-bM:SRE"
 // CHECK-LD32-SHARED: "-bnoentry"
@@ -623,10 +635,53 @@
 // CHECK-LD32-SHARED: "-lm"
 // CHECK-LD32-SHARED: "-lc"
 
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared with export list.
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir -shared \
+// RUN:--target=powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-Wl,-bE:input.exp \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED-EXPORTS %s
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared with export list (no -Wl, variant).
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir -shared \
+// RUN:--target=powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-bE:input.exp \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED-EXPORTS %s
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared with export list (-Xlinker variant).
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir -shared \
+// RUN:--target=powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-Xlinker -bE:input.exp \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED-EXPORTS %s
+
+// CHECK-LD32-SHARED-EXPORTS: "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0"
+// CHECK-LD32-SHARED-EXPORTS: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK-LD32-SHARED-EXPORTS: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "{{.*}}llvm-nm"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "-X"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "32"
+// CHECK-LD32-SHARED-EXPORTS: "{{.*}}ld{{(.exe)?}}"
+// CHECK-LD32-SHARED-EXPORTS: "-bM:SRE"
+// CHECK-LD32-SHARED-EXPORTS: "-bnoentry"
+// CHECK-LD32-SHARED-EXPORTS: "-b32"
+// CHECK-LD32-SHARED-EXPORTS: "-bpT:0x1000" "-bpD:0x2000"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
+// CHECK-LD32-SHARED-EXPORTS: "-b{{(" ")?}}E:input.exp"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "-bE:{{[^"]+}}"
+// CHECK-LD32-SHARED-EXPORTS: "-lc++"
+// CHECK-LD32-SHARED-EXPORTS: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-SHARED-EXPORTS: "-lm"
+// CHECK-LD32-SHARED-EXPORTS: "-lc"
+
 // Check powerpc64-ibm-aix7.1.0.0, 64-bit. -shared.
 // RUN: %clangxx -x c++ %s 2>&1 -### \
-// RUN:-resource-dir=%S/Inputs/resource_dir \
-// RUN:-shared \
+// RUN:-resource-dir=%S/Inputs/resource_dir -shared \
 // RUN:--target=powerpc64-ibm-aix7.1.0.0 \
 // RUN:--sysro

[PATCH] D132911: [clang-format] Fix annotating when deleting array of pointers

2022-09-02 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3bbdf06b2827: [clang-format] Fix annotating when deleting 
array of pointers (authored by jackh ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132911

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -120,6 +120,17 @@
   Tokens = annotate("int i = int{42} * 2;");
   EXPECT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::star, TT_BinaryOperator);
+
+  Tokens = annotate("delete[] *ptr;");
+  EXPECT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_UnaryOperator);
+  Tokens = annotate("delete[] **ptr;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_UnaryOperator);
+  EXPECT_TOKEN(Tokens[4], tok::star, TT_UnaryOperator);
+  Tokens = annotate("delete[] *(ptr);");
+  EXPECT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_UnaryOperator);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10535,6 +10535,11 @@
"} &&ptr = {};",
Style);
 
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("delete[] *ptr;", Style);
+  verifyFormat("delete[] **ptr;", Style);
+  verifyFormat("delete[] *(ptr);", Style);
+
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2372,6 +2372,9 @@
 !PrevToken->MatchingParen)
   return TT_PointerOrReference;
 
+if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
+  return TT_UnaryOperator;
+
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
tok::kw_false, tok::r_brace)) {


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -120,6 +120,17 @@
   Tokens = annotate("int i = int{42} * 2;");
   EXPECT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::star, TT_BinaryOperator);
+
+  Tokens = annotate("delete[] *ptr;");
+  EXPECT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_UnaryOperator);
+  Tokens = annotate("delete[] **ptr;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_UnaryOperator);
+  EXPECT_TOKEN(Tokens[4], tok::star, TT_UnaryOperator);
+  Tokens = annotate("delete[] *(ptr);");
+  EXPECT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_UnaryOperator);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10535,6 +10535,11 @@
"} &&ptr = {};",
Style);
 
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("delete[] *ptr;", Style);
+  verifyFormat("delete[] **ptr;", Style);
+  verifyFormat("delete[] *(ptr);", Style);
+
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2372,6 +2372,9 @@
 !PrevToken->MatchingParen)
   return TT_PointerOrReference;
 
+if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
+  return TT_UnaryOperator;
+
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
tok::kw_false, tok::r_brace)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133308: [cmake] do not set execution permission to regular files

2022-09-06 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG73593145cb5b: [cmake] do not set execution permission to 
regular files. (authored by sinan, committed by Lin Sinan 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133308

Files:
  clang-tools-extra/clang-include-fixer/tool/CMakeLists.txt
  clang/CMakeLists.txt
  clang/tools/clang-format/CMakeLists.txt
  clang/tools/clang-rename/CMakeLists.txt
  clang/tools/scan-build-py/CMakeLists.txt

Index: clang/tools/scan-build-py/CMakeLists.txt
===
--- clang/tools/scan-build-py/CMakeLists.txt
+++ clang/tools/scan-build-py/CMakeLists.txt
@@ -87,7 +87,7 @@
${CMAKE_BINARY_DIR}/lib/libscanbuild/
  DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/lib/libscanbuild/${lib})
   list(APPEND Depends ${CMAKE_BINARY_DIR}/lib/libscanbuild/${lib})
-  install(PROGRAMS lib/libscanbuild/${lib}
+  install(FILES lib/libscanbuild/${lib}
   DESTINATION lib${CLANG_LIBDIR_SUFFIX}/libscanbuild
   COMPONENT scan-build-py)
 endforeach()
@@ -105,7 +105,7 @@
${CMAKE_BINARY_DIR}/lib/libscanbuild/resources
  DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/lib/libscanbuild/resources/${resource})
   list(APPEND Depends ${CMAKE_BINARY_DIR}/lib/libscanbuild/resources/${resource})
-  install(PROGRAMS lib/libscanbuild/resources/${resource}
+  install(FILES lib/libscanbuild/resources/${resource}
   DESTINATION lib${CLANG_LIBDIR_SUFFIX}/libscanbuild/resources
   COMPONENT scan-build-py)
 endforeach()
@@ -121,7 +121,7 @@
${CMAKE_BINARY_DIR}/lib/libear/
  DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/lib/libear/${lib})
   list(APPEND Depends ${CMAKE_BINARY_DIR}/lib/libear/${lib})
-  install(PROGRAMS lib/libear/${lib}
+  install(FILES lib/libear/${lib}
   DESTINATION lib${CLANG_LIBDIR_SUFFIX}/libear
   COMPONENT scan-build-py)
 endforeach()
Index: clang/tools/clang-rename/CMakeLists.txt
===
--- clang/tools/clang-rename/CMakeLists.txt
+++ clang/tools/clang-rename/CMakeLists.txt
@@ -18,9 +18,9 @@
   clangToolingRefactoring
   )
 
-install(PROGRAMS clang-rename.py
+install(FILES clang-rename.py
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-rename)
-install(PROGRAMS clang-rename.el
+install(FILES clang-rename.el
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-rename)
Index: clang/tools/clang-format/CMakeLists.txt
===
--- clang/tools/clang-format/CMakeLists.txt
+++ clang/tools/clang-format/CMakeLists.txt
@@ -20,19 +20,19 @@
   add_subdirectory(fuzzer)
 endif()
 
-install(PROGRAMS clang-format-bbedit.applescript
+install(FILES clang-format-bbedit.applescript
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-format)
 install(PROGRAMS clang-format-diff.py
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-format)
-install(PROGRAMS clang-format-sublime.py
+install(FILES clang-format-sublime.py
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-format)
-install(PROGRAMS clang-format.el
+install(FILES clang-format.el
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-format)
-install(PROGRAMS clang-format.py
+install(FILES clang-format.py
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-format)
 install(PROGRAMS git-clang-format
Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -418,7 +418,7 @@
   endif()
 
   add_custom_target(bash-autocomplete DEPENDS utils/bash-autocomplete.sh)
-  install(PROGRAMS utils/bash-autocomplete.sh
+  install(FILES utils/bash-autocomplete.sh
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT bash-autocomplete)
   if(NOT LLVM_ENABLE_IDE)
Index: clang-tools-extra/clang-include-fixer/tool/CMakeLists.txt
===
--- clang-tools-extra/clang-include-fixer/tool/CMakeLists.txt
+++ clang-tools-extra/clang-include-fixer/tool/CMakeLists.txt
@@ -20,9 +20,9 @@
   findAllSymbols
   )
 
-install(PROGRAMS clang-include-fixer.el
+install(FILES clang-include-fixer.el
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-include-fixer)
-install(PROGRAMS clang-include-fixer.py
+install(FILES clang-include-fixer.py
   DESTINATION "${CMAKE_INSTALL_DATADIR}/clang"
   COMPONENT clang-include-fixer)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122513: [analyzer] Fix "RhsLoc and LhsLoc bitwidth must be same"

2022-03-29 Thread 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 rGfe8b2236ef9c: [analyzer] Fix "RhsLoc and LhsLoc 
bitwidth must be same" (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122513

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/addrspace-null.c


Index: clang/test/Analysis/addrspace-null.c
===
--- /dev/null
+++ clang/test/Analysis/addrspace-null.c
@@ -0,0 +1,47 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DAMDGCN_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+//
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DDEFAULT_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// different than Generic.
+
+// expected-no-diagnostics
+
+#define DEVICE __attribute__((address_space(3)))
+
+#if defined(AMDGCN_TRIPLE)
+// this crashes
+int fn1() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (void *)0;
+}
+
+// does not crash
+int fn2() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+
+// this crashes
+int fn3() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+#endif
+
+// does not crash
+int fn4() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (void *)0;
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -682,8 +682,11 @@
   }
 
   // Pointer to any pointer.
-  if (Loc::isLocType(CastTy))
-return V;
+  if (Loc::isLocType(CastTy)) {
+llvm::APSInt Value = V.getValue();
+BasicVals.getAPSIntType(CastTy).apply(Value);
+return loc::ConcreteInt(BasicVals.getValue(Value));
+  }
 
   // Pointer to whatever else.
   return UnknownVal();


Index: clang/test/Analysis/addrspace-null.c
===
--- /dev/null
+++ clang/test/Analysis/addrspace-null.c
@@ -0,0 +1,47 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DAMDGCN_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+//
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DDEFAULT_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// different than Generic.
+
+// expected-no-diagnostics
+
+#define DEVICE __attribute__((address_space(3)))
+
+#if defined(AMDGCN_TRIPLE)
+// this crashes
+int fn1() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (void *)0;
+}
+
+// does not crash
+int fn2() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+
+// this crashes
+int fn3() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+#endif
+
+// does not crash
+int fn4() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (void *)0;
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -682,8 +682,11 @@
   }
 
   // Pointer to any pointer.
-  if (Loc::isLocType(CastTy))
-return V;
+  if (Loc::isLocType(CastTy)) {
+llvm::APSInt Value = V.getValue();
+BasicVals.getAPSIntType(CastTy).apply(Value);
+return loc::ConcreteInt(BasicVals.getValue(Value));
+  }
 
   // Pointer to whatever else.
   return UnknownVal();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118050: [analyzer] Avoid checking addrspace pointers in cstring checker

2022-03-31 Thread 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 rG4d5b824e3df2: [analyzer] Avoid checking addrspace pointers 
in cstring checker (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118050

Files:
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/cstring-addrspace.c

Index: clang/test/Analysis/cstring-addrspace.c
===
--- /dev/null
+++ clang/test/Analysis/cstring-addrspace.c
@@ -0,0 +1,64 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core,alpha.unix.cstring \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -analyzer-config crosscheck-with-z3=true -verify %s \
+// RUN: -Wno-incompatible-library-redeclaration
+// REQUIRES: z3
+
+void clang_analyzer_warnIfReached();
+
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// different than Generic.
+#define DEVICE __attribute__((address_space(3)))
+_Static_assert(sizeof(int *) == 8, "");
+_Static_assert(sizeof(DEVICE int *) == 4, "");
+_Static_assert(sizeof(void *) == 8, "");
+_Static_assert(sizeof(DEVICE void *) == 4, "");
+
+// Copy from host to device memory. Note this is specialized
+// since one of the parameters is assigned an address space such
+// that the sizeof the the pointer is different than the other.
+//
+// Some downstream implementations may have specialized memcpy
+// routines that copy from one address space to another. In cases
+// like that, the address spaces are assumed to not overlap, so the
+// cstring overlap check is not needed. When a static analysis report
+// is generated in as case like this, SMTConv may attempt to create
+// a refutation to Z3 with different bitwidth pointers which lead to
+// a crash. This is not common in directly used upstream compiler builds,
+// but can be seen in specialized downstrean implementations. This case
+// covers those specific instances found and debugged.
+//
+// Since memcpy is a builtin, a specialized builtin instance named like
+// 'memcpy_special' will hit in cstring, triggering this behavior. The
+// best we can do for an upstream test is use the same memcpy function name.
+DEVICE void *memcpy(DEVICE void *dst, const void *src, unsigned long len);
+
+void top1(DEVICE void *dst, void *src, int len) {
+  memcpy(dst, src, len);
+
+  // Create a bugreport for triggering Z3 refutation.
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+}
+
+void top2(DEVICE int *dst, void *src, int len) {
+  memcpy(dst, src, len);
+
+  // Create a bugreport for triggering Z3 refutation.
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+}
+
+void top3(DEVICE int *dst, int *src, int len) {
+  memcpy(dst, src, len);
+
+  // Create a bugreport for triggering Z3 refutation.
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+}
+
+void top4() {
+  memcpy((DEVICE void *)1, (const void *)1, 1);
+
+  // Create a bugreport for triggering Z3 refutation.
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -715,11 +715,41 @@
   llvm_unreachable("Fields not found in parent record's definition");
 }
 
+// This is used in debug builds only for now because some downstream users
+// may hit this assert in their subsequent merges.
+// There are still places in the analyzer where equal bitwidth Locs
+// are compared, and need to be found and corrected. Recent previous fixes have
+// addressed the known problems of making NULLs with specific bitwidths
+// for Loc comparisons along with deprecation of APIs for the same purpose.
+//
+static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
+ Loc LhsLoc) {
+  // Implements a "best effort" check for RhsLoc and LhsLoc bit widths
+  ASTContext &Ctx = State->getStateManager().getContext();
+  uint64_t RhsBitwidth =
+  RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
+  uint64_t LhsBitwidth =
+  LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
+  if (RhsBitwidth && LhsBitwidth &&
+  (LhsLoc.getSubKind() == RhsLoc.getSubKind())) {
+assert(RhsBitwidth == LhsBitwidth &&
+   "RhsLoc and LhsLoc bitwidth must be same!");
+  }
+}
+
 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
 SVal SimpleSValBuil

[PATCH] D105974: [analyzer] Do not assume that all pointers have the same bitwidth as void*

2021-07-16 Thread 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 rG918bda124120: [analyzer] Do not assume that all pointers 
have the same bitwidth as void* (authored by vabridgers, committed by einvbri 
).

Changed prior to commit:
  https://reviews.llvm.org/D105974?vs=359163&id=359246#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105974

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/solver-sym-simplification-ptr-bool.cl


Index: clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
===
--- /dev/null
+++ clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown -analyze 
-analyzer-checker=core %s
+
+// expected-no-diagnostics
+
+// This test case covers an issue found in the static analyzer
+// solver where pointer sizes were assumed. Pointer sizes may vary on other
+// architectures. This issue was originally discovered on a downstream,
+// custom target, this assert occurs on the custom target and this one
+// without the fix, and is fixed with this change.
+//
+// The assertion appears to be happening as a result of evaluating the
+// SymIntExpr (reg_$0) != 0U in VisitSymIntExpr located in
+// SimpleSValBuilder.cpp. The LHS is evaluated to 32b and the RHS is
+// evaluated to 16b. This eventually leads to the assertion in APInt.h.
+//
+// APInt.h:1151: bool llvm::APInt::operator==(const llvm::APInt &) const: 
Assertion `BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"'
+// 
+void test1(__attribute__((address_space(256))) int * p) {
+  __attribute__((address_space(256))) int * q = p-1;
+  if (q) {}
+  if (q) {}
+  (void)q;
+}
+ 
+void test2(__attribute__((address_space(256))) int * p) {
+  __attribute__((address_space(256))) int * q = p-1;
+  q && q; 
+  q && q; 
+  (void)q;
+} 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -712,9 +712,23 @@
   // symbols to use, only content metadata.
   return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
 
-if (const SymbolicRegion *SymR = R->getSymbolicBase())
-  return makeNonLoc(SymR->getSymbol(), BO_NE,
-BasicVals.getZeroWithPtrWidth(), CastTy);
+if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
+  SymbolRef Sym = SymR->getSymbol();
+  QualType Ty = Sym->getType();
+  // This change is needed for architectures with varying
+  // pointer widths. See the amdgcn opencl reproducer with
+  // this change as an example: solver-sym-simplification-ptr-bool.cl
+  // FIXME: We could encounter a reference here,
+  //try returning a concrete 'true' since it might
+  //be easier on the solver.
+  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
+  //and `getIntWithPtrWidth()` functions to prevent future
+  //confusion
+  const llvm::APSInt &Zero = Ty->isReferenceType()
+ ? BasicVals.getZeroWithPtrWidth()
+ : BasicVals.getZeroWithTypeSize(Ty);
+  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+}
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
   }


Index: clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
===
--- /dev/null
+++ clang/test/Analysis/solver-sym-simplification-ptr-bool.cl
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown -analyze -analyzer-checker=core %s
+
+// expected-no-diagnostics
+
+// This test case covers an issue found in the static analyzer
+// solver where pointer sizes were assumed. Pointer sizes may vary on other
+// architectures. This issue was originally discovered on a downstream,
+// custom target, this assert occurs on the custom target and this one
+// without the fix, and is fixed with this change.
+//
+// The assertion appears to be happening as a result of evaluating the
+// SymIntExpr (reg_$0) != 0U in VisitSymIntExpr located in
+// SimpleSValBuilder.cpp. The LHS is evaluated to 32b and the RHS is
+// evaluated to 16b. This eventually leads to the assertion in APInt.h.
+//
+// APInt.h:1151: bool llvm::APInt::operator==(const llvm::APInt &) const: Assertion `BitWidth == RHS.BitWidth && "Comparison requires equal bit widths"'
+// 
+void test1(__attribute__((address_space(256))) int * p) {
+  __attribute__((address_space(256))) int * q = p-1;
+  if (q) {}
+  if (q) {}
+  (void)q;
+}
+ 
+void test2(__attribute__((address_

[PATCH] D106833: [dfsan][NFC] Add compile flags and environment variables to doc

2021-07-26 Thread 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 rGc7b7638dfee5: [dfsan][NFC] Add compile flags and environment 
variables to doc (authored by Jianzhou Zhao ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106833

Files:
  clang/docs/DataFlowSanitizer.rst


Index: clang/docs/DataFlowSanitizer.rst
===
--- clang/docs/DataFlowSanitizer.rst
+++ clang/docs/DataFlowSanitizer.rst
@@ -137,6 +137,88 @@
   fun:memcpy=uninstrumented
   fun:memcpy=custom
 
+Compilation Flags
+-
+
+* ``-dfsan-abilist`` -- The additional ABI list files that control how shadow
+  parameters are passed. File names are separated by comma.
+* ``-dfsan-combine-pointer-labels-on-load`` -- Controls whether to include or
+  ignore the labels of pointers in load instructions. Its default value is 
true.
+  For example:
+
+.. code-block:: c++
+  v = *p;
+
+If the flag is true, the label of ``v`` is the union of the label of ``p`` and
+the label of ``*p``. If the flag is false, the label of ``v`` is the label of
+just ``*p``.
+* ``-dfsan-combine-pointer-labels-on-store`` -- Controls whether to include or
+  ignore the labels of pointers in store instructions. Its default value is
+  false. For example:
+
+.. code-block:: c++
+  *p = v;
+
+If the flag is true, the label of ``*p`` is the union of the label of ``p`` and
+the label of ``v``. If the flag is false, the label of ``*p`` is the label of
+just ``v``.
+* ``-dfsan-combine-offset-labels-on-gep`` -- Controls whether to propagate
+  labels of offsets in GEP instructions. Its default value is true. For 
example:
+
+.. code-block:: c++
+  p += i;
+
+If the flag is true, the label of ``p`` is the union of the label of ``p`` and
+the label of ``i``. If the flag is false, the label of ``p`` is unchanged.
+* ``-dfsan-track-select-control-flow`` -- Controls whether to track the control
+  flow of select instructions. Its default value is true. For example:
+
+.. code-block:: c++
+  v = b? v1: v2;
+
+If the flag is true, the label of ``v`` is the union of the labels of ``b``,
+``v1`` and ``v2``.  If the flag is false, the label of ``v`` is the union of 
the
+labels of just ``v1`` and ``v2``.
+* ``-dfsan-event-callbacks`` -- An experimental feature that inserts callbacks 
for
+certain data events. Currently callbacks are only inserted for loads, stores,
+memory transfers (i.e. memcpy and memmove), and comparisons. Its default value
+is false. If this flag is set to true, a user must provide definitions for the
+following callback functions:
+
+.. code-block:: c++
+  void __dfsan_load_callback(dfsan_label Label, void* Addr);
+  void __dfsan_store_callback(dfsan_label Label, void* Addr);
+  void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
+  void __dfsan_cmp_callback(dfsan_label CombinedLabel);
+* ``-dfsan-track-origins`` -- Controls how to track origins. When its value is
+  0, the runtime does not track origins. When its value is 1, the runtime 
tracks
+  origins at memory store operations. When its value is 2, the runtime tracks
+  origins at memory load and store operations. Its default value is 0.
+* ``-dfsan-instrument-with-call-threshold`` -- If a function being instrumented
+   requires more than this number of origin stores, use callbacks instead of
+  inline checks (-1 means never use callbacks). Its default value is 3500.
+
+Environment Variables
+-
+
+* ``warn_unimplemented`` -- Whether to warn on unimplemented functions. Its
+  default value is false.
+* ``strict_data_dependencies`` -- Whether to propagate labels only when there 
is
+  explicit obvious data dependency (e.g., when comparing strings, ignore the 
fact
+  that the output of the comparison might be implicit data-dependent on the
+  content of the strings). This applies only to functions with ``custom`` 
category
+  in ABI list. Its default value is true.
+* ``origin_history_size`` -- The limit of origin chain length. Non-positive 
values
+  mean unlimited. Its default value is 16.
+* ``origin_history_per_stack_limit`` -- The limit of origin node's references 
count.
+  Non-positive values mean unlimited. Its default value is 2.
+* ``store_context_size`` -- The depth limit of origin tracking stack traces. 
Its
+  default value is 20.
+* ``zero_in_malloc`` -- Whether to zero shadow space of new allocated memory. 
Its
+  default value is true.
+* ``zero_in_free`` --- Whether to zero shadow space of deallocated memory. Its
+  default value is true.
+
 Example
 ===
 


Index: clang/docs/DataFlowSanitizer.rst
===
--- clang/docs/DataFlowSanitizer.rst
+++ clang/docs/DataFlowSanitizer.rst
@@ -137,6 +137,88 @@
   fun:memcpy=uninstrumented
   fun:memc

[PATCH] D106895: [dfsan][NFC] Update API interfaces

2021-07-27 Thread 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 rG00411ebeeb71: [dfsan][NFC] Update API interfaces (authored 
by Jianzhou Zhao ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106895

Files:
  clang/docs/DataFlowSanitizerDesign.rst


Index: clang/docs/DataFlowSanitizerDesign.rst
===
--- clang/docs/DataFlowSanitizerDesign.rst
+++ clang/docs/DataFlowSanitizerDesign.rst
@@ -48,12 +48,79 @@
   /// value.
   dfsan_label dfsan_get_label(long data);
 
+  /// Retrieves the label associated with the data at the given address.
+  dfsan_label dfsan_read_label(const void *addr, size_t size);
+
   /// Returns whether the given label label contains the label elem.
   int dfsan_has_label(dfsan_label label, dfsan_label elem);
 
   /// Computes the union of \c l1 and \c l2, resulting in a union label.
   dfsan_label dfsan_union(dfsan_label l1, dfsan_label l2);
 
+  /// Flushes the DFSan shadow, i.e. forgets about all labels currently 
associated
+  /// with the application memory.  Use this call to start over the taint 
tracking
+  /// within the same process.
+  ///
+  /// Note: If another thread is working with tainted data during the flush, 
that
+  /// taint could still be written to shadow after the flush.
+  void dfsan_flush(void);
+
+The following functions are provided to check origin tracking status and 
results.
+
+.. code-block:: c
+
+  /// Retrieves the immediate origin associated with the given data. The 
returned
+  /// origin may point to another origin.
+  ///
+  /// The type of 'data' is arbitrary. The function accepts a value of any 
type,
+  /// which can be truncated or extended (implicitly or explicitly) as 
necessary.
+  /// The truncation/extension operations will preserve the label of the 
original
+  /// value.
+  dfsan_origin dfsan_get_origin(long data);
+
+  /// Retrieves the very first origin associated with the data at the given
+  /// address.
+  dfsan_origin dfsan_get_init_origin(const void *addr);
+
+  /// Prints the origin trace of the label at the address `addr` to stderr. It 
also
+  /// prints description at the beginning of the trace. If origin tracking is 
not
+  /// on, or the address is not labeled, it prints nothing.
+  void dfsan_print_origin_trace(const void *addr, const char *description);
+
+  /// Prints the origin trace of the label at the address `addr` to a 
pre-allocated
+  /// output buffer. If origin tracking is not on, or the address is`
+  /// not labeled, it prints nothing.
+  ///
+  /// `addr` is the tainted memory address whose origin we are printing.
+  /// `description` is a description printed at the beginning of the trace.
+  /// `out_buf` is the output buffer to write the results to. `out_buf_size` is
+  /// the size of `out_buf`. The function returns the number of symbols that
+  /// should have been written to `out_buf` (not including trailing null byte 
'\0').
+  /// Thus, the string is truncated iff return value is not less than 
`out_buf_size`.
+  size_t dfsan_sprint_origin_trace(const void *addr, const char *description,
+   char *out_buf, size_t out_buf_size);
+
+  /// Returns the value of `-dfsan-track-origins`.
+  int dfsan_get_track_origins(void);
+
+The following functions are provided to register hooks called by custom 
wrappers.
+
+.. code-block:: c
+
+  /// Sets a callback to be invoked on calls to `write`.  The callback is 
invoked
+  /// before the write is done. The write is not guaranteed to succeed when the
+  /// callback executes. Pass in NULL to remove any callback.
+  typedef void (*dfsan_write_callback_t)(int fd, const void *buf, size_t 
count);
+  void dfsan_set_write_callback(dfsan_write_callback_t labeled_write_callback);
+
+  /// Callbacks to be invoked on calls to `memcmp` or `strncmp`.
+  void dfsan_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
+  size_t n, dfsan_label s1_label,
+  dfsan_label s2_label, dfsan_label n_label);
+  void dfsan_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2,
+  size_t n, dfsan_label s1_label,
+  dfsan_label s2_label, dfsan_label n_label);
+
 Taint label representation
 --
 


Index: clang/docs/DataFlowSanitizerDesign.rst
===
--- clang/docs/DataFlowSanitizerDesign.rst
+++ clang/docs/DataFlowSanitizerDesign.rst
@@ -48,12 +48,79 @@
   /// value.
   dfsan_label dfsan_get_label(long data);
 
+  /// Retrieves the label associated with the data at the given address.
+  dfsan_label dfsan_read_label(const void *addr, size_t size);
+
   /// Returns whether the given label label cont

[PATCH] D106903: [dfsan][NFC] Describe how origin trace tracking works

2021-07-27 Thread 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 rGc49df15c2788: [dfsan][NFC] Describe how origin trace 
tracking works (authored by Jianzhou Zhao ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106903

Files:
  clang/docs/DataFlowSanitizerDesign.rst


Index: clang/docs/DataFlowSanitizerDesign.rst
===
--- clang/docs/DataFlowSanitizerDesign.rst
+++ clang/docs/DataFlowSanitizerDesign.rst
@@ -135,6 +135,35 @@
 track of what labels they have used so far, picking one that is yet
 unused, etc).
 
+Origin tracking trace representation
+
+
+An origin tracking trace is a list of chains. Each chain has a stack trace
+where the DFSan runtime records a label propapation, and a pointer to its
+previous chain. The very first chain does not point to any chain.
+
+Every four 4-bytes aligned application bytes share a 4-byte origin trace ID. A
+4-byte origin trace ID contains a 4-bit depth and a 28-bit hash ID of a chain.
+
+A chain ID is calculated as a hash from a chain structure. A chain structure
+contains a stack ID and the previous chain ID. The chain head has a zero
+previous chain ID. A stack ID is a hash from a stack trace. The 4-bit depth
+limits the maximal length of a path. The environment variable 
``origin_history_size``
+can set the depth limit. Non-positive values mean unlimited. Its default value
+is 16. When reaching the limit, origin tracking ignores following propagation
+chains.
+
+The first chain of a trace starts by `dfsan_set_label` with non-zero labels. A
+new chain is appended at the end of a trace at stores or memory transfers when
+``-dfsan-track-origins`` is 1. Memory transfers include LLVM memory transfer
+instructions, glibc memcpy and memmove. When ``-dfsan-track-origins`` is 2, a
+new chain is also appended at loads.
+
+Other instructions do not create new chains, but simply propagate origin trace
+IDs. If an instruction has more than one operands with non-zero labels, the 
origin
+treace ID of the last operand with non-zero label is propagated to the result 
of
+the instruction.
+
 Memory layout and label management
 --
 


Index: clang/docs/DataFlowSanitizerDesign.rst
===
--- clang/docs/DataFlowSanitizerDesign.rst
+++ clang/docs/DataFlowSanitizerDesign.rst
@@ -135,6 +135,35 @@
 track of what labels they have used so far, picking one that is yet
 unused, etc).
 
+Origin tracking trace representation
+
+
+An origin tracking trace is a list of chains. Each chain has a stack trace
+where the DFSan runtime records a label propapation, and a pointer to its
+previous chain. The very first chain does not point to any chain.
+
+Every four 4-bytes aligned application bytes share a 4-byte origin trace ID. A
+4-byte origin trace ID contains a 4-bit depth and a 28-bit hash ID of a chain.
+
+A chain ID is calculated as a hash from a chain structure. A chain structure
+contains a stack ID and the previous chain ID. The chain head has a zero
+previous chain ID. A stack ID is a hash from a stack trace. The 4-bit depth
+limits the maximal length of a path. The environment variable ``origin_history_size``
+can set the depth limit. Non-positive values mean unlimited. Its default value
+is 16. When reaching the limit, origin tracking ignores following propagation
+chains.
+
+The first chain of a trace starts by `dfsan_set_label` with non-zero labels. A
+new chain is appended at the end of a trace at stores or memory transfers when
+``-dfsan-track-origins`` is 1. Memory transfers include LLVM memory transfer
+instructions, glibc memcpy and memmove. When ``-dfsan-track-origins`` is 2, a
+new chain is also appended at loads.
+
+Other instructions do not create new chains, but simply propagate origin trace
+IDs. If an instruction has more than one operands with non-zero labels, the origin
+treace ID of the last operand with non-zero label is propagated to the result of
+the instruction.
+
 Memory layout and label management
 --
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119601: [analyzer] Refactor makeNull to makeNullWithWidth (NFC)

2022-03-22 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG985888411da9: [analyzer] Refactor makeNull to 
makeNullWithWidth (NFC) (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119601

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/cast-value-notes.cpp

Index: clang/test/Analysis/cast-value-notes.cpp
===
--- clang/test/Analysis/cast-value-notes.cpp
+++ clang/test/Analysis/cast-value-notes.cpp
@@ -1,9 +1,22 @@
 // RUN: %clang_analyze_cc1 -std=c++14 \
 // RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
-// RUN:  -analyzer-output=text -verify %s
+// RUN:  -analyzer-output=text -verify -DDEFAULT_TRIPLE %s 2>&1 | FileCheck %s -check-prefix=DEFAULT-CHECK
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple amdgcn-unknown-unknown \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN: -analyzer-output=text -verify -DAMDGCN_TRIPLE %s 2>&1 | FileCheck %s -check-prefix=AMDGCN-CHECK
 
 #include "Inputs/llvm.h"
 
+// The amggcn triple case uses an intentionally different address space.
+// The core.NullDereference checker intentionally ignores checks
+// that use address spaces, so the case is differentiated here.
+//
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// different than Generic.
+#define DEVICE __attribute__((address_space(3)))
+
 namespace clang {
 struct Shape {
   template 
@@ -21,12 +34,30 @@
 using namespace llvm;
 using namespace clang;
 
+void clang_analyzer_printState();
+
+#if defined(DEFAULT_TRIPLE)
 void evalReferences(const Shape &S) {
   const auto &C = dyn_cast(S);
   // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
+  clang_analyzer_printState();
+  // DEFAULT-CHECK: "dynamic_types": [
+  // DEFAULT-CHECK-NEXT: { "region": "SymRegion{reg_$0}", "dyn_type": "const class clang::Circle &", "sub_classable": true }
+  (void)C;
+}
+#elif defined(AMDGCN_TRIPLE)
+void evalReferences(const Shape &S) {
+  const auto &C = dyn_cast(S);
+  clang_analyzer_printState();
+  // AMDGCN-CHECK: "dynamic_types": [
+  // AMDGCN-CHECK-NEXT: { "region": "SymRegion{reg_$0}", "dyn_type": "const __attribute__((address_space(3))) class clang::Circle &", "sub_classable": true }
+  (void)C;
 }
+#else
+#error Target must be specified, and must be pinned
+#endif
 
 void evalNonNullParamNonNullReturnReference(const Shape &S) {
   const auto *C = dyn_cast_or_null(S);
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -61,7 +61,7 @@
 
 DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) {
   if (Loc::isLocType(type))
-return makeNull();
+return makeNullWithType(type);
 
   if (type->isIntegralOrEnumerationType())
 return makeIntVal(0, type);
@@ -359,7 +359,7 @@
 return makeBoolVal(cast(E));
 
   case Stmt::CXXNullPtrLiteralExprClass:
-return makeNull();
+return makeNullWithType(E->getType());
 
   case Stmt::CStyleCastExprClass:
   case Stmt::CXXFunctionalCastExprClass:
@@ -399,7 +399,7 @@
 
 if (Loc::isLocType(E->getType()))
   if (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
-return makeNull();
+return makeNullWithType(E->getType());
 
 return None;
   }
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2410,7 +2410,7 @@
   SVal V;
 
   if (Loc::isLocType(T))
-V = svalBuilder.makeNull();
+V = svalBuilder.makeNullWithType(T);
   else if (T->isIntegralOrEnumerationType())
 V = svalBuilder.makeZeroVal(T);
   else if (T->isStructureOrClassType() || T->isArrayType()) {
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -46

[PATCH] D120134: [analyzer] refactor makeIntValWithPtrWidth, remove getZeroWithPtrWidth (NFC)

2022-03-23 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5fdc4dd77704: [analyzer] refactor makeIntValWithPtrWidth, 
remove getZeroWithPtrWidth (NFC) (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120134

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -742,9 +742,6 @@
   // This change is needed for architectures with varying
   // pointer widths. See the amdgcn opencl reproducer with
   // this change as an example: solver-sym-simplification-ptr-bool.cl
-  // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
-  //and `getIntWithPtrWidth()` functions to prevent future
-  //confusion
   if (!Ty->isReferenceType())
 return makeNonLoc(Sym, BO_NE, BasicVals.getZeroWithTypeSize(Ty),
   CastTy);
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1345,8 +1345,9 @@
 case Stmt::GNUNullExprClass: {
   // GNU __null is a pointer-width integer, not an actual pointer.
   ProgramStateRef state = Pred->getState();
-  state = state->BindExpr(S, Pred->getLocationContext(),
-  svalBuilder.makeIntValWithPtrWidth(0, false));
+  state = state->BindExpr(
+  S, Pred->getLocationContext(),
+  svalBuilder.makeIntValWithWidth(getContext().VoidPtrTy, 0));
   Bldr.generateNode(S, Pred, state);
   break;
 }
Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -2608,8 +2608,9 @@
 
   // Compare the size argument to 0.
   DefinedOrUnknownSVal SizeZero =
-svalBuilder.evalEQ(State, TotalSize.castAs(),
-   svalBuilder.makeIntValWithPtrWidth(0, false));
+  svalBuilder.evalEQ(State, TotalSize.castAs(),
+ svalBuilder.makeIntValWithWidth(
+ svalBuilder.getContext().getSizeType(), 0));
 
   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -332,9 +332,8 @@
 return nonloc::ConcreteInt(BasicVals.getIntValue(integer, isUnsigned));
   }
 
-  NonLoc makeIntValWithPtrWidth(uint64_t integer, bool isUnsigned) {
-return nonloc::ConcreteInt(
-BasicVals.getIntWithPtrWidth(integer, isUnsigned));
+  NonLoc makeIntValWithWidth(QualType ptrType, uint64_t integer) {
+return nonloc::ConcreteInt(BasicVals.getValue(integer, ptrType));
   }
 
   NonLoc makeLocAsInteger(Loc loc, unsigned bits) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -220,14 +220,6 @@
 return getValue(0, Ctx.getTypeSize(T), true);
   }
 
-  const llvm::APSInt &getZeroWithPtrWidth(bool isUnsigned = true) {
-return getValue(0, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned);
-  }
-
-  const llvm::APSInt &getIntWithPtrWidth(uint64_t X, bool isUnsigned) {
-return getValue(X, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned);
-  }
-
   const llvm::APSInt &getTruthValue(bool b, QualType T) {
 return getValue(b ? 1 : 0, Ctx.getIntWidth(T),
 T->isUnsignedIntegerOrEnumerationType());


Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -742,9 +742,6 @@
   // This change is needed for architectures with varying
   // pointer widths. See the amdgcn opencl reproducer with
   // this change as an example: solver-sym-

[PATCH] D122277: [analyzer] Fix crash in RangedConstraintManager.cpp

2022-03-23 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9ef7ac51af67: [analyzer] Fix crash in 
RangedConstraintManager.cpp (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122277

Files:
  clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
  clang/test/Analysis/symbol-simplification-bo-div.c

Index: clang/test/Analysis/symbol-simplification-bo-div.c
===
--- /dev/null
+++ clang/test/Analysis/symbol-simplification-bo-div.c
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core %s \
+// RUN:-triple x86_64-pc-linux-gnu -verify
+
+// don't crash
+// expected-no-diagnostics
+
+int a, b;
+int c(void) {
+  unsigned d = a;
+  --d;
+  short e = b / b - a;
+  ++e;
+  return d <= 0 && e && e;
+}
Index: clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
@@ -48,47 +48,48 @@
 
   if (const auto *SSE = dyn_cast(Sym)) {
 BinaryOperator::Opcode Op = SSE->getOpcode();
-assert(BinaryOperator::isComparisonOp(Op));
-
-// We convert equality operations for pointers only.
-if (Loc::isLocType(SSE->getLHS()->getType()) &&
-Loc::isLocType(SSE->getRHS()->getType())) {
-  // Translate "a != b" to "(b - a) != 0".
-  // We invert the order of the operands as a heuristic for how loop
-  // conditions are usually written ("begin != end") as compared to length
-  // calculations ("end - begin"). The more correct thing to do would be to
-  // canonicalize "a - b" and "b - a", which would allow us to treat
-  // "a != b" and "b != a" the same.
-
-  SymbolManager &SymMgr = getSymbolManager();
-  QualType DiffTy = SymMgr.getContext().getPointerDiffType();
-  SymbolRef Subtraction =
-  SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
-
-  const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
-  Op = BinaryOperator::reverseComparisonOp(Op);
-  if (!Assumption)
-Op = BinaryOperator::negateComparisonOp(Op);
-  return assumeSymRel(State, Subtraction, Op, Zero);
-}
+if (BinaryOperator::isComparisonOp(Op)) {
+
+  // We convert equality operations for pointers only.
+  if (Loc::isLocType(SSE->getLHS()->getType()) &&
+  Loc::isLocType(SSE->getRHS()->getType())) {
+// Translate "a != b" to "(b - a) != 0".
+// We invert the order of the operands as a heuristic for how loop
+// conditions are usually written ("begin != end") as compared to length
+// calculations ("end - begin"). The more correct thing to do would be
+// to canonicalize "a - b" and "b - a", which would allow us to treat
+// "a != b" and "b != a" the same.
+
+SymbolManager &SymMgr = getSymbolManager();
+QualType DiffTy = SymMgr.getContext().getPointerDiffType();
+SymbolRef Subtraction =
+SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
+
+const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
+Op = BinaryOperator::reverseComparisonOp(Op);
+if (!Assumption)
+  Op = BinaryOperator::negateComparisonOp(Op);
+return assumeSymRel(State, Subtraction, Op, Zero);
+  }
 
-if (BinaryOperator::isEqualityOp(Op)) {
-  SymbolManager &SymMgr = getSymbolManager();
+  if (BinaryOperator::isEqualityOp(Op)) {
+SymbolManager &SymMgr = getSymbolManager();
 
-  QualType ExprType = SSE->getType();
-  SymbolRef CanonicalEquality =
-  SymMgr.getSymSymExpr(SSE->getLHS(), BO_EQ, SSE->getRHS(), ExprType);
+QualType ExprType = SSE->getType();
+SymbolRef CanonicalEquality =
+SymMgr.getSymSymExpr(SSE->getLHS(), BO_EQ, SSE->getRHS(), ExprType);
 
-  bool WasEqual = SSE->getOpcode() == BO_EQ;
-  bool IsExpectedEqual = WasEqual == Assumption;
+bool WasEqual = SSE->getOpcode() == BO_EQ;
+bool IsExpectedEqual = WasEqual == Assumption;
 
-  const llvm::APSInt &Zero = getBasicVals().getValue(0, ExprType);
+const llvm::APSInt &Zero = getBasicVals().getValue(0, ExprType);
 
-  if (IsExpectedEqual) {
-return assumeSymNE(State, CanonicalEquality, Zero, Zero);
-  }
+if (IsExpectedEqual) {
+  return assumeSymNE(State, CanonicalEquality, Zero, Zero);
+}
 
-  return assumeSymEQ(State, CanonicalEquality, Zero, Zero);
+return assumeSymEQ(State, CanonicalEquality, Zero, Zero);
+  }
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.

[PATCH] D117972: [PowerPC] Fix SSE translation on FreeBSD

2022-02-05 Thread 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 rGf2f4080c10f4: [PowerPC] Fix SSE translation on FreeBSD 
(authored by pkubaj, committed by Qiu Chaofan ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117972

Files:
  clang/lib/Headers/ppc_wrappers/mm_malloc.h


Index: clang/lib/Headers/ppc_wrappers/mm_malloc.h
===
--- clang/lib/Headers/ppc_wrappers/mm_malloc.h
+++ clang/lib/Headers/ppc_wrappers/mm_malloc.h
@@ -19,7 +19,7 @@
 #ifndef __cplusplus
 extern int posix_memalign (void **, size_t, size_t);
 #else
-extern "C" int posix_memalign (void **, size_t, size_t) throw ();
+extern "C" int posix_memalign (void **, size_t, size_t);
 #endif
 
 static __inline void *


Index: clang/lib/Headers/ppc_wrappers/mm_malloc.h
===
--- clang/lib/Headers/ppc_wrappers/mm_malloc.h
+++ clang/lib/Headers/ppc_wrappers/mm_malloc.h
@@ -19,7 +19,7 @@
 #ifndef __cplusplus
 extern int posix_memalign (void **, size_t, size_t);
 #else
-extern "C" int posix_memalign (void **, size_t, size_t) throw ();
+extern "C" int posix_memalign (void **, size_t, size_t);
 #endif
 
 static __inline void *
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119440: [OpenMP][NFC] update status for 5.1 'nothing' directive to 'worked on'

2022-02-10 Thread Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG02a05097e700: [OpenMP][NFC] update status for 5.1 
'nothing' directive to 'worked on' (authored by dreachem, 
committed by Chi-Chun, Chen ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119440

Files:
  clang/docs/OpenMPSupport.rst


Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -339,7 +339,7 @@
 
+--+--+--+---+
 | misc extension   | assume and assumes directives 
   | :part:`worked on`| 
  |
 
+--+--+--+---+
-| misc extension   | nothing directive 
   | :none:`unclaimed`| 
  |
+| misc extension   | nothing directive 
   | :part:`worked on`| 
  |
 
+--+--+--+---+
 | misc extension   | masked construct and related combined 
constructs | :part:`worked on`| D5, D100514 
  |
 
+--+--+--+---+


Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -339,7 +339,7 @@
 +--+--+--+---+
 | misc extension   | assume and assumes directives| :part:`worked on`|   |
 +--+--+--+---+
-| misc extension   | nothing directive| :none:`unclaimed`|   |
+| misc extension   | nothing directive| :part:`worked on`|   |
 +--+--+--+---+
 | misc extension   | masked construct and related combined constructs | :part:`worked on`| D5, D100514   |
 +--+--+--+---+
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123464: [analyzer] Clean checker options from bool to DefaultBool (NFC)

2022-04-23 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5114db933dbf: [analyzer] Clean checker options from bool to 
DefaultBool (NFC) (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123464

Files:
  clang/include/clang/StaticAnalyzer/Core/Checker.h
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  clang/lib/StaticAnalyzer/Checkers/CloneChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
  clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp

Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -46,7 +46,7 @@
 CK_NumCheckKinds
   };
 
-  DefaultBool ChecksEnabled[CK_NumCheckKinds];
+  bool ChecksEnabled[CK_NumCheckKinds] = {false};
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
   void checkPreStmt(const VAArgExpr *VAA, CheckerContext &C) const;
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -43,7 +43,7 @@
   mutable Optional Val_O_CREAT;
 
 public:
-  DefaultBool CheckMisuse, CheckPortability;
+  bool CheckMisuse = false, CheckPortability = false;
 
   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
 
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -563,7 +563,7 @@
 CK_StdCLibraryFunctionsTesterChecker,
 CK_NumCheckKinds
   };
-  DefaultBool ChecksEnabled[CK_NumCheckKinds];
+  bool ChecksEnabled[CK_NumCheckKinds] = {false};
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
   bool DisplayLoadedSummaries = false;
Index: clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -42,7 +42,7 @@
 CK_NumCheckKinds
   };
 
-  DefaultBool ChecksEnabled[CK_NumCheckKinds];
+  bool ChecksEnabled[CK_NumCheckKinds] = {false};
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -48,7 +48,7 @@
 
 public:
   // Whether the checker should model for null dereferences of smart pointers.
-  DefaultBool ModelSmartPtrDereference;
+  bool ModelSmartPtrDereference = false;
   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Index: clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
@@ -78,7 +78,7 @@
 CK_C11LockChecker,
 CK_NumCheckKinds
   };
-  DefaultBool ChecksEnabled[CK_NumCheckKinds];
+  bool ChecksEnabled[CK_NumCheckKinds] = {false};
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
 private:
Index: clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -90,7 +90,7 @@
   // find warnings about nullability annotations that they have explicitly
   // added themselves higher priority to fix 

[PATCH] D122841: [analyzer] Add option for AddrSpace in core.NullDereference check

2022-04-24 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3566bbe62f2e: [analyzer] Add option for AddrSpace in 
core.NullDereference check (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122841

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/cast-value-notes.cpp

Index: clang/test/Analysis/cast-value-notes.cpp
===
--- clang/test/Analysis/cast-value-notes.cpp
+++ clang/test/Analysis/cast-value-notes.cpp
@@ -1,10 +1,44 @@
-// RUN: %clang_analyze_cc1 -std=c++14 \
-// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
-// RUN:  -analyzer-output=text -verify -DDEFAULT_TRIPLE %s 2>&1 | FileCheck %s -check-prefix=DEFAULT-CHECK
+// RUN: %clang_analyze_cc1 -std=c++14 -triple amdgcn-unknown-unknown \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN: -analyzer-output=text -verify -DX86 -DSUPPRESSED %s 2>&1 | FileCheck %s -check-prefix=X86-CHECK
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple amdgcn-unknown-unknown \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN:  -analyzer-config core.NullDereference:SuppressAddressSpaces=false\
+// RUN:  -analyzer-output=text -verify -DX86 -DNOT_SUPPRESSED %s 2>&1 | FileCheck %s -check-prefix=X86-CHECK
 //
 // RUN: %clang_analyze_cc1 -std=c++14 -triple amdgcn-unknown-unknown \
 // RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
-// RUN: -analyzer-output=text -verify -DAMDGCN_TRIPLE %s 2>&1 | FileCheck %s -check-prefix=AMDGCN-CHECK
+// RUN:  -analyzer-config core.NullDereference:SuppressAddressSpaces=true\
+// RUN:  -analyzer-output=text -verify -DX86 -DSUPPRESSED %s 2>&1 | FileCheck %s -check-prefix=X86-CHECK
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-unknown-unknown \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN:  -analyzer-output=text -verify -DX86 -DSUPPRESSED %s 2>&1 | FileCheck %s --check-prefix=X86-CHECK
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-unknown-unknown \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN:  -analyzer-config core.NullDereference:SuppressAddressSpaces=true\
+// RUN:  -analyzer-output=text -verify -DX86 -DSUPPRESSED %s 2>&1 | FileCheck %s --check-prefix=X86-CHECK-SUPPRESSED
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-unknown-unknown \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN:  -analyzer-config core.NullDereference:SuppressAddressSpaces=false\
+// RUN:  -analyzer-output=text -verify -DX86 -DNOT_SUPPRESSED %s 2>&1 | FileCheck %s --check-prefix=X86-CHECK
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple mips-unknown-unknown \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN: -analyzer-output=text -verify -DMIPS %s 2>&1
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple mips-unknown-unknown \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN: -analyzer-config core.NullDereference:SuppressAddressSpaces=false\
+// RUN: -analyzer-output=text -verify -DMIPS %s 2>&1
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple mips-unknown-unknown \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN: -analyzer-config core.NullDereference:SuppressAddressSpaces=true\
+// RUN: -analyzer-output=text -verify -DMIPS_SUPPRESSED %s
 
 #include "Inputs/llvm.h"
 
@@ -36,27 +70,51 @@
 
 void clang_analyzer_printState();
 
-#if defined(DEFAULT_TRIPLE)
+#if defined(X86)
 void evalReferences(const Shape &S) {
   const auto &C = dyn_cast(S);
   // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
   clang_analyzer_printState();
-  // DEFAULT-CHECK: "dynamic_types": [
-  // DEFAULT-CHECK-NEXT: { "region": "SymRegion{reg_$0}", "dyn_type": "const class clang::Circle &", "sub_classable": true }
+  // XX86-CHECK:  "dynamic_types": [
+  // XX86-CHECK-NEXT:   { "region": "SymRegion{reg_$0}", "dyn_type": "const class clang::Circle &", "sub_classable": true }
   (void)C;
 }
-#elif defined(AMDGCN_TRIPLE)
-void evalReferences(const Shape &S) {
+#if defined(SUPPRESSED)
+void evalReferences_addrspace(const Shape &S) {
   const auto &C = dyn_cast(S);
   clang_analyzer_printState();
-  // AMDGCN-CHECK: "dynamic_types": [
-  // AMDGCN-CHECK-NEXT: { "region": "SymRegion{reg_$0}", "dyn_type": "const __attribute__((address_space(3)

[PATCH] D122920: [Clang][CodeGen]Fix __builtin_dump_struct missing record type field name

2022-04-28 Thread 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 rGeaca933c59fd: [Clang][CodeGen]Fix __builtin_dump_struct 
missing record type field name (authored by jonasyhwang 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122920

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/dump-struct-builtin.c

Index: clang/test/CodeGen/dump-struct-builtin.c
===
--- clang/test/CodeGen/dump-struct-builtin.c
+++ clang/test/CodeGen/dump-struct-builtin.c
@@ -4,95 +4,148 @@
 #include 
 
 // CHECK: @__const.unit1.a = private unnamed_addr constant %struct.U1A { i16 12 }, align 2
-// CHECK-NEXT: [[STRUCT_STR_U1:@[0-9]+]] = private unnamed_addr constant [14 x i8] c"struct U1A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U1:@[0-9]+]] = private unnamed_addr constant [19 x i8] c"short a = %hd\0A\00", align 1
-// CHECK-NEXT: [[END_STRUCT_U1:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_STR_U1:@[0-9]+]] = private unnamed_addr constant [12 x i8] c"struct U1A \00", align 1
+// CHECK-NEXT: [[STRUCT_L_BRACE_U1:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"{\0A\00", align 1
+// CHECK-NEXT: [[FIELD_U1:@[0-9]+]] = private unnamed_addr constant [15 x i8] c"short a = \00", align 1
+// CHECK-NEXT: [[FORMAT_U1:@[0-9]+]] = private unnamed_addr constant [5 x i8] c"%hd\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_R_BRACE_U1:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
 
 // CHECK: @__const.unit2.a = private unnamed_addr constant %struct.U2A { i16 12 }, align 2
-// CHECK-NEXT: [[STRUCT_STR_U2:@[0-9]+]] = private unnamed_addr constant [14 x i8] c"struct U2A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U2:@[0-9]+]] = private unnamed_addr constant [28 x i8] c"unsigned short a = %hu\0A\00", align 1
-// CHECK-NEXT: [[END_STRUCT_U2:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_STR_U2:@[0-9]+]] = private unnamed_addr constant [12 x i8] c"struct U2A \00", align 1
+// CHECK-NEXT: [[STRUCT_L_BRACE_U2:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"{\0A\00", align 1
+// CHECK-NEXT: [[FIELD_U2:@[0-9]+]] = private unnamed_addr constant [24 x i8] c"unsigned short a = \00", align 1
+// CHECK-NEXT: [[FORMAT_U2:@[0-9]+]] = private unnamed_addr constant [5 x i8] c"%hu\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_R_BRACE_U2:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
 
 // CHECK: @__const.unit3.a = private unnamed_addr constant %struct.U3A { i32 12 }, align 4
-// CHECK-NEXT: [[STRUCT_STR_U3:@[0-9]+]] = private unnamed_addr constant [14 x i8] c"struct U3A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U3:@[0-9]+]] = private unnamed_addr constant [16 x i8] c"int a = %d\0A\00", align 1
-// CHECK-NEXT: [[END_STRUCT_U3:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_STR_U3:@[0-9]+]] = private unnamed_addr constant [12 x i8] c"struct U3A \00", align 1
+// CHECK-NEXT: [[STRUCT_L_BRACE_U3:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"{\0A\00", align 1
+// CHECK-NEXT: [[FIELD_U3:@[0-9]+]] = private unnamed_addr constant [13 x i8] c"int a = \00", align 1
+// CHECK-NEXT: [[FORMAT_U3:@[0-9]+]] = private unnamed_addr constant [4 x i8] c"%d\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_R_BRACE_U3:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
 
 // CHECK: @__const.unit4.a = private unnamed_addr constant %struct.U4A { i32 12 }, align 4
-// CHECK-NEXT: [[STRUCT_STR_U4:@[0-9]+]] = private unnamed_addr constant [14 x i8] c"struct U4A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U4:@[0-9]+]] = private unnamed_addr constant [25 x i8] c"unsigned int a = %u\0A\00", align 1
-// CHECK-NEXT: [[END_STRUCT_U4:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_STR_U4:@[0-9]+]] = private unnamed_addr constant [12 x i8] c"struct U4A \00", align 1
+// CHECK-NEXT: [[STRUCT_L_BRACE_U4:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"{\0A\00", align 1
+// CHECK-NEXT: [[FIELD_U4:@[0-9]+]] = private unnamed_addr constant [22 x i8] c"unsigned int a = \00", align 1
+// CHECK-NEXT: [[FORMAT_U4:@[0-9]+]] = private unnamed_addr constant [4 x i8] c"%u\0A\00", align 1
+// CHECK-NEXT: [[STRUCT_R_BRACE_U4:@[0-9]+]] = private unnamed_addr constant [3 x i8] c"}\0A\00", align 1
 
 // CHECK: @__const.unit5.a = private unnamed_addr constant %struct.U5A { i64 12 }, align 8
-// CHECK-NEXT: [[STRUCT_STR_U5:@[0-9]+]] = private unnamed_addr constant [14 x i8] c"struct U5A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U5:@[0-9]+]] = private unnamed_addr constant [18 x i8] c"long a = %ld\0A\00", align 1
-// CHECK-NEXT: [[END_STRUCT_U5:@[0-9]+]] = private

[PATCH] D124349: [analyzer] Get direct binding for specific punned case

2022-05-05 Thread 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 rGdf5801806d03: [analyzer] Get direct binding for specific 
punned case (authored by einvbri ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124349

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/array-punned-region.c


Index: clang/test/Analysis/array-punned-region.c
===
--- /dev/null
+++ clang/test/Analysis/array-punned-region.c
@@ -0,0 +1,39 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false -triple x86_64-pc-linux-gnu %s
+
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false -triple i386-pc-linux-gnu  %s
+
+int clang_analyzer_eval(int);
+
+typedef struct {
+  int a : 1;
+  int b[2];
+} BITFIELD_CAST;
+
+void array_struct_bitfield_1() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  clang_analyzer_eval(*((int *)pff + 1) == 0); // expected-warning{{TRUE}}
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 1) == 3); // expected-warning{{TRUE}}
+}
+
+int array_struct_bitfield_2() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  int a = *((int *)pff + 2); // expected-warning{{Assigned value is garbage or 
undefined [core.uninitialized.Assign]}}
+  return a;
+}
+
+typedef struct {
+  unsigned int a : 1;
+  unsigned int x : 31;
+  unsigned int c : 1;
+  int b[2];
+} mystruct;
+
+void array_struct_bitfield_3() {
+  mystruct ff;
+  mystruct *pff = &ff;
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 2) == 3); // expected-warning{{TRUE}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2147,8 +2147,13 @@
   return UnknownVal();
 
 // Additionally allow introspection of a block's internal layout.
-if (!hasPartialLazyBinding && !isa(R->getBaseRegion()))
+// Try to get direct binding if all other attempts failed thus far.
+// Else, return UndefinedVal()
+if (!hasPartialLazyBinding && !isa(R->getBaseRegion())) {
+  if (const Optional &V = B.getDefaultBinding(R))
+return *V;
   return UndefinedVal();
+}
   }
 
   // All other values are symbolic.


Index: clang/test/Analysis/array-punned-region.c
===
--- /dev/null
+++ clang/test/Analysis/array-punned-region.c
@@ -0,0 +1,39 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config eagerly-assume=false -triple x86_64-pc-linux-gnu %s
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config eagerly-assume=false -triple i386-pc-linux-gnu  %s
+
+int clang_analyzer_eval(int);
+
+typedef struct {
+  int a : 1;
+  int b[2];
+} BITFIELD_CAST;
+
+void array_struct_bitfield_1() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  clang_analyzer_eval(*((int *)pff + 1) == 0); // expected-warning{{TRUE}}
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 1) == 3); // expected-warning{{TRUE}}
+}
+
+int array_struct_bitfield_2() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  int a = *((int *)pff + 2); // expected-warning{{Assigned value is garbage or undefined [core.uninitialized.Assign]}}
+  return a;
+}
+
+typedef struct {
+  unsigned int a : 1;
+  unsigned int x : 31;
+  unsigned int c : 1;
+  int b[2];
+} mystruct;
+
+void array_struct_bitfield_3() {
+  mystruct ff;
+  mystruct *pff = &ff;
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 2) == 3); // expected-warning{{TRUE}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2147,8 +2147,13 @@
   return UnknownVal();
 
 // Additionally allow introspection of a block's internal layout.
-if (!hasPartialLazyBinding && !isa(R->getBaseRegion()))
+// Try to get direct binding if all other attempts failed thus far.
+// Else, return UndefinedVal()
+if (!hasPartialLazyBinding && !isa(R->getBaseRegion())) {
+  if (const Optional &V = B.getDefaultBinding(R))
+return *V;
   return UndefinedVal();
+}
   }
 
   // All other values are symbolic.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129269: [analyzer] Fix use of length in CStringChecker

2022-07-13 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1d7e58cfade1: [analyzer] Fix use of length in CStringChecker 
(authored by einvbri ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129269

Files:
  clang/docs/analyzer/checkers.rst
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/string.c


Index: clang/test/Analysis/string.c
===
--- clang/test/Analysis/string.c
+++ clang/test/Analysis/string.c
@@ -1652,3 +1652,18 @@
   __builtin___memset_chk(&x, 0, sizeof(x), __builtin_object_size(&x, 0));
   clang_analyzer_eval(x == 0); // expected-warning{{TRUE}}
 }
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void strcpy_no_overflow_2(char *y) {
+  char x[3];
+  // FIXME: string literal modeling does not account for embedded NULLs.
+  //This case should not elicit a warning, but does.
+  //See discussion at https://reviews.llvm.org/D129269
+  strcpy(x, "12\0"); // expected-warning{{String copy function overflows the 
destination buffer}}
+}
+#else
+void strcpy_no_overflow_2(char *y) {
+  char x[3];
+  strcpy(x, "12\0");
+}
+#endif
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -848,7 +848,7 @@
 SValBuilder &svalBuilder = C.getSValBuilder();
 QualType sizeTy = svalBuilder.getContext().getSizeType();
 const StringLiteral *strLit = cast(MR)->getStringLiteral();
-return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
+return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
   }
   case MemRegion::SymbolicRegionKind:
   case MemRegion::AllocaRegionKind:
Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -2726,6 +2726,9 @@
 ""
 Check for out-of-bounds access in string functions; applies to:`` strncopy, 
strncat``.
 
+This check also applies to string literals, except there is a known bug in that
+the analyzer cannot detect embedded NULL characters.
+
 .. code-block:: c
 
  void test() {


Index: clang/test/Analysis/string.c
===
--- clang/test/Analysis/string.c
+++ clang/test/Analysis/string.c
@@ -1652,3 +1652,18 @@
   __builtin___memset_chk(&x, 0, sizeof(x), __builtin_object_size(&x, 0));
   clang_analyzer_eval(x == 0); // expected-warning{{TRUE}}
 }
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void strcpy_no_overflow_2(char *y) {
+  char x[3];
+  // FIXME: string literal modeling does not account for embedded NULLs.
+  //This case should not elicit a warning, but does.
+  //See discussion at https://reviews.llvm.org/D129269
+  strcpy(x, "12\0"); // expected-warning{{String copy function overflows the destination buffer}}
+}
+#else
+void strcpy_no_overflow_2(char *y) {
+  char x[3];
+  strcpy(x, "12\0");
+}
+#endif
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -848,7 +848,7 @@
 SValBuilder &svalBuilder = C.getSValBuilder();
 QualType sizeTy = svalBuilder.getContext().getSizeType();
 const StringLiteral *strLit = cast(MR)->getStringLiteral();
-return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
+return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
   }
   case MemRegion::SymbolicRegionKind:
   case MemRegion::AllocaRegionKind:
Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -2726,6 +2726,9 @@
 ""
 Check for out-of-bounds access in string functions; applies to:`` strncopy, strncat``.
 
+This check also applies to string literals, except there is a known bug in that
+the analyzer cannot detect embedded NULL characters.
+
 .. code-block:: c
 
  void test() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125840: [Analyzer] Removed extra space from NSErrorChecker debug message and updated relevant tests

2022-05-18 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdd7233bc67e4: [Analyzer] Remove extra space from 
NSErrorChecker message. (authored by usama54321, committed by Artem Dergachev 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125840

Files:
  clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
  clang/test/Analysis/CheckNSError.m
  clang/test/Analysis/incorrect-checker-names.mm


Index: clang/test/Analysis/incorrect-checker-names.mm
===
--- clang/test/Analysis/incorrect-checker-names.mm
+++ clang/test/Analysis/incorrect-checker-names.mm
@@ -107,7 +107,7 @@
 
 void foo(CFErrorRef* error) { // expected-warning{{Function accepting 
CFErrorRef* should have a non-void return value to indicate whether or not an 
error occurred [osx.coreFoundation.CFError]}}
   // FIXME: This shouldn't be tied to a modeling checker.
-  *error = 0; // expected-warning {{Potential null dereference.  According to 
coding standards documented in CoreFoundation/CFError.h the parameter may be 
null [osx.coreFoundation.CFError]}}
+  *error = 0; // expected-warning {{Potential null dereference. According to 
coding standards documented in CoreFoundation/CFError.h the parameter may be 
null [osx.coreFoundation.CFError]}}
 }
 
 @interface A
@@ -116,7 +116,7 @@
 
 @implementation A
 - (void)myMethodWhichMayFail:(NSError **)error {  // 
expected-warning {{Method accepting NSError** should have a non-void return 
value to indicate whether or not an error occurred [osx.cocoa.NSError]}}
-  *error = [NSError errorWithDomain:@"domain" code:1 userInfo:0]; // 
expected-warning {{Potential null dereference.  According to coding standards 
in 'Creating and Returning NSError Objects' the parameter may be null 
[osx.cocoa.NSError]}}
+  *error = [NSError errorWithDomain:@"domain" code:1 userInfo:0]; // 
expected-warning {{Potential null dereference. According to coding standards in 
'Creating and Returning NSError Objects' the parameter may be null 
[osx.cocoa.NSError]}}
 }
 @end
 
Index: clang/test/Analysis/CheckNSError.m
===
--- clang/test/Analysis/CheckNSError.m
+++ clang/test/Analysis/CheckNSError.m
@@ -27,7 +27,7 @@
 
 @implementation A
 - (void)myMethodWhichMayFail:(NSError **)error {   // expected-warning 
{{Method accepting NSError** should have a non-void return value to indicate 
whether or not an error occurred}}
-  *error = [NSError errorWithDomain:@"domain" code:1 userInfo:0]; // 
expected-warning {{Potential null dereference}}
+  *error = [NSError errorWithDomain:@"domain" code:1 userInfo:0]; // 
expected-warning {{Potential null dereference. According to coding standards in 
'Creating and Returning NSError Objects' the parameter may be null 
[osx.cocoa.NSError]}}
 }
 
 - (BOOL)myMethodWhichMayFail2:(NSError **)error {  // no-warning
@@ -50,7 +50,7 @@
 typedef struct __CFError* CFErrorRef;
 
 void foo(CFErrorRef* error) { // expected-warning {{Function accepting 
CFErrorRef* should have a non-void return value to indicate whether or not an 
error occurred}}
-  *error = 0;  // expected-warning {{Potential null dereference}}
+  *error = 0; // expected-warning {{Potential null 
dereference. According to coding standards documented in 
CoreFoundation/CFError.h the parameter may be null 
[osx.coreFoundation.CFError]}}
 }
 
 int f1(CFErrorRef* error) {
@@ -74,7 +74,7 @@
 }
 
 int __attribute__((nonnull(1))) f5(int *x, CFErrorRef *error) {
-  *error = 0; // expected-warning {{Potential null dereference}}
+  *error = 0; // expected-warning {{Potential null dereference. According to 
coding standards documented in CoreFoundation/CFError.h the parameter may be 
null [osx.coreFoundation.CFError]}}
   return 0;
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp
@@ -266,7 +266,7 @@
   SmallString<128> Buf;
   llvm::raw_svector_ostream os(Buf);
 
-  os << "Potential null dereference.  According to coding standards ";
+  os << "Potential null dereference. According to coding standards ";
   os << (isNSError
  ? "in 'Creating and Returning NSError Objects' the parameter"
  : "documented in CoreFoundation/CFError.h the parameter");


Index: clang/test/Analysis/incorrect-checker-names.mm
===
--- clang/test/Analysis/incorrect-checker-names.mm
+++ clang/test/Analysis/incorrect-checker-names.mm
@@ -107,7 +107,7 @@
 
 void foo(CFErrorRef* error) { // expected-warning{{Function accepting CFErrorRef* should have a non-void return value to indicate whether or not an error occurred [os

[PATCH] D158266: [OpenMP] Patch for Support to loop bind clause : Checking Parent Region

2023-10-26 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG85f6b2fac9a3: [OpenMP] Patch for Support to loop bind clause 
: Checking Parent Region (authored by koops, committed by Sandeep Kosuri 
).

Changed prior to commit:
  https://reviews.llvm.org/D158266?vs=557877&id=557890#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158266

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/loop_bind_messages.cpp
  clang/test/PCH/pragma-loop.cpp

Index: clang/test/PCH/pragma-loop.cpp
===
--- clang/test/PCH/pragma-loop.cpp
+++ clang/test/PCH/pragma-loop.cpp
@@ -116,9 +116,13 @@
 
   inline void run10(int *List, int Length) {
 int i = 0;
-#pragma omp loop bind(teams)
+int j = 0;
+#pragma omp teams
 for (int i = 0; i < Length; i++) {
-  List[i] = i;
+  #pragma omp loop bind(teams)
+  for (int j = 0; j < Length; j++) {
+List[i] = i+j;
+  }
 }
   }
 
Index: clang/test/OpenMP/loop_bind_messages.cpp
===
--- clang/test/OpenMP/loop_bind_messages.cpp
+++ clang/test/OpenMP/loop_bind_messages.cpp
@@ -4,6 +4,7 @@
 
 #define NNN 50
 int aaa[NNN];
+int aaa2[NNN][NNN];
 
 void parallel_loop() {
   #pragma omp parallel
@@ -15,6 +16,91 @@
}
 }
 
+void parallel_for_AND_loop_bind() {
+  #pragma omp parallel for
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_nowait() {
+  #pragma omp parallel
+  #pragma omp for nowait
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_for_with_nothing() {
+  #pragma omp parallel for
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp nothing
+#pragma omp loop // expected-error{{region cannot be closely nested inside 'parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_targetfor_with_loop_bind() {
+  #pragma omp target teams distribute parallel for 
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'target teams distribute parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_targetparallel_with_loop() {
+  #pragma omp target parallel
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel)
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void loop_bind_AND_loop_bind() {
+  #pragma omp parallel for
+  for (int i = 0; i < 100; ++i) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}} 
+for (int i = 0 ; i < NNN ; i++) {
+  #pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'loop' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}} 
+  for (int j = 0 ; j < NNN ; j++) {
+aaa[j] = j*NNN;
+  }
+}
+  }
+}
+
+void parallel_with_sections_loop() {
+  #pragma omp parallel
+  {
+ #pragma omp sections
+ {
+for (int i = 0 ; i < NNN ; i++) {
+  #pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'sections' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+  for (int j = 0 ; j < NNN ; j++) {
+aaa2[i][j] = i+j;
+  }
+}
+
+#pragma omp section
+	{
+  aaa[NNN-1] = NNN;
+}
+ }
+  }
+}
+
 void teams_loop() {
   int var1, var2;
 
@@ -34,17 +120,23 @@
}
 }
 
-void orphan_loop_with_bind() {
-  #pragma omp loop bind(parallel) 
-  for (int j = 0 ; j < NNN ; j++) {
-aaa[j] = j*NNN;
+void teams_targetteams_with_loop() {
+  #pragma omp target teams
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(teams)
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
   }
 }
 
-void orphan_loop_no_bind() {
-  #pragma omp loop  // expected-error{{expected 'bind' clause for 'loop' construct 

[PATCH] D86828: [windows-itanium] make dllimport/export handling closer to MS behavior

2020-10-09 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbb148ad426f8: [windows-itanium] make dllimport/export 
handling closer to MS behavior (authored by Ben Dunbobbin 
).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86828

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/Sema/dllimport.c
  clang/test/SemaCXX/dllexport.cpp
  clang/test/SemaCXX/dllimport.cpp

Index: clang/test/SemaCXX/dllimport.cpp
===
--- clang/test/SemaCXX/dllimport.cpp
+++ clang/test/SemaCXX/dllimport.cpp
@@ -1,8 +1,10 @@
-// RUN: %clang_cc1 -triple i686-win32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DMS %s
-// RUN: %clang_cc1 -triple x86_64-win32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DMS %s
-// RUN: %clang_cc1 -triple i686-mingw32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DGNU %s
-// RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DGNU %s
-// RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++17 -Wunsupported-dll-base-class-template -DGNU %s
+// RUN: %clang_cc1 -triple i686-win32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DMS %s
+// RUN: %clang_cc1 -triple x86_64-win32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DMS %s
+// RUN: %clang_cc1 -triple i686-mingw32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DGNU %s
+// RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DGNU %s
+// RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++17 -Wunsupported-dll-base-class-template -DGNU %s
+// RUN: %clang_cc1 -triple i686-windows-itanium   -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI %s
+// RUN: %clang_cc1 -triple x86_64-windows-itanium -fsyntax-only -fms-extensions -verify -std=c++17 -Wunsupported-dll-base-class-template -DWI %s
 
 // Helper structs to make templates more expressive.
 struct ImplicitInst_Imported {};
@@ -55,7 +57,7 @@
 // expected-note@+2{{previous attribute is here}}
 #endif
 __declspec(dllimport) extern int ExternGlobalDeclInit; // expected-note{{previous declaration is here}}
-#ifdef MS
+#if defined(MS) || defined(WI)
 // expected-warning@+4{{'ExternGlobalDeclInit' redeclared without 'dllimport' attribute: 'dllexport' attribute added}}
 #else
 // expected-warning@+2{{'ExternGlobalDeclInit' redeclared without 'dllimport' attribute: previous 'dllimport' ignored}}
@@ -66,7 +68,7 @@
 // expected-note@+2{{previous attribute is here}}
 #endif
 __declspec(dllimport) int GlobalDeclInit; // expected-note{{previous declaration is here}}
-#ifdef MS
+#if defined(MS) || defined(WI)
 // expected-warning@+4{{'GlobalDeclInit' redeclared without 'dllimport' attribute: 'dllexport' attribute added}}
 #else
 // expected-warning@+2{{'GlobalDeclInit' redeclared without 'dllimport' attribute: previous 'dllimport' ignored}}
@@ -77,7 +79,7 @@
 // expected-note@+2{{previous attribute is here}}
 #endif
 int *__attribute__((dllimport)) GlobalDeclChunkAttrInit; // expected-note{{previous declaration is here}}
-#ifdef MS
+#if defined(MS) || defined(WI)
 // expected-warning@+4{{'GlobalDeclChunkAttrInit' redeclared without 'dllimport' attribute: 'dllexport' attribute added}}
 #else
 // expected-warning@+2{{'GlobalDeclChunkAttrInit' redeclared without 'dllimport' attribute: previous 'dllimport' ignored}}
@@ -88,7 +90,7 @@
 // expected-note@+2{{previous attribute is here}}
 #endif
 int GlobalDeclAttrInit __attribute__((dllimport)); // expected-note{{previous declaration is here}}
-#ifdef MS
+#if defined(MS) || defined(WI)
 // expected-warning@+4{{'GlobalDeclAttrInit' redeclared without 'dllimport' attribute: 'dllexport' attribute added}}
 #else
 // expected-warning@+2{{'GlobalDeclAttrInit' redeclared without 'dllimport' attribute: previous 'dllimport' ignored}}
@@ -179,7 +181,7 @@
 #endif
 template 
 __declspec(dllimport) extern int ExternVarTmplDeclInit; // expected-note{{previous declaration is here}}
-#ifdef MS
+#if defined(MS) || defined(WI)
 // expected-warning@+5{{'ExternVarTmplDeclInit' redeclared without 'dllimport' attribute: 'dllexport' attribute added}}
 #else
 // expected-warning@+3{{'ExternVarTmplDeclInit' redeclared without 'dllimport' attribute: previous 'dllimport' ignored}}
@@ -192,7 +194,7 @@
 #endif
 template 

[PATCH] D89025: [RISCV] Add -mtune support

2020-10-15 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcfa7094e49cf: [RISCV] Add -mtune support (authored by Kito 
Cheng ).
Herald added a subscriber: NickHung.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89025

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/RISCV.cpp
  clang/lib/Basic/Targets/RISCV.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/riscv-cpus.c
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/RISCVTargetParser.def
  llvm/include/llvm/Support/TargetParser.h
  llvm/lib/Support/TargetParser.cpp
  llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
  llvm/lib/Target/RISCV/RISCVSubtarget.cpp
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/lib/Target/RISCV/RISCVTargetMachine.cpp

Index: llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
===
--- llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
+++ llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
@@ -75,13 +75,16 @@
 const RISCVSubtarget *
 RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
   Attribute CPUAttr = F.getFnAttribute("target-cpu");
+  Attribute TuneAttr = F.getFnAttribute("tune-cpu");
   Attribute FSAttr = F.getFnAttribute("target-features");
 
   std::string CPU =
   CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
+  std::string TuneCPU =
+  TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
   std::string FS =
   FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
-  std::string Key = CPU + FS;
+  std::string Key = CPU + TuneCPU + FS;
   auto &I = SubtargetMap[Key];
   if (!I) {
 // This needs to be done before we create a new subtarget since any
@@ -98,7 +101,7 @@
   }
   ABIName = ModuleTargetABI->getString();
 }
-I = std::make_unique(TargetTriple, CPU, FS, ABIName, *this);
+I = std::make_unique(TargetTriple, CPU, TuneCPU, FS, ABIName, *this);
   }
   return I.get();
 }
Index: llvm/lib/Target/RISCV/RISCVSubtarget.h
===
--- llvm/lib/Target/RISCV/RISCVSubtarget.h
+++ llvm/lib/Target/RISCV/RISCVSubtarget.h
@@ -71,13 +71,15 @@
   /// Initializes using the passed in CPU and feature strings so that we can
   /// use initializer lists for subtarget initialization.
   RISCVSubtarget &initializeSubtargetDependencies(const Triple &TT,
-  StringRef CPU, StringRef FS,
+  StringRef CPU,
+  StringRef TuneCPU,
+  StringRef FS,
   StringRef ABIName);
 
 public:
   // Initializes the data members to match that of the specified triple.
-  RISCVSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
- StringRef ABIName, const TargetMachine &TM);
+  RISCVSubtarget(const Triple &TT, StringRef CPU, StringRef TuneCPU,
+ StringRef FS, StringRef ABIName, const TargetMachine &TM);
 
   // Parses features string setting specified subtarget options. The
   // definition of this function is auto-generated by tblgen.
Index: llvm/lib/Target/RISCV/RISCVSubtarget.cpp
===
--- llvm/lib/Target/RISCV/RISCVSubtarget.cpp
+++ llvm/lib/Target/RISCV/RISCVSubtarget.cpp
@@ -30,13 +30,16 @@
 void RISCVSubtarget::anchor() {}
 
 RISCVSubtarget &RISCVSubtarget::initializeSubtargetDependencies(
-const Triple &TT, StringRef CPU, StringRef FS, StringRef ABIName) {
+const Triple &TT, StringRef CPU, StringRef TuneCPU, StringRef FS, StringRef ABIName) {
   // Determine default and user-specified characteristics
   bool Is64Bit = TT.isArch64Bit();
   std::string CPUName = std::string(CPU);
+  std::string TuneCPUName = std::string(TuneCPU);
   if (CPUName.empty())
 CPUName = Is64Bit ? "generic-rv64" : "generic-rv32";
-  ParseSubtargetFeatures(CPUName, /*TuneCPU*/ CPUName, FS);
+  if (TuneCPUName.empty())
+TuneCPUName = CPUName;
+  ParseSubtargetFeatures(CPUName, TuneCPUName, FS);
   if (Is64Bit) {
 XLenVT = MVT::i64;
 XLen = 64;
@@ -47,11 +50,12 @@
   return *this;
 }
 
-RISCVSubtarget::RISCVSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
+RISCVSubtarget::RISCVSubtarget(const Triple &TT, StringRef CPU,
+   StringRef TuneCPU, StringRef FS,
StringRef ABIName, const TargetMachine &TM)
-: RISCVGenSubtargetInfo(TT, CPU, /*TuneCPU*/ CPU, FS),
+: RISCVGenSubtargetInfo(TT, CPU, TuneCPU, FS),
   UserReservedRegister(RISCV::NUM_TARGET_REGS),
-  FrameLowering(initializeSubtargetDependencies(TT, CPU, FS, ABIName)),
+  FrameLowering(initializeSubtargetDependenci

[PATCH] D91779: [Clang][-fvisibility-from-dllstorageclass] Set DSO Locality from final visibility

2020-11-23 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe42021d5cc25: [Clang][-fvisibility-from-dllstorageclass] Set 
DSO Locality from final… (authored by Ben Dunbobbin 
).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91779

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenCXX/visibility-dllstorageclass.cpp

Index: clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
===
--- clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
+++ clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
@@ -5,12 +5,14 @@
 
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-itanium -fdeclspec \
 // RUN: -fvisibility hidden \
+// RUN: -fapply-global-visibility-to-externs \
 // RUN: -fvisibility-from-dllstorageclass \
 // RUN: -x c++ %s -S -emit-llvm -o - | \
-// RUN:   FileCheck %s --check-prefixes=DEFAULT
+// RUN:   FileCheck %s --check-prefixes=DEFAULTS
 
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-itanium -fdeclspec \
 // RUN: -fvisibility hidden \
+// RUN: -fapply-global-visibility-to-externs \
 // RUN: -fvisibility-from-dllstorageclass \
 // RUN: -fvisibility-dllexport=hidden \
 // RUN: -fvisibility-nodllstorageclass=protected \
@@ -19,45 +21,78 @@
 // RUN: -x c++  %s -S -emit-llvm -o - | \
 // RUN:   FileCheck %s --check-prefixes=EXPLICIT
 
+// RUN: %clang_cc1 -triple x86_64-unknown-windows-itanium -fdeclspec \
+// RUN: -fvisibility hidden \
+// RUN: -fapply-global-visibility-to-externs \
+// RUN: -fvisibility-from-dllstorageclass \
+// RUN: -fvisibility-dllexport=default \
+// RUN: -fvisibility-nodllstorageclass=default \
+// RUN: -fvisibility-externs-dllimport=default \
+// RUN: -fvisibility-externs-nodllstorageclass=default \
+// RUN: -x c++  %s -S -emit-llvm -o - | \
+// RUN:   FileCheck %s --check-prefixes=ALL_DEFAULT
+
 // Local
 static void l() {}
 void use_locals(){l();}
-// DEFAULT-DAG: define internal void @_ZL1lv()
+// DEFAULTS-DAG: define internal void @_ZL1lv()
 // EXPLICIT-DAG: define internal void @_ZL1lv()
+// ALL_DEFAULT-DAG: define internal void @_ZL1lv()
 
 // Function
 void f() {}
 void __declspec(dllexport) exported_f() {}
-// DEFAULT-DAG: define hidden void @_Z1fv()
-// DEFAULT-DAG: define dso_local void @_Z10exported_fv()
+// DEFAULTS-DAG: define hidden void @_Z1fv()
+// DEFAULTS-DAG: define void @_Z10exported_fv()
 // EXPLICIT-DAG: define protected void @_Z1fv()
 // EXPLICIT-DAG: define hidden void @_Z10exported_fv()
+// ALL_DEFAULT-DAG: define void @_Z1fv()
+// ALL_DEFAULT-DAG: define void @_Z10exported_fv()
 
 // Variable
 int d = 123;
 __declspec(dllexport) int exported_d = 123;
-// DEFAULT-DAG: @d = hidden global
-// DEFAULT-DAG: @exported_d = dso_local global
+// DEFAULTS-DAG: @d = hidden global
+// DEFAULTS-DAG: @exported_d = global
 // EXPLICIT-DAG: @d = protected global
 // EXPLICIT-DAG: @exported_d = hidden global
+// ALL_DEFAULT-DAG: @d = global
+// ALL_DEFAULT-DAG: @exported_d = global
 
 // Alias
 extern "C" void aliased() {}
 void a() __attribute__((alias("aliased")));
 void __declspec(dllexport) a_exported() __attribute__((alias("aliased")));
-// DEFAULT-DAG: @_Z1av = hidden alias
-// DEFAULT-DAG: @_Z10a_exportedv = dso_local alias
+// DEFAULTS-DAG: @_Z1av = hidden alias
+// DEFAULTS-DAG: @_Z10a_exportedv = alias
 // EXPLICIT-DAG: @_Z1av = protected alias
 // EXPLICIT-DAG: @_Z10a_exportedv = hidden alias
+// ALL_DEFAULT-DAG: @_Z1av = alias
+// ALL_DEFAULT-DAG: @_Z10a_exportedv = alias
 
 // Declaration
 extern void e();
 extern void __declspec(dllimport) imported_e();
-void use_declarations(){e(); imported_e();}
-// DEFAULT-DAG: declare hidden void @_Z1ev()
-// DEFAULT-DAG: declare void @_Z10imported_ev()
+// DEFAULTS-DAG: declare hidden void @_Z1ev()
+// DEFAULTS-DAG: declare void @_Z10imported_ev()
 // EXPLICIT-DAG: declare protected void @_Z1ev()
 // EXPLICIT-DAG: declare hidden void @_Z10imported_ev()
+// ALL_DEFAULT-DAG: declare void @_Z1ev()
+// ALL_DEFAULT-DAG: declare void @_Z10imported_ev()
+
+// Weak Declaration
+__attribute__((weak))
+extern void w();
+__attribute__((weak))
+extern void __declspec(dllimport) imported_w();
+// DEFAULTS-DAG: declare extern_weak hidden void @_Z1wv()
+// DEFAULTS-DAG: declare extern_weak void @_Z10imported_wv()
+// EXPLICIT-DAG: declare extern_weak protected void @_Z1wv()
+// EXPLICIT-DAG: declare extern_weak hidden void @_Z10imported_wv()
+// ALL_DEFAULT-DAG: declare extern_weak void @_Z1wv()
+// ALL_DEFAULT-DAG: declare extern_weak void @_Z10imported_wv()
+
+void use_declarations(){e(); imported_e(); w(); imported_w();}
 
 // Show that -fvisibility-from-dllstorageclass overrides the effect of visibility annotations.
 
@@ -65,12 +100,12 @@
   virtual void foo();
 };
 void 

[PATCH] D90299: [windows-itanium] handle dllimport/export code paths separately and share with PS4

2020-11-30 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd5aaf6021476: [windows-itanium] handle dllimport/export code 
paths separately and share with… (authored by Ben Dunbobbin 
).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90299

Files:
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/CodeGenCXX/dllexport-vtable-thunks.cpp
  clang/test/CodeGenCXX/windows-implicit-dllexport-template-specialization.cpp
  clang/test/CodeGenCXX/windows-itanium-dllexport.cpp
  clang/test/Sema/dllimport.c
  clang/test/SemaCXX/dllexport.cpp
  clang/test/SemaCXX/dllimport.cpp

Index: clang/test/SemaCXX/dllimport.cpp
===
--- clang/test/SemaCXX/dllimport.cpp
+++ clang/test/SemaCXX/dllimport.cpp
@@ -5,6 +5,8 @@
 // RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++17 -Wunsupported-dll-base-class-template -DGNU %s
 // RUN: %clang_cc1 -triple i686-windows-itanium   -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI %s
 // RUN: %clang_cc1 -triple x86_64-windows-itanium -fsyntax-only -fms-extensions -verify -std=c++17 -Wunsupported-dll-base-class-template -DWI %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fdeclspec  -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fdeclspec  -verify -std=c++17 -Wunsupported-dll-base-class-template -DWI %s
 
 // Helper structs to make templates more expressive.
 struct ImplicitInst_Imported {};
Index: clang/test/SemaCXX/dllexport.cpp
===
--- clang/test/SemaCXX/dllexport.cpp
+++ clang/test/SemaCXX/dllexport.cpp
@@ -4,6 +4,7 @@
 // RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template %s
 // RUN: %clang_cc1 -triple i686-windows-itanium   -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI %s
 // RUN: %clang_cc1 -triple x86_64-windows-itanium -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DWI %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fdeclspec  -verify -std=c++1y -Wunsupported-dll-base-class-template -DWI %s
 
 // Helper structs to make templates more expressive.
 struct ImplicitInst_Exported {};
Index: clang/test/Sema/dllimport.c
===
--- clang/test/Sema/dllimport.c
+++ clang/test/Sema/dllimport.c
@@ -5,6 +5,8 @@
 // RUN: %clang_cc1 -triple aarch64-win32  -fsyntax-only -fms-extensions -verify -std=c99 -DMS %s
 // RUN: %clang_cc1 -triple i686-windows-itanium   -fsyntax-only -fms-extensions -verify -std=c99 -DWI %s
 // RUN: %clang_cc1 -triple x86_64-windows-itanium -fsyntax-only -fms-extensions -verify -std=c11 -DWI %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fms-extensions -verify -std=c11 -DWI %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fms-extensions -verify -std=c99 -DWI %s
 
 // Invalid usage.
 __declspec(dllimport) typedef int typedef1;
Index: clang/test/CodeGenCXX/windows-itanium-dllexport.cpp
===
--- clang/test/CodeGenCXX/windows-itanium-dllexport.cpp
+++ clang/test/CodeGenCXX/windows-itanium-dllexport.cpp
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -emit-llvm -triple i686-windows-itanium -fdeclspec %s -o - | FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -triple i686-windows-itanium -fdeclspec %s -o - | FileCheck %s --check-prefixes=CHECK,WI
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps4 -fdeclspec %s -o - | FileCheck %s --check-prefixes=CHECK,PS4
 
 #define JOIN2(x, y) x##y
 #define JOIN(x, y) JOIN2(x, y)
@@ -25,14 +26,18 @@
 extern template class c;
 template class __declspec(dllexport) c;
 
-// CHECK: define {{.*}} dllexport {{.*}} @_ZN1cIcEaSERKS0_
-// CHECK: define {{.*}} dllexport {{.*}} @_ZN1cIcE1fEv
+// WI: define {{.*}} dllexport {{.*}} @_ZN1cIcEaSERKS0_
+// WI: define {{.*}} dllexport {{.*}} @_ZN1cIcE1fEv
+// PS4-NOT: @_ZN1cIcEaSERKS0_
+// PS4: define weak_odr void @_ZN1cIcE1fEv
 
 c g;
 template class __declspec(dllexport) c;
 
-// CHECK: define {{.*}} dllexport {{.*}} @_ZN1cIdEaSERKS0_
-// CHECK: define {{.*}} dllexport {{.*}} @_ZN1cIdE1fEv
+// WI: define {{.*}} dllexport {{.*}} @_ZN1cIdEaSERKS0_
+// WI: define {{.*}} dllexport {{.*}} @_ZN1cIdE1fEv
+// PS4-NOT: @_ZN1cIdEaSERKS0_
+// PS4: define weak_odr void @_ZN1cIdE1fEv
 
 template 
 struct outer {

[PATCH] D83448: [CodeGen] Emit destructor calls to destruct non-trivial C struct temporaries created by conditional and assignment operators

2020-10-23 Thread 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 rG71e1a56de153: [CodeGen] Emit destructor calls to destruct 
non-trivial C struct (authored by ahatanak, committed by --local 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83448

Files:
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/test/CodeGenObjC/strong-in-c-struct.m

Index: clang/test/CodeGenObjC/strong-in-c-struct.m
===
--- clang/test/CodeGenObjC/strong-in-c-struct.m
+++ clang/test/CodeGenObjC/strong-in-c-struct.m
@@ -95,12 +95,13 @@
 @end
 
 id g0;
+StrongSmall g1, g2;
 
+// CHECK: %[[STRUCT_STRONGSMALL:.*]] = type { i32, i8* }
 // CHECK: %[[STRUCT_STRONGOUTER:.*]] = type { %[[STRUCT_STRONG:.*]], i8*, double }
 // CHECK: %[[STRUCT_STRONG]] = type { %[[STRUCT_TRIVIAL:.*]], i8* }
 // CHECK: %[[STRUCT_TRIVIAL]] = type { [4 x i32] }
 // CHECK: %[[STRUCT_BLOCK_BYREF_T:.*]] = type { i8*, %[[STRUCT_BLOCK_BYREF_T]]*, i32, i32, i8*, i8*, i8*, %[[STRUCT_STRONGOUTER]] }
-// CHECK: %[[STRUCT_STRONGSMALL:.*]] = type { i32, i8* }
 // CHECK: %[[STRUCT_STRONGBLOCK:.*]] = type { void ()* }
 // CHECK: %[[STRUCT_BITFIELD1:.*]] = type { i8, i8, i8*, i32, i8*, [3 x i32], i8*, double, i8, i8 }
 
@@ -900,4 +901,47 @@
   a = b;
 }
 
+// CHECK-LABEL: define i8* @test_conditional0(
+// CHECK: %[[TMP:.*]] = alloca %[[STRUCT_STRONGSMALL]], align 8
+
+// CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGSMALL]]* %[[TMP]] to i8**
+// CHECK: call void @__copy_constructor_8_8_t0w4_s8(i8** %[[V1]], i8** bitcast (%[[STRUCT_STRONGSMALL]]* @g2 to i8**))
+
+// CHECK: %[[V2:.*]] = bitcast %[[STRUCT_STRONGSMALL]]* %[[TMP]] to i8**
+// CHECK: call void @__copy_constructor_8_8_t0w4_s8(i8** %[[V2]], i8** bitcast (%[[STRUCT_STRONGSMALL]]* @g1 to i8**))
+
+// CHECK: %[[V5:.*]] = bitcast %[[STRUCT_STRONGSMALL]]* %[[TMP]] to i8**
+// CHECK: call void @__destructor_8_s8(i8** %[[V5]])
+// CHECK: @llvm.objc.autoreleaseReturnValue
+
+id test_conditional0(int c) {
+  return (c ? g2 : g1).f1;
+}
+
+// CHECK-LABEL: define i8* @test_conditional1(
+// CHECK-NOT: call void @__destructor
+
+id test_conditional1(int c) {
+  calleeStrongSmall(c ? g2 : g1);
+}
+
+// CHECK-LABEL: define i8* @test_assignment0(
+// CHECK: %[[TMP:.*]] = alloca %[[STRUCT_STRONGSMALL]], align 8
+// CHECK: call void @__copy_assignment_8_8_t0w4_s8(i8** bitcast (%[[STRUCT_STRONGSMALL]]* @g2 to i8**), i8** bitcast (%[[STRUCT_STRONGSMALL]]* @g1 to i8**))
+// CHECK: %[[V0:.*]] = bitcast %[[STRUCT_STRONGSMALL]]* %[[TMP]] to i8**
+// CHECK: call void @__copy_constructor_8_8_t0w4_s8(i8** %[[V0]], i8** bitcast (%[[STRUCT_STRONGSMALL]]* @g2 to i8**))
+// CHECK: %[[V3:.*]] = bitcast %[[STRUCT_STRONGSMALL]]* %[[TMP]] to i8**
+// CHECK: call void @__destructor_8_s8(i8** %[[V3]])
+
+id test_assignment0(void) {
+  return (g2 = g1).f1;
+}
+
+// CHECK-LABEL: define i8* @test_assignment1(
+// CHECK-NOT: call void @__destructor
+
+id test_assignment1(void) {
+  calleeStrongSmall(g2 = g1);
+}
+
 #endif /* USESTRUCT */
Index: clang/lib/CodeGen/CGExprAgg.cpp
===
--- clang/lib/CodeGen/CGExprAgg.cpp
+++ clang/lib/CodeGen/CGExprAgg.cpp
@@ -1216,6 +1216,11 @@
 
   // Copy into the destination if the assignment isn't ignored.
   EmitFinalDestCopy(E->getType(), LHS);
+
+  if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
+  E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
+CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
+E->getType());
 }
 
 void AggExprEmitter::
@@ -1233,6 +1238,11 @@
 
   // Save whether the destination's lifetime is externally managed.
   bool isExternallyDestructed = Dest.isExternallyDestructed();
+  bool destructNonTrivialCStruct =
+  !isExternallyDestructed &&
+  E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
+  isExternallyDestructed |= destructNonTrivialCStruct;
+  Dest.setExternallyDestructed(isExternallyDestructed);
 
   eval.begin(CGF);
   CGF.EmitBlock(LHSBlock);
@@ -1254,6 +1264,10 @@
   Visit(E->getFalseExpr());
   eval.end(CGF);
 
+  if (destructNonTrivialCStruct)
+CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
+E->getType());
+
   CGF.EmitBlock(ContBlock);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D90442: [PS4] Support dllimport/export attributes

2020-11-02 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGff2e24a741e4: [PS4] Support dllimport/export attributes 
(authored by Ben Dunbobbin ).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90442

Files:
  clang/include/clang/Basic/Attr.td
  clang/test/CodeGen/ps4-dllimport-dllexport.c
  llvm/include/llvm/ADT/Triple.h

Index: llvm/include/llvm/ADT/Triple.h
===
--- llvm/include/llvm/ADT/Triple.h
+++ llvm/include/llvm/ADT/Triple.h
@@ -782,6 +782,9 @@
 return isOSBinFormatXCOFF() || isWasm();
   }
 
+  /// Tests if the environment supports dllimport/export annotations.
+  bool hasDLLImportExport() const { return isOSWindows() || isPS4CPU(); }
+
   /// @}
   /// @name Mutators
   /// @{
Index: clang/test/CodeGen/ps4-dllimport-dllexport.c
===
--- /dev/null
+++ clang/test/CodeGen/ps4-dllimport-dllexport.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 \
+// RUN: -triple x86_64-scei-ps4 \
+// RUN: -fdeclspec \
+// RUN: -Werror \
+// RUN: -emit-llvm %s -o - | \
+// RUN:   FileCheck %s
+
+__declspec(dllexport) int export_int;
+
+__declspec(dllimport) int import_int;
+
+__declspec(dllexport) void export_declared_function();
+
+__declspec(dllexport) void export_implemented_function() {
+}
+
+__declspec(dllimport) void import_function(int);
+
+void call_imported_function() {
+  export_declared_function();
+  return import_function(import_int);
+}
+
+// CHECK-DAG: @import_int = external dllimport
+// CHECK-DAG: @export_int = dllexport global i32 0
+// CHECK-DAG: define dllexport void @export_implemented_function()
+// CHECK-DAG: declare dllimport void @import_function(i32)
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -368,8 +368,8 @@
 def TargetX86 : TargetArch<["x86"]>;
 def TargetAnyX86 : TargetArch<["x86", "x86_64"]>;
 def TargetWebAssembly : TargetArch<["wasm32", "wasm64"]>;
-def TargetWindows : TargetArch<["x86", "x86_64", "arm", "thumb", "aarch64"]> {
-  let OSes = ["Win32"];
+def TargetHasDLLImportExport : TargetSpec {
+  let CustomCode = [{ Target.getTriple().hasDLLImportExport() }];
 }
 def TargetItaniumCXXABI : TargetSpec {
   let CustomCode = [{ Target.getCXXABI().isItaniumFamily() }];
@@ -3144,24 +3144,24 @@
   let SimpleHandler = 1;
 }
 
-def DLLExport : InheritableAttr, TargetSpecificAttr {
+def DLLExport : InheritableAttr, TargetSpecificAttr {
   let Spellings = [Declspec<"dllexport">, GCC<"dllexport">];
   let Subjects = SubjectList<[Function, Var, CXXRecord, ObjCInterface]>;
   let Documentation = [DLLExportDocs];
 }
 
-def DLLExportStaticLocal : InheritableAttr, TargetSpecificAttr {
+def DLLExportStaticLocal : InheritableAttr, TargetSpecificAttr {
   // This attribute is used internally only when -fno-dllexport-inlines is
-  // passed. This attribute is added to inline function of class having
-  // dllexport attribute. And if the function has static local variables, this
-  // attribute is used to whether the variables are exported or not. Also if
-  // function has local static variables, the function is dllexported too.
+  // passed. This attribute is added to inline functions of a class having the
+  // dllexport attribute. If the function has static local variables, this
+  // attribute is used to determine whether the variables are exported or not. If
+  // the function has local static variables, the function is dllexported too.
   let Spellings = [];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [Undocumented];
 }
 
-def DLLImport : InheritableAttr, TargetSpecificAttr {
+def DLLImport : InheritableAttr, TargetSpecificAttr {
   let Spellings = [Declspec<"dllimport">, GCC<"dllimport">];
   let Subjects = SubjectList<[Function, Var, CXXRecord, ObjCInterface]>;
   let Documentation = [DLLImportDocs];
@@ -3177,11 +3177,11 @@
   }];
 }
 
-def DLLImportStaticLocal : InheritableAttr, TargetSpecificAttr {
+def DLLImportStaticLocal : InheritableAttr, TargetSpecificAttr {
   // This attribute is used internally only when -fno-dllexport-inlines is
-  // passed. This attribute is added to inline function of class having
-  // dllimport attribute. And if the function has static local variables, this
-  // attribute is used to whether the variables are imported or not.
+  // passed. This attribute is added to inline functions of a class having the
+  // dllimport attribute. If the function has static local variables, this
+  // attribute is used to determine whether the variables are imported or not.
   let Spellings = [];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [Undocumente

[PATCH] D89970: Add the ability to map DLL storage class to visibility

2020-11-02 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG415f7ee88369: [Clang] Add the ability to map DLL storage 
class to visibility (authored by Ben Dunbobbin ).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D89970?vs=301803&id=302305#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89970

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/PS4CPU.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
  clang/test/Driver/ps4-visibility-dllstorageclass.c
  clang/test/Driver/visibility-dllstorageclass.c

Index: clang/test/Driver/visibility-dllstorageclass.c
===
--- /dev/null
+++ clang/test/Driver/visibility-dllstorageclass.c
@@ -0,0 +1,87 @@
+// Check behaviour of -fvisibility-from-dllstorageclass options
+
+// RUN: %clang -target x86_64-unknown-windows-itanium -fdeclspec \
+// RUN: -Werror -S -### %s 2>&1 | \
+// RUN:   FileCheck %s \
+// RUN: --implicit-check-not=-fvisibility-from-dllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-dllexport \
+// RUN: --implicit-check-not=-fvisibility-nodllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-externs-dllimport \
+// RUN: --implicit-check-not=-fvisibility-externs-nodllstorageclass
+
+// RUN: %clang -target x86_64-unknown-windows-itanium -fdeclspec \
+// RUN: -fvisibility-from-dllstorageclass \
+// RUN: -fno-visibility-from-dllstorageclass \
+// RUN: -Werror -S -### %s 2>&1 | \
+// RUN:   FileCheck %s \
+// RUN: --implicit-check-not=-fvisibility-from-dllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-dllexport \
+// RUN: --implicit-check-not=-fvisibility-nodllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-externs-dllimport \
+// RUN: --implicit-check-not=-fvisibility-externs-nodllstorageclass
+
+// RUN: %clang -target x86_64-unknown-windows-itanium -fdeclspec \
+// RUN: -fno-visibility-from-dllstorageclass \
+// RUN: -fvisibility-from-dllstorageclass \
+// RUN: -Werror -S -### %s 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=SET \
+// RUN: --implicit-check-not=-fvisibility-from-dllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-dllexport \
+// RUN: --implicit-check-not=-fvisibility-nodllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-externs-dllimport \
+// RUN: --implicit-check-not=-fvisibility-externs-nodllstorageclass
+
+// RUN: %clang -target x86_64-unknown-windows-itanium -fdeclspec \
+// RUN: -fvisibility-dllexport=hidden \
+// RUN: -fvisibility-nodllstorageclass=protected \
+// RUN: -fvisibility-externs-dllimport=hidden \
+// RUN: -fvisibility-externs-nodllstorageclass=protected \
+// RUN: -S -### %s 2>&1 | \
+// RUN:   FileCheck %s --check-prefixes=UNUSED \
+// RUN: --implicit-check-not=-fvisibility-from-dllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-dllexport \
+// RUN: --implicit-check-not=-fvisibility-nodllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-externs-dllimport \
+// RUN: --implicit-check-not=-fvisibility-externs-nodllstorageclass \
+// RUN: --implicit-check-not=error: \
+// RUN: --implicit-check-not=warning:
+
+// RUN: %clang -target x86_64-unknown-windows-itanium -fdeclspec \
+// RUN: -fno-visibility-from-dllstorageclass \
+// RUN: -fvisibility-dllexport=hidden \
+// RUN: -fvisibility-nodllstorageclass=protected \
+// RUN: -fvisibility-externs-dllimport=hidden \
+// RUN: -fvisibility-externs-nodllstorageclass=protected \
+// RUN: -S -### %s 2>&1 | \
+// RUN:   FileCheck %s --check-prefixes=UNUSED \
+// RUN: --implicit-check-not=-fvisibility-from-dllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-dllexport \
+// RUN: --implicit-check-not=-fvisibility-nodllstorageclass \
+// RUN: --implicit-check-not=-fvisibility-externs-dllimport \
+// RUN: --implicit-check-not=-fvisibility-externs-nodllstorageclass \
+// RUN: --implicit-check-not=error: \
+// RUN: --implicit-check-not=warning:
+
+// UNUSED:  clang: warning: argument unused during compilation: '-fvisibility-dllexport=hidden'
+// UNUSED-NEXT: clang: warning: argument unused during compilation: '-fvisibility-nodllstorageclass=protected'
+// UNUSED-NEXT: clang: warning: argument unused during compilation: '-fvisibility-externs-dllimport=hidden'
+// UNUSED-NEXT: clang: warning: argument unused during compilation: '-fvisibility-externs-nodllstorageclass=protected'
+
+// RUN: %clang -target x86_64-unknown-windows-itanium -fdeclspec \
+//

[PATCH] D71714: [Sema] Fix -Warray-bounds false negative when casting an out-of-bounds array item

2021-02-03 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe48f444751cf: [Sema] Fix -Warray-bounds false negative when 
casting an out-of-bounds array… (authored by ilya, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71714

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Parser/cxx-ambig-decl-expr.cpp
  clang/test/SemaCXX/array-bounds.cpp

Index: clang/test/SemaCXX/array-bounds.cpp
===
--- clang/test/SemaCXX/array-bounds.cpp
+++ clang/test/SemaCXX/array-bounds.cpp
@@ -27,7 +27,7 @@
 };
 
 void f1(int a[1]) {
-  int val = a[3]; // no warning for function argumnet
+  int val = a[3]; // no warning for function argument
 }
 
 void f2(const int (&a)[2]) { // expected-note {{declared here}}
@@ -133,7 +133,7 @@
 
 int test_sizeof_as_condition(int flag) {
   int arr[2] = { 0, 0 }; // expected-note {{array 'arr' declared here}}
-  if (flag) 
+  if (flag)
 return sizeof(char) != sizeof(char) ? arr[2] : arr[1];
   return sizeof(char) == sizeof(char) ? arr[2] : arr[1]; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
 }
@@ -241,7 +241,7 @@
 }
 
 int test_pr11007_aux(const char * restrict, ...);
-  
+
 // Test checking with varargs.
 void test_pr11007() {
   double a[5]; // expected-note {{array 'a' declared here}}
@@ -320,3 +320,33 @@
   arr[1] = 0; // expected-warning {{array index 1 is past the end of the array (which contains 1 element)}}
 }
 } // namespace var_template_array
+
+namespace PR44343 {
+  const unsigned int array[2] = {0, 1}; // expected-note 5{{array 'array' declared here}}
+
+  const int i1 = (const int)array[2]; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  const int i2 = static_cast(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  const int &i3 = reinterpret_cast(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  unsigned int &i4 = const_cast(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  int i5 = int(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  const unsigned int *i6 = &(1 > 0 ? array[2] : array[1]); // no warning for one-past-end element's address retrieval
+
+  // Test dynamic cast
+  struct Base {
+virtual ~Base();
+  };
+  struct Derived : Base {
+  };
+  Base baseArr[2]; // expected-note {{array 'baseArr' declared here}}
+  Derived *d1 = dynamic_cast(&baseArr[2]); // FIXME: Should actually warn because dynamic_cast accesses the vptr
+  Derived &d2 = dynamic_cast(baseArr[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+
+  // Test operator `&` in combination with operators `.` and `->`
+  struct A {
+int n;
+  };
+  A a[2]; // expected-note {{array 'a' declared here}}
+  int *n = &a[2].n; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  A *aPtr[2]; // expected-note {{array 'aPtr' declared here}}
+  int *n2 = &aPtr[2]->n; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+}
Index: clang/test/Parser/cxx-ambig-decl-expr.cpp
===
--- clang/test/Parser/cxx-ambig-decl-expr.cpp
+++ clang/test/Parser/cxx-ambig-decl-expr.cpp
@@ -24,7 +24,7 @@
 
   // This is array indexing not an array declarator because a comma expression
   // is not syntactically a constant-expression.
-  int(x[1,1]); // expected-warning 2{{unused}}
+  int(x[1,0]); // expected-warning 2{{unused}}
 
   // This is array indexing not an array declaration because a braced-init-list
   // is not syntactically a constant-expression.
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14387,62 +14387,63 @@
 PDiag(diag::note_array_declared_here) << ND);
 }
 
-void Sema::CheckArrayAccess(const Expr *expr) {
-  int AllowOnePastEnd = 0;
-  while (expr) {
-expr = expr->IgnoreParenImpCasts();
-switch (expr->getStmtClass()) {
-  case Stmt::ArraySubscriptExprClass: {
-const ArraySubscriptExpr *ASE = cast(expr);
-CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
- AllowOnePastEnd > 0);
-expr = ASE->getBase();
-break;
-  }
-  case Stmt::MemberExprClass: {
-expr = cast(expr)->getBase();
-break;
-  }
-  case Stmt::OMPArraySectionExprClass: {
-const OMPArraySection

[PATCH] D93222: [analyzer] Introduce MacroExpansionContext to libAnalysis

2021-02-22 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6e3071007b4c: [analyzer] Introduce MacroExpansionContext to 
libAnalysis (authored by steakhal, committed by Balazs Benics 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93222

Files:
  clang/include/clang/Analysis/MacroExpansionContext.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/MacroExpansionContext.cpp
  clang/unittests/Analysis/CMakeLists.txt
  clang/unittests/Analysis/MacroExpansionContextTest.cpp

Index: clang/unittests/Analysis/MacroExpansionContextTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/MacroExpansionContextTest.cpp
@@ -0,0 +1,424 @@
+//===- unittests/Analysis/MacroExpansionContextTest.cpp - -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/MacroExpansionContext.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/TargetOptions.h"
+#include "clang/Lex/HeaderSearch.h"
+#include "clang/Lex/HeaderSearchOptions.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Parse/Parser.h"
+#include "llvm/ADT/SmallString.h"
+#include "gtest/gtest.h"
+
+// static bool HACK_EnableDebugInUnitTest = (::llvm::DebugFlag = true);
+
+namespace clang {
+namespace analysis {
+namespace {
+
+class MacroExpansionContextTest : public ::testing::Test {
+protected:
+  MacroExpansionContextTest()
+  : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
+FileMgr(FileSystemOptions(), InMemoryFileSystem),
+DiagID(new DiagnosticIDs()), DiagOpts(new DiagnosticOptions()),
+Diags(DiagID, DiagOpts.get(), new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions()) {
+TargetOpts->Triple = "x86_64-pc-linux-unknown";
+Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
+LangOpts.CPlusPlus20 = 1; // For __VA_OPT__
+  }
+
+  IntrusiveRefCntPtr InMemoryFileSystem;
+  FileManager FileMgr;
+  IntrusiveRefCntPtr DiagID;
+  IntrusiveRefCntPtr DiagOpts;
+  DiagnosticsEngine Diags;
+  SourceManager SourceMgr;
+  LangOptions LangOpts;
+  std::shared_ptr TargetOpts;
+  IntrusiveRefCntPtr Target;
+
+  std::unique_ptr
+  getMacroExpansionContextFor(StringRef SourceText) {
+std::unique_ptr Buf =
+llvm::MemoryBuffer::getMemBuffer(SourceText);
+SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
+TrivialModuleLoader ModLoader;
+HeaderSearch HeaderInfo(std::make_shared(), SourceMgr,
+Diags, LangOpts, Target.get());
+Preprocessor PP(std::make_shared(), Diags, LangOpts,
+SourceMgr, HeaderInfo, ModLoader,
+/*IILookup =*/nullptr,
+/*OwnsHeaderSearch =*/false);
+
+PP.Initialize(*Target);
+auto Ctx = std::make_unique(LangOpts);
+Ctx->registerForPreprocessor(PP);
+
+// Lex source text.
+PP.EnterMainSourceFile();
+
+while (true) {
+  Token Tok;
+  PP.Lex(Tok);
+  if (Tok.is(tok::eof))
+break;
+}
+
+// Callbacks have been executed at this point.
+return Ctx;
+  }
+
+  /// Returns the expansion location to main file at the given row and column.
+  SourceLocation at(unsigned row, unsigned col) const {
+SourceLocation Loc =
+SourceMgr.translateLineCol(SourceMgr.getMainFileID(), row, col);
+return SourceMgr.getExpansionLoc(Loc);
+  }
+
+  static std::string dumpExpandedTexts(const MacroExpansionContext &Ctx) {
+std::string Buf;
+llvm::raw_string_ostream OS{Buf};
+Ctx.dumpExpandedTextsToStream(OS);
+return OS.str();
+  }
+
+  static std::string dumpExpansionRanges(const MacroExpansionContext &Ctx) {
+std::string Buf;
+llvm::raw_string_ostream OS{Buf};
+Ctx.dumpExpansionRangesToStream(OS);
+return OS.str();
+  }
+};
+
+TEST_F(MacroExpansionContextTest, IgnoresPragmas) {
+  // No-crash during lexing.
+  const auto Ctx = getMacroExpansionContextFor(R"code(
+  _Pragma("pack(push, 1)")
+  _Pragma("pack(pop, 1)")
+  )code");
+  // After preprocessing:
+  // #pragma pack(push, 1)
+  // #pragma pack(pop, 1)
+
+  EXPECT_EQ("\n=== ExpandedTokens ===\n",
+dumpExpandedTexts(*Ctx));
+  EXPECT_EQ("\n=== Expa

[PATCH] D93223: [analyzer] Create MacroExpansionContext member in AnalysisConsumer

2021-02-22 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7c58fb6ba04e: [analyzer] Create MacroExpansionContext member 
in AnalysisConsumer (authored by steakhal, committed by Balazs Benics 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93223

Files:
  clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
  clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -20,6 +20,7 @@
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CallGraph.h"
 #include "clang/Analysis/CodeInjector.h"
+#include "clang/Analysis/MacroExpansionContext.h"
 #include "clang/Analysis/PathDiagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/CrossTU/CrossTranslationUnit.h"
@@ -98,6 +99,8 @@
   /// working with a PCH file.
   SetOfDecls LocalTUDecls;
 
+  MacroExpansionContext MacroExpansions;
+
   // Set of PathDiagnosticConsumers.  Owned by AnalysisManager.
   PathDiagnosticConsumers PathConsumers;
 
@@ -122,7 +125,8 @@
CodeInjector *injector)
   : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
-Plugins(plugins), Injector(injector), CTU(CI) {
+Plugins(plugins), Injector(injector), CTU(CI),
+MacroExpansions(CI.getLangOpts()) {
 DigestAnalyzerOptions();
 if (Opts->PrintStats || Opts->ShouldSerializeStats) {
   AnalyzerTimers = std::make_unique(
@@ -136,6 +140,9 @@
   *AnalyzerTimers);
   llvm::EnableStatistics(/* PrintOnExit= */ false);
 }
+
+if (Opts->ShouldDisplayMacroExpansions)
+  MacroExpansions.registerForPreprocessor(PP);
   }
 
   ~AnalysisConsumer() override {
@@ -150,7 +157,8 @@
   break;
 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)\
   case PD_##NAME:  \
-CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU); \
+CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU,  \
+ MacroExpansions); \
 break;
 #include "clang/StaticAnalyzer/Core/Analyses.def"
 default:
Index: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
@@ -10,6 +10,7 @@
 //
 //===--===//
 
+#include "clang/Analysis/MacroExpansionContext.h"
 #include "clang/Analysis/PathDiagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/Version.h"
@@ -138,8 +139,9 @@
 
 void ento::createTextPathDiagnosticConsumer(
 PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
-const std::string &Prefix, const clang::Preprocessor &PP,
-const cross_tu::CrossTranslationUnitContext &CTU) {
+const std::string &Prefix, const Preprocessor &PP,
+const cross_tu::CrossTranslationUnitContext &CTU,
+const MacroExpansionContext &MacroExpansions) {
   C.emplace_back(new TextDiagnostics(std::move(DiagOpts), PP.getDiagnostics(),
  PP.getLangOpts(),
  /*ShouldDisplayPathNotes=*/true));
@@ -147,8 +149,9 @@
 
 void ento::createTextMinimalPathDiagnosticConsumer(
 PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
-const std::string &Prefix, const clang::Preprocessor &PP,
-const cross_tu::CrossTranslationUnitContext &CTU) {
+const std::string &Prefix, const Preprocessor &PP,
+const cross_tu::CrossTranslationUnitContext &CTU,
+const MacroExpansionContext &MacroExpansions) {
   C.emplace_back(new TextDiagnostics(std::move(DiagOpts), PP.getDiagnostics(),
  PP.getLangOpts(),
  /*ShouldDisplayPathNotes=*/false));
Index: clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
@@ -10,6 +10,7 @@
 //
 //===--===//
 
+#include "clang/Analysis/MacroExpansionContext.h"
 #include "clan

[PATCH] D94673: [analyzer][CTU] API for CTU macro expansions

2021-02-22 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG38b185832e04: [analyzer][CTU] API for CTU macro expansions 
(authored by steakhal, committed by Balazs Benics 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94673

Files:
  clang/include/clang/AST/ASTImporter.h
  clang/include/clang/CrossTU/CrossTranslationUnit.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  clang/test/Analysis/plist-macros-with-expansion-ctu.c
  clang/unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -91,26 +91,6 @@
   *Success = NewFD && NewFD->hasBody() && !OrigFDHasBody;
 
   if (NewFD) {
-// Check GetImportedFromSourceLocation.
-llvm::Optional> SLocResult =
-CTU.getImportedFromSourceLocation(NewFD->getLocation());
-EXPECT_TRUE(SLocResult);
-if (SLocResult) {
-  SourceLocation OrigSLoc = (*SLocResult).first;
-  ASTUnit *OrigUnit = (*SLocResult).second;
-  // OrigUnit is created internally by CTU (is not the
-  // ASTWithDefinition).
-  TranslationUnitDecl *OrigTU =
-  OrigUnit->getASTContext().getTranslationUnitDecl();
-  const FunctionDecl *FDWithDefinition = FindFInTU(OrigTU);
-  EXPECT_TRUE(FDWithDefinition);
-  if (FDWithDefinition) {
-EXPECT_EQ(FDWithDefinition->getName(), "f");
-EXPECT_TRUE(FDWithDefinition->isThisDeclarationADefinition());
-EXPECT_EQ(OrigSLoc, FDWithDefinition->getLocation());
-  }
-}
-
 // Check parent map.
 const DynTypedNodeList ParentsAfterImport =
 Ctx.getParentMapContext().getParents(*FD);
Index: clang/test/Analysis/plist-macros-with-expansion-ctu.c
===
--- clang/test/Analysis/plist-macros-with-expansion-ctu.c
+++ clang/test/Analysis/plist-macros-with-expansion-ctu.c
@@ -2,13 +2,13 @@
 // RUN: mkdir -p %t/ctudir
 // RUN: %clang_cc1 -emit-pch -o %t/ctudir/plist-macros-ctu.c.ast %S/Inputs/plist-macros-ctu.c
 // RUN: cp %S/Inputs/plist-macros-with-expansion-ctu.c.externalDefMap.txt %t/ctudir/externalDefMap.txt
-
+//
 // RUN: %clang_analyze_cc1 -analyzer-checker=core \
 // RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
 // RUN:   -analyzer-config ctu-dir=%t/ctudir \
 // RUN:   -analyzer-config expand-macros=true \
 // RUN:   -analyzer-output=plist-multi-file -o %t.plist -verify %s
-// XFAIL: *
+//
 // Check the macro expansions from the plist output here, to make the test more
 // understandable.
 //   RUN: FileCheck --input-file=%t.plist %s
@@ -23,25 +23,30 @@
   F3(&X);
   *X = 1; // expected-warning{{Dereference of null pointer}}
 }
-// CHECK: nameM1
-// CHECK-NEXT: expansion*Z = (int *)0
-
+// FIXME: Macro expansion for other TUs should also work.
+// CHECK:  macro_expansions
+// CHECK-NEXT: 
+// CHECK-NEXT: 
 
 void test1() {
   int *X;
   F1(&X);
   *X = 1; // expected-warning{{Dereference of null pointer}}
 }
-// CHECK: nameM
-// CHECK-NEXT: expansion*X = (int *)0
+
+// CHECK:  macro_expansions
+// CHECK-NEXT: 
+// CHECK-NEXT: 
 
 void test2() {
   int *X;
   F2(&X);
   *X = 1; // expected-warning{{Dereference of null pointer}}
 }
-// CHECK: nameM
-// CHECK-NEXT: expansion*Y = (int *)0
+
+// CHECK:  macro_expansions
+// CHECK-NEXT: 
+// CHECK-NEXT: 
 
 #define M F1(&X)
 
@@ -50,10 +55,20 @@
   M;
   *X = 1; // expected-warning{{Dereference of null pointer}}
 }
-// CHECK: nameM
-// CHECK-NEXT: expansionF1(&X)
-// CHECK: nameM
-// CHECK-NEXT: expansion*X = (int *)0
+// Macro expansions for the main TU still works, even in CTU mode.
+// CHECK:  macro_expansions
+// CHECK-NEXT: 
+// CHECK-NEXT:  
+// CHECK-NEXT:   location
+// CHECK-NEXT:   
+// CHECK-NEXT:line55
+// CHECK-NEXT:col3
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:   nameM
+// CHECK-NEXT:   expansionF1 (&X )
+// CHECK-NEXT:  
+// CHECK-NEXT: 
 
 #undef M
 #define M F2(&X)
@@ -64,10 +79,19 @@
   *X = 1; // expected-warning{{Dereference of null pointer}}
 }
 
-// CHECK: nameM
-// CHECK-NEXT: expansionF2(&X)
-// CHECK: nameM
-// CHECK-NEXT: expansion*Y = (int *)0
+// CHECK:  macro_expansions
+// CHECK-NEXT: 
+// CHECK-NEXT:  
+// CHECK-NEXT:   location
+// CHECK-NEXT:   
+// CHECK-NEXT:line78
+// CHECK-NEXT:col3
+// CHECK-NEXT:file0
+// CHECK-NEXT:   
+// CHECK-NEXT:   nameM
+// CHECK-NEXT:   expansionF2 (&X )
+// CHECK-NEXT:  
+// CHECK-NEXT: 
 
 void test_h() {
   int *X;
@@ -75,5 +99,6 @@
   *X = 1; // expected-warning

[PATCH] D103707: [AIX] Define __STDC_NO_ATOMICS__ and __STDC_NO_THREADS__ predefined macros

2021-06-07 Thread 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 rGe6629be31e67: [AIX] Define __STDC_NO_ATOMICS__ and 
__STDC_NO_THREADS__ predefined macros (authored by Jake-Egan, committed by 
cbowler ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103707

Files:
  clang/lib/Basic/Targets/OSTargets.h
  clang/test/Preprocessor/init-ppc.c


Index: clang/test/Preprocessor/init-ppc.c
===
--- clang/test/Preprocessor/init-ppc.c
+++ clang/test/Preprocessor/init-ppc.c
@@ -723,6 +723,16 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 
-fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix 
PPC-AIX-NOTHREADSAFE %s
 // PPC-AIX-NOTHREADSAFE-NOT:#define _THREAD_SAFE 1
 
+// RUN: %clang_cc1 -x c -std=c11 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=gnu11 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=c17 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// PPC-AIX-STDC:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC:#define __STDC_NO_THREADS__ 1
+
+// RUN: %clang_cc1 -x c -std=c99 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC-N %s
+// PPC-AIX-STDC-N-NOT:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC-N-NOT:#define __STDC_NO_THREADS__ 1
+
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-unknown-linux-gnu 
-fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix 
PPC-LINUX %s
 //
 // PPC-LINUX:#define _ARCH_PPC 1
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -676,6 +676,11 @@
 
 Builder.defineMacro("_AIX");
 
+if (LangStandard::getLangStandardForKind(Opts.LangStd).isC11()) {
+  Builder.defineMacro("__STDC_NO_ATOMICS__");
+  Builder.defineMacro("__STDC_NO_THREADS__");
+}
+
 if (Opts.EnableAIXExtendedAltivecABI)
   Builder.defineMacro("__EXTABI__");
 


Index: clang/test/Preprocessor/init-ppc.c
===
--- clang/test/Preprocessor/init-ppc.c
+++ clang/test/Preprocessor/init-ppc.c
@@ -723,6 +723,16 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-NOTHREADSAFE %s
 // PPC-AIX-NOTHREADSAFE-NOT:#define _THREAD_SAFE 1
 
+// RUN: %clang_cc1 -x c -std=c11 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=gnu11 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=c17 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// PPC-AIX-STDC:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC:#define __STDC_NO_THREADS__ 1
+
+// RUN: %clang_cc1 -x c -std=c99 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC-N %s
+// PPC-AIX-STDC-N-NOT:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC-N-NOT:#define __STDC_NO_THREADS__ 1
+
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-unknown-linux-gnu -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-LINUX %s
 //
 // PPC-LINUX:#define _ARCH_PPC 1
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -676,6 +676,11 @@
 
 Builder.defineMacro("_AIX");
 
+if (LangStandard::getLangStandardForKind(Opts.LangStd).isC11()) {
+  Builder.defineMacro("__STDC_NO_ATOMICS__");
+  Builder.defineMacro("__STDC_NO_THREADS__");
+}
+
 if (Opts.EnableAIXExtendedAltivecABI)
   Builder.defineMacro("__EXTABI__");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D104774: [clang-format] Fix a bug that indents else-comment-if incorrectly

2021-06-23 Thread 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 rGca7f47158581: [clang-format] Fix a bug that indents 
else-comment-if incorrectly (authored by owenca 
).

Changed prior to commit:
  https://reviews.llvm.org/D104774?vs=353909&id=353933#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104774

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1181,6 +1181,13 @@
"  g();\n"
"else\n"
"  h();");
+  verifyFormat("if (a)\n"
+   "  f();\n"
+   "else // comment\n"
+   "  if (b) {\n"
+   "g();\n"
+   "h();\n"
+   "  }");
   verifyFormat("if constexpr (a)\n"
"  f();\n"
"else if constexpr (b)\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2021,7 +2021,15 @@
   parseBlock(/*MustBeDeclaration=*/false);
   addUnwrappedLine();
 } else if (FormatTok->Tok.is(tok::kw_if)) {
+  FormatToken *Previous = AllTokens[Tokens->getPosition() - 1];
+  bool PrecededByComment = Previous->is(tok::comment);
+  if (PrecededByComment) {
+addUnwrappedLine();
+++Line->Level;
+  }
   parseIfThenElse();
+  if (PrecededByComment)
+--Line->Level;
 } else {
   addUnwrappedLine();
   ++Line->Level;


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1181,6 +1181,13 @@
"  g();\n"
"else\n"
"  h();");
+  verifyFormat("if (a)\n"
+   "  f();\n"
+   "else // comment\n"
+   "  if (b) {\n"
+   "g();\n"
+   "h();\n"
+   "  }");
   verifyFormat("if constexpr (a)\n"
"  f();\n"
"else if constexpr (b)\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2021,7 +2021,15 @@
   parseBlock(/*MustBeDeclaration=*/false);
   addUnwrappedLine();
 } else if (FormatTok->Tok.is(tok::kw_if)) {
+  FormatToken *Previous = AllTokens[Tokens->getPosition() - 1];
+  bool PrecededByComment = Previous->is(tok::comment);
+  if (PrecededByComment) {
+addUnwrappedLine();
+++Line->Level;
+  }
   parseIfThenElse();
+  if (PrecededByComment)
+--Line->Level;
 } else {
   addUnwrappedLine();
   ++Line->Level;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107720: [analyzer] Cleanup a FIXME in SValBuilder.cpp

2021-08-10 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd39ebdae674c: [analyzer] Cleanup a FIXME in SValBuilder.cpp 
(authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107720

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/solver-sym-simplification-bool.cpp


Index: clang/test/Analysis/solver-sym-simplification-bool.cpp
===
--- /dev/null
+++ clang/test/Analysis/solver-sym-simplification-bool.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_analyze_cc1 -analyze -analyzer-checker=core \
+// RUN: -analyzer-checker=debug.ExprInspection -verify %s
+
+void clang_analyzer_dump(bool);
+
+void foo(int &x) {
+  int *p = &x; // 'p' is the same SVal as 'x'
+  bool b = p;
+  clang_analyzer_dump(b); // expected-warning {{1 U1b}}
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -725,16 +725,12 @@
   // This change is needed for architectures with varying
   // pointer widths. See the amdgcn opencl reproducer with
   // this change as an example: solver-sym-simplification-ptr-bool.cl
-  // FIXME: We could encounter a reference here,
-  //try returning a concrete 'true' since it might
-  //be easier on the solver.
   // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
   //and `getIntWithPtrWidth()` functions to prevent future
   //confusion
-  const llvm::APSInt &Zero = Ty->isReferenceType()
- ? BasicVals.getZeroWithPtrWidth()
- : BasicVals.getZeroWithTypeSize(Ty);
-  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+  if (!Ty->isReferenceType())
+return makeNonLoc(Sym, BO_NE, BasicVals.getZeroWithTypeSize(Ty),
+  CastTy);
 }
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);


Index: clang/test/Analysis/solver-sym-simplification-bool.cpp
===
--- /dev/null
+++ clang/test/Analysis/solver-sym-simplification-bool.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_analyze_cc1 -analyze -analyzer-checker=core \
+// RUN: -analyzer-checker=debug.ExprInspection -verify %s
+
+void clang_analyzer_dump(bool);
+
+void foo(int &x) {
+  int *p = &x; // 'p' is the same SVal as 'x'
+  bool b = p;
+  clang_analyzer_dump(b); // expected-warning {{1 U1b}}
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -725,16 +725,12 @@
   // This change is needed for architectures with varying
   // pointer widths. See the amdgcn opencl reproducer with
   // this change as an example: solver-sym-simplification-ptr-bool.cl
-  // FIXME: We could encounter a reference here,
-  //try returning a concrete 'true' since it might
-  //be easier on the solver.
   // FIXME: Cleanup remainder of `getZeroWithPtrWidth ()`
   //and `getIntWithPtrWidth()` functions to prevent future
   //confusion
-  const llvm::APSInt &Zero = Ty->isReferenceType()
- ? BasicVals.getZeroWithPtrWidth()
- : BasicVals.getZeroWithTypeSize(Ty);
-  return makeNonLoc(Sym, BO_NE, Zero, CastTy);
+  if (!Ty->isReferenceType())
+return makeNonLoc(Sym, BO_NE, BasicVals.getZeroWithTypeSize(Ty),
+  CastTy);
 }
 // Non-symbolic memory regions are always true.
 return makeTruthVal(true, CastTy);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107952: [AMDGPU][OpenMP] Use llvm-link to link ocml libraries

2021-08-13 Thread 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 rG60e07a956862: [AMDGPU][OpenMP] Use llvm-link to link ocml 
libraries (authored by Pushpinder Singh ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107952

Files:
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
  clang/test/Driver/amdgpu-openmp-toolchain.c

Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -76,4 +76,4 @@
 // CHECK-EMIT-LLVM-IR: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-emit-llvm"
 
 // RUN: env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### -target x86_64-pc-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 -lm --rocm-device-lib-path=%S/Inputs/rocm/amdgcn/bitcode %s 2>&1 | FileCheck %s --check-prefix=CHECK-LIB-DEVICE
-// CHECK-LIB-DEVICE: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx803.bc"{{.*}}"-mlink-builtin-bitcode"{{.*}}ocml.bc" "-mlink-builtin-bitcode"{{.*}}ockl.bc" "-mlink-builtin-bitcode"{{.*}}oclc_daz_opt_on.bc" "-mlink-builtin-bitcode"{{.*}}oclc_unsafe_math_off.bc" "-mlink-builtin-bitcode"{{.*}}oclc_finite_only_off.bc" "-mlink-builtin-bitcode"{{.*}}oclc_correctly_rounded_sqrt_on.bc" "-mlink-builtin-bitcode"{{.*}}oclc_wavefrontsize64_on.bc" "-mlink-builtin-bitcode"{{.*}}oclc_isa_version_803.bc"
+// CHECK-LIB-DEVICE: {{.*}}llvm-link{{.*}}ocml.bc"{{.*}}ockl.bc"{{.*}}oclc_daz_opt_on.bc"{{.*}}oclc_unsafe_math_off.bc"{{.*}}oclc_finite_only_off.bc"{{.*}}oclc_correctly_rounded_sqrt_on.bc"{{.*}}oclc_wavefrontsize64_on.bc"{{.*}}oclc_isa_version_803.bc"
Index: clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
===
--- clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
+++ clang/lib/Driver/ToolChains/AMDGPUOpenMP.h
@@ -16,6 +16,10 @@
 namespace clang {
 namespace driver {
 
+namespace toolchains {
+class AMDGPUOpenMPToolChain;
+}
+
 namespace tools {
 
 namespace AMDGCN {
@@ -35,11 +39,11 @@
 
 private:
   /// \return llvm-link output file name.
-  const char *constructLLVMLinkCommand(Compilation &C, const JobAction &JA,
-   const InputInfoList &Inputs,
-   const llvm::opt::ArgList &Args,
-   llvm::StringRef SubArchName,
-   llvm::StringRef OutputFilePrefix) const;
+  const char *constructLLVMLinkCommand(
+  const toolchains::AMDGPUOpenMPToolChain &AMDGPUOpenMPTC, Compilation &C,
+  const JobAction &JA, const InputInfoList &Inputs,
+  const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
+  llvm::StringRef OutputFilePrefix) const;
 
   /// \return llc output file name.
   const char *constructLlcCommand(Compilation &C, const JobAction &JA,
Index: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
+++ clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
@@ -86,14 +86,34 @@
 } // namespace
 
 const char *AMDGCN::OpenMPLinker::constructLLVMLinkCommand(
-Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
-const ArgList &Args, StringRef SubArchName,
-StringRef OutputFilePrefix) const {
+const toolchains::AMDGPUOpenMPToolChain &AMDGPUOpenMPTC, Compilation &C,
+const JobAction &JA, const InputInfoList &Inputs, const ArgList &Args,
+StringRef SubArchName, StringRef OutputFilePrefix) const {
   ArgStringList CmdArgs;
 
   for (const auto &II : Inputs)
 if (II.isFilename())
   CmdArgs.push_back(II.getFilename());
+
+  if (Args.hasArg(options::OPT_l)) {
+auto Lm = Args.getAllArgValues(options::OPT_l);
+bool HasLibm = false;
+for (auto &Lib : Lm) {
+  if (Lib == "m") {
+HasLibm = true;
+break;
+  }
+}
+
+if (HasLibm) {
+  SmallVector BCLibs =
+  AMDGPUOpenMPTC.getCommonDeviceLibNames(Args, SubArchName.str());
+  llvm::for_each(BCLibs, [&](StringRef BCFile) {
+CmdArgs.push_back(Args.MakeArgString(BCFile));
+  });
+}
+  }
+
   // Add an intermediate output file.
   CmdArgs.push_back("-o");
   const char *OutputFileName =
@@ -182,8 +202,8 @@
   assert(Prefix.length() && "no linker inputs are files ");
 
   // Each command outputs different files.
-  const char *LLVMLinkCommand =
-  constructLLVMLinkCommand(C, JA, Inputs, Args, GPUArch, Prefix);
+  const char *LLVMLinkCommand = constructLLVMLinkCommand(
+  AMDGPUOpenMPTC, C, JA, Inputs, Args, GPUArch, Prefix);
 

[PATCH] D105368: Lex: add a callback for `#pragma mark`

2021-07-02 Thread 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 rG24f4c3ebef63: Lex: add a callback for `#pragma mark` 
(authored by compnerd, committed by Saleem Abdulrasool 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105368

Files:
  clang/include/clang/Lex/PPCallbacks.h
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/Pragma.cpp
  clang/unittests/Lex/PPCallbacksTest.cpp

Index: clang/unittests/Lex/PPCallbacksTest.cpp
===
--- clang/unittests/Lex/PPCallbacksTest.cpp
+++ clang/unittests/Lex/PPCallbacksTest.cpp
@@ -112,6 +112,20 @@
   unsigned State;
 };
 
+class PragmaMarkCallbacks : public PPCallbacks {
+public:
+  struct Mark {
+SourceLocation Location;
+std::string Trivia;
+  };
+
+  std::vector Marks;
+
+  void PragmaMark(SourceLocation Loc, StringRef Trivia) override {
+Marks.emplace_back(Mark{Loc, Trivia.str()});
+  }
+};
+
 // PPCallbacks test fixture.
 class PPCallbacksTest : public ::testing::Test {
 protected:
@@ -256,6 +270,36 @@
 return Callbacks->Results;
   }
 
+  std::vector
+  PragmaMarkCall(const char *SourceText) {
+std::unique_ptr SourceBuf =
+llvm::MemoryBuffer::getMemBuffer(SourceText, "test.c");
+SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(SourceBuf)));
+
+HeaderSearch HeaderInfo(std::make_shared(), SourceMgr,
+Diags, LangOpts, Target.get());
+TrivialModuleLoader ModLoader;
+
+Preprocessor PP(std::make_shared(), Diags, LangOpts,
+SourceMgr, HeaderInfo, ModLoader, /*IILookup=*/nullptr,
+/*OwnsHeaderSearch=*/false);
+PP.Initialize(*Target);
+
+auto *Callbacks = new PragmaMarkCallbacks;
+PP.addPPCallbacks(std::unique_ptr(Callbacks));
+
+// Lex source text.
+PP.EnterMainSourceFile();
+while (true) {
+  Token Tok;
+  PP.Lex(Tok);
+  if (Tok.is(tok::eof))
+break;
+}
+
+return Callbacks->Marks;
+  }
+
   PragmaOpenCLExtensionCallbacks::CallbackParameters
   PragmaOpenCLExtensionCall(const char *SourceText) {
 LangOptions OpenCLLangOpts;
@@ -424,6 +468,24 @@
   ASSERT_EQ(ExpectedState, Parameters.State);
 }
 
+TEST_F(PPCallbacksTest, CollectMarks) {
+  const char *Source =
+"#pragma mark\n"
+"#pragma mark\r\n"
+"#pragma mark - trivia\n"
+"#pragma mark - trivia\r\n";
+
+  auto Marks = PragmaMarkCall(Source);
+
+  ASSERT_EQ(4u, Marks.size());
+  ASSERT_TRUE(Marks[0].Trivia.empty());
+  ASSERT_TRUE(Marks[1].Trivia.empty());
+  ASSERT_FALSE(Marks[2].Trivia.empty());
+  ASSERT_FALSE(Marks[3].Trivia.empty());
+  ASSERT_EQ(" - trivia", Marks[2].Trivia);
+  ASSERT_EQ(" - trivia", Marks[3].Trivia);
+}
+
 TEST_F(PPCallbacksTest, DirectiveExprRanges) {
   const auto &Results1 = DirectiveExprRange("#if FLUZZY_FLOOF\n#endif\n");
   EXPECT_EQ(Results1.size(), 1U);
Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -412,9 +412,13 @@
   HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
 }
 
-void Preprocessor::HandlePragmaMark() {
+void Preprocessor::HandlePragmaMark(Token &MarkTok) {
   assert(CurPPLexer && "No current lexer?");
-  CurLexer->ReadToEndOfLine();
+
+  SmallString<64> Buffer;
+  CurLexer->ReadToEndOfLine(&Buffer);
+  if (Callbacks)
+Callbacks->PragmaMark(MarkTok.getLocation(), Buffer);
 }
 
 /// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
@@ -992,7 +996,7 @@
 
   void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
 Token &MarkTok) override {
-PP.HandlePragmaMark();
+PP.HandlePragmaMark(MarkTok);
   }
 };
 
Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -2365,7 +2365,7 @@
 
 public:
   void HandlePragmaOnce(Token &OnceTok);
-  void HandlePragmaMark();
+  void HandlePragmaMark(Token &MarkTok);
   void HandlePragmaPoison();
   void HandlePragmaSystemHeader(Token &SysHeaderTok);
   void HandlePragmaDependency(Token &DependencyTok);
Index: clang/include/clang/Lex/PPCallbacks.h
===
--- clang/include/clang/Lex/PPCallbacks.h
+++ clang/include/clang/Lex/PPCallbacks.h
@@ -191,6 +191,10 @@
  StringRef Str) {
   }
 
+  /// Callback invoked when a \#pragma mark comment is read.
+  virtual void PragmaMark(SourceLocation Loc, StringRef Trivia) {
+  }
+
   /// Callback invoked when a \#pragma detect_mismatch directive is
   /// read.
   virtual void PragmaDetectMismatch(SourceLocation Loc, StringRef Name,

[PATCH] D105378: [dfsan][NFC] Add Origin Tracking into doc

2021-07-07 Thread 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 rG71dc0f1c02cd: [dfsan][NFC] Add Origin Tracking into doc 
(authored by Jianzhou Zhao ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105378

Files:
  clang/docs/DataFlowSanitizer.rst


Index: clang/docs/DataFlowSanitizer.rst
===
--- clang/docs/DataFlowSanitizer.rst
+++ clang/docs/DataFlowSanitizer.rst
@@ -191,6 +191,44 @@
 return 0;
   }
 
+Origin Tracking
+===
+
+DataFlowSanitizer can track origins of labeled values. This feature is enabled 
by
+``-mllvm -dfsan-track-origins=1``. For example,
+
+.. code-block:: console
+
+% cat test.cc
+#include 
+#include 
+
+int main(int argc, char** argv) {
+  int i = 0;
+  dfsan_set_label(i_label, &i, sizeof(i));
+  int j = i + 1;
+  dfsan_print_origin_trace(&j, "A flow from i to j");
+  return 0;
+}
+
+% clang++ -fsanitize=dataflow -mllvm -dfsan-track-origins=1 
-fno-omit-frame-pointer -g -O2 test.cc
+% ./a.out
+Taint value 0x1 (at 0x7ffd42bf415c) origin tracking (A flow from i to j)
+Origin value: 0x1391, Taint value was stored to memory at
+  #0 0x55676db85a62 in main test.cc:7:7
+  #1 0x7f0083611bbc in __libc_start_main libc-start.c:285
+
+Origin value: 0x9e1, Taint value was created at
+  #0 0x55676db85a08 in main test.cc:6:3
+  #1 0x7f0083611bbc in __libc_start_main libc-start.c:285
+
+By ``-mllvm -dfsan-track-origins=1`` DataFlowSanitizer collects only
+intermediate stores a labeled value went through. Origin tracking slows down
+program execution by a factor of 2x on top of the usual DataFlowSanitizer
+slowdown and increases memory overhead by 1x. By ``-mllvm 
-dfsan-track-origins=2``
+DataFlowSanitizer also collects intermediate loads a labeled value went 
through.
+This mode slows down program execution by a factor of 4x.
+
 Current status
 ==
 


Index: clang/docs/DataFlowSanitizer.rst
===
--- clang/docs/DataFlowSanitizer.rst
+++ clang/docs/DataFlowSanitizer.rst
@@ -191,6 +191,44 @@
 return 0;
   }
 
+Origin Tracking
+===
+
+DataFlowSanitizer can track origins of labeled values. This feature is enabled by
+``-mllvm -dfsan-track-origins=1``. For example,
+
+.. code-block:: console
+
+% cat test.cc
+#include 
+#include 
+
+int main(int argc, char** argv) {
+  int i = 0;
+  dfsan_set_label(i_label, &i, sizeof(i));
+  int j = i + 1;
+  dfsan_print_origin_trace(&j, "A flow from i to j");
+  return 0;
+}
+
+% clang++ -fsanitize=dataflow -mllvm -dfsan-track-origins=1 -fno-omit-frame-pointer -g -O2 test.cc
+% ./a.out
+Taint value 0x1 (at 0x7ffd42bf415c) origin tracking (A flow from i to j)
+Origin value: 0x1391, Taint value was stored to memory at
+  #0 0x55676db85a62 in main test.cc:7:7
+  #1 0x7f0083611bbc in __libc_start_main libc-start.c:285
+
+Origin value: 0x9e1, Taint value was created at
+  #0 0x55676db85a08 in main test.cc:6:3
+  #1 0x7f0083611bbc in __libc_start_main libc-start.c:285
+
+By ``-mllvm -dfsan-track-origins=1`` DataFlowSanitizer collects only
+intermediate stores a labeled value went through. Origin tracking slows down
+program execution by a factor of 2x on top of the usual DataFlowSanitizer
+slowdown and increases memory overhead by 1x. By ``-mllvm -dfsan-track-origins=2``
+DataFlowSanitizer also collects intermediate loads a labeled value went through.
+This mode slows down program execution by a factor of 4x.
+
 Current status
 ==
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105091: [RISCV] Pass -u to linker correctly.

2021-07-13 Thread 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 rG5635d2a56dab: [RISCV] Pass -u to linker correctly. (authored 
by Kito Cheng ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105091

Files:
  clang/lib/Driver/ToolChains/RISCVToolchain.cpp
  clang/test/Driver/riscv-args.c


Index: clang/test/Driver/riscv-args.c
===
--- clang/test/Driver/riscv-args.c
+++ clang/test/Driver/riscv-args.c
@@ -1,7 +1,6 @@
 // Check the arguments are correctly passed
 
 // Make sure -T is the last with gcc-toolchain option
-// RUN: %clang -### -target riscv32 \
-// RUN:   --gcc-toolchain= -Xlinker --defsym=FOO=10 -T a.lds %s 2>&1 \
+// RUN: %clang -### -target riscv32 --gcc-toolchain= -Xlinker --defsym=FOO=10 
-T a.lds -u foo %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-LD %s
-// CHECK-LD: {{.*}} "--defsym=FOO=10" {{.*}} "-T" "a.lds"
+// CHECK-LD: {{.*}} "--defsym=FOO=10" {{.*}} "-u" "foo" {{.*}} "-T" "a.lds"
Index: clang/lib/Driver/ToolChains/RISCVToolchain.cpp
===
--- clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -184,6 +184,7 @@
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
+  Args.AddAllArgs(CmdArgs, options::OPT_u);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
   Args.AddAllArgs(CmdArgs,
   {options::OPT_T_Group, options::OPT_e, options::OPT_s,


Index: clang/test/Driver/riscv-args.c
===
--- clang/test/Driver/riscv-args.c
+++ clang/test/Driver/riscv-args.c
@@ -1,7 +1,6 @@
 // Check the arguments are correctly passed
 
 // Make sure -T is the last with gcc-toolchain option
-// RUN: %clang -### -target riscv32 \
-// RUN:   --gcc-toolchain= -Xlinker --defsym=FOO=10 -T a.lds %s 2>&1 \
+// RUN: %clang -### -target riscv32 --gcc-toolchain= -Xlinker --defsym=FOO=10 -T a.lds -u foo %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-LD %s
-// CHECK-LD: {{.*}} "--defsym=FOO=10" {{.*}} "-T" "a.lds"
+// CHECK-LD: {{.*}} "--defsym=FOO=10" {{.*}} "-u" "foo" {{.*}} "-T" "a.lds"
Index: clang/lib/Driver/ToolChains/RISCVToolchain.cpp
===
--- clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -184,6 +184,7 @@
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
+  Args.AddAllArgs(CmdArgs, options::OPT_u);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
   Args.AddAllArgs(CmdArgs,
   {options::OPT_T_Group, options::OPT_e, options::OPT_s,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97759: [doc] Fix description of _Float16

2021-03-03 Thread 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 rGb46a1b129f68: [doc] Fix description of _Float16 (authored by 
Kito Cheng ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D97759?vs=327387&id=328023#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97759

Files:
  clang/docs/LanguageExtensions.rst


Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -542,7 +542,7 @@
 Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the 
ARM
 alternative format.
 
-``_Float16`` is an extended floating-point type.  This means that, just like 
arithmetic on
+``_Float16`` is an interchange floating-point type.  This means that, just 
like arithmetic on
 ``float`` or ``double``, arithmetic on ``_Float16`` operands is formally 
performed in the
 ``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values 
has type
 ``_Float16``.  The behavior of ``_Float16`` is specified by ISO/IEC TS 
18661-3:2015


Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -542,7 +542,7 @@
 Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
 alternative format.
 
-``_Float16`` is an extended floating-point type.  This means that, just like arithmetic on
+``_Float16`` is an interchange floating-point type.  This means that, just like arithmetic on
 ``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the
 ``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
 ``_Float16``.  The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97936: [analyzer][docs][NFC] Fix typo in checkers.rst

2021-03-10 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG57e149d38628: [analyzer][docs][NFC] Fix typo in checkers.rst 
(authored by Balazs Benics ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97936

Files:
  clang/docs/analyzer/checkers.rst


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -1476,6 +1476,9 @@
return y;
  }
 
+alpha.core
+^^
+
 .. _alpha-core-BoolAssignment:
 
 alpha.core.BoolAssignment (ObjC)
@@ -1488,9 +1491,6 @@
BOOL b = -1; // warn
  }
 
-alpha.core
-^^
-
 .. _alpha-core-C11Lock:
 
 alpha.core.C11Lock


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -1476,6 +1476,9 @@
return y;
  }
 
+alpha.core
+^^
+
 .. _alpha-core-BoolAssignment:
 
 alpha.core.BoolAssignment (ObjC)
@@ -1488,9 +1491,6 @@
BOOL b = -1; // warn
  }
 
-alpha.core
-^^
-
 .. _alpha-core-C11Lock:
 
 alpha.core.C11Lock
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86870: [analyzer] Add more tests for ArrayBoundCheckerV2

2021-03-10 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0dc0e2a9ab3c: [analyzer][NFC] Add more tests for 
ArrayBoundCheckerV2 (authored by Balazs Benics 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86870

Files:
  clang/test/Analysis/out-of-bounds-false-positive.c

Index: clang/test/Analysis/out-of-bounds-false-positive.c
===
--- /dev/null
+++ clang/test/Analysis/out-of-bounds-false-positive.c
@@ -0,0 +1,101 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.security.ArrayBoundV2,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false -verify %s
+
+void clang_analyzer_eval(int);
+void clang_analyzer_printState();
+
+typedef unsigned long long size_t;
+const char a[] = "abcd"; // extent: 5 bytes
+
+void symbolic_size_t_and_int0(size_t len) {
+  // FIXME: Should not warn for this.
+  (void)a[len + 1]; // expected-warning {{Out of bound memory access}}
+  // We infered that the 'len' must be in a specific range to make the previous indexing valid.
+  // len: [0,3]
+  clang_analyzer_eval(len <= 3); // expected - warning {{TRUE}}
+  clang_analyzer_eval(len <= 2); // expected - warning {{UNKNOWN}}
+}
+
+void symbolic_size_t_and_int1(size_t len) {
+  (void)a[len]; // no-warning
+  // len: [0,4]
+  clang_analyzer_eval(len <= 4); // expected-warning {{TRUE}}
+  clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_size_t_and_int2(size_t len) {
+  (void)a[len - 1]; // no-warning
+  // len: [1,5]
+  clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}}
+  clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_uint_and_int0(unsigned len) {
+  (void)a[len + 1]; // no-warning
+  // len: [0,3]
+  clang_analyzer_eval(0 <= len && len <= 3); // expected-warning {{TRUE}}
+  clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_uint_and_int1(unsigned len) {
+  (void)a[len]; // no-warning
+  // len: [0,4]
+  clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}}
+  clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}}
+}
+void symbolic_uint_and_int2(unsigned len) {
+  (void)a[len - 1]; // no-warning
+  // len: [1,5]
+  clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}}
+  clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_int_and_int0(int len) {
+  (void)a[len + 1]; // no-warning
+  // len: [-1,3]
+  clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}}
+  clang_analyzer_eval(0 <= len);  // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 2);  // expected-warning {{UNKNOWN}}
+}
+void symbolic_int_and_int1(int len) {
+  (void)a[len]; // no-warning
+  // len: [0,4]
+  clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}}
+  clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}}
+}
+void symbolic_int_and_int2(int len) {
+  (void)a[len - 1]; // no-warning
+  // len: [1,5]
+  clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}}
+  clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_longlong_and_int0(long long len) {
+  (void)a[len + 1]; // no-warning
+  // len: [-1,3]
+  clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}}
+  clang_analyzer_eval(0 <= len);  // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 2);  // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_longlong_and_int1(long long len) {
+  (void)a[len]; // no-warning
+  // len: [0,4]
+  clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}}
+  clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}}
+}
+
+void symbolic_longlong_and_int2(long long len) {
+  (void)a[len - 1]; // no-warning
+  // len: [1,5]
+  clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}}
+  clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}}
+}
___
cfe-commits mailing list
cfe-commits@lists.ll

[PATCH] D96586: [analyzer][CTU][NFC] Add an extra regression test

2021-03-10 Thread 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 rG0e0ea9ffb802: [analyzer][CTU][NFC] Add an extra regression 
test (authored by Balazs Benics ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96586

Files:
  clang/test/Analysis/Inputs/ctu-inherited-default-ctor-other.cpp
  clang/test/Analysis/ctu-inherited-default-ctor.cpp


Index: clang/test/Analysis/ctu-inherited-default-ctor.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-inherited-default-ctor.cpp
@@ -0,0 +1,28 @@
+// Should not crash with '-analyzer-opt-analyze-headers' option during CTU 
analysis.
+//
+// RUN: rm -r %t && mkdir -p %t/ctudir
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -emit-pch -o %t/ctudir/ctu-inherited-default-ctor-other.cpp.ast \
+// RUN:%S/Inputs/ctu-inherited-default-ctor-other.cpp
+// RUN: echo "c:@N@clang@S@DeclContextLookupResult@SingleElementDummyList 
ctu-inherited-default-ctor-other.cpp.ast" \
+// RUN:   > %t/ctudir/externalDefMap.txt
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -analyzer-opt-analyze-headers \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir \
+// RUN:   -analyzer-config display-ctu-progress=true \
+// RUN:   -verify %s 2>&1 | FileCheck %s
+//
+// expected-no-diagnostics
+//
+// CHECK: CTU loaded AST file: ctu-inherited-default-ctor-other.cpp.ast
+
+namespace clang {}
+namespace llvm {}
+namespace clang {
+class DeclContextLookupResult {
+  static int *const SingleElementDummyList;
+};
+} // namespace clang
Index: clang/test/Analysis/Inputs/ctu-inherited-default-ctor-other.cpp
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-inherited-default-ctor-other.cpp
@@ -0,0 +1,27 @@
+namespace llvm {
+template 
+class impl;
+// basecase
+template 
+class impl {};
+// recursion
+template 
+class impl : impl {
+  using child = impl;
+  using child::child; // no-crash
+  impl(T);
+};
+template 
+class container : impl<0, TS...> {};
+} // namespace llvm
+namespace clang {
+class fun {
+  llvm::container k;
+  fun() {}
+};
+class DeclContextLookupResult {
+  static int *const SingleElementDummyList;
+};
+} // namespace clang
+using namespace clang;
+int *const DeclContextLookupResult::SingleElementDummyList = nullptr;


Index: clang/test/Analysis/ctu-inherited-default-ctor.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-inherited-default-ctor.cpp
@@ -0,0 +1,28 @@
+// Should not crash with '-analyzer-opt-analyze-headers' option during CTU analysis.
+//
+// RUN: rm -r %t && mkdir -p %t/ctudir
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -emit-pch -o %t/ctudir/ctu-inherited-default-ctor-other.cpp.ast \
+// RUN:%S/Inputs/ctu-inherited-default-ctor-other.cpp
+// RUN: echo "c:@N@clang@S@DeclContextLookupResult@SingleElementDummyList ctu-inherited-default-ctor-other.cpp.ast" \
+// RUN:   > %t/ctudir/externalDefMap.txt
+//
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -analyzer-opt-analyze-headers \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir \
+// RUN:   -analyzer-config display-ctu-progress=true \
+// RUN:   -verify %s 2>&1 | FileCheck %s
+//
+// expected-no-diagnostics
+//
+// CHECK: CTU loaded AST file: ctu-inherited-default-ctor-other.cpp.ast
+
+namespace clang {}
+namespace llvm {}
+namespace clang {
+class DeclContextLookupResult {
+  static int *const SingleElementDummyList;
+};
+} // namespace clang
Index: clang/test/Analysis/Inputs/ctu-inherited-default-ctor-other.cpp
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-inherited-default-ctor-other.cpp
@@ -0,0 +1,27 @@
+namespace llvm {
+template 
+class impl;
+// basecase
+template 
+class impl {};
+// recursion
+template 
+class impl : impl {
+  using child = impl;
+  using child::child; // no-crash
+  impl(T);
+};
+template 
+class container : impl<0, TS...> {};
+} // namespace llvm
+namespace clang {
+class fun {
+  llvm::container k;
+  fun() {}
+};
+class DeclContextLookupResult {
+  static int *const SingleElementDummyList;
+};
+} // namespace clang
+using namespace clang;
+int *const DeclContextLookupResult::SingleElementDummyList = nullptr;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D85424: [Analyzer] Crash fix for alpha.cplusplus.IteratorRange

2021-03-10 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbcc662484a95: [analyzer] Crash fix for 
alpha.cplusplus.IteratorRange (authored by baloghadamsoftware, committed by 
Balazs Benics ).

Changed prior to commit:
  https://reviews.llvm.org/D85424?vs=290967&id=329600#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85424

Files:
  clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
  clang/test/Analysis/iterator-range.cpp


Index: clang/test/Analysis/iterator-range.cpp
===
--- clang/test/Analysis/iterator-range.cpp
+++ clang/test/Analysis/iterator-range.cpp
@@ -939,3 +939,10 @@
   auto i0 = c.begin(), i1 = c.end();
   ptrdiff_t len = i1 - i0; // no-crash
 }
+
+int uninit_var(int n) {
+  int uninit; // expected-note{{'uninit' declared without an initial value}}
+  return n - uninit; // no-crash
+  // expected-warning@-1 {{The right operand of '-' is a garbage value}}
+  // expected-note@-2 {{The right operand of '-' is a garbage value}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
@@ -228,7 +228,7 @@
 Value = State->getRawSVal(*ValAsLoc);
   }
 
-  if (Value.isUnknown())
+  if (Value.isUnknownOrUndef())
 return;
 
   // Incremention or decremention by 0 is never a bug.


Index: clang/test/Analysis/iterator-range.cpp
===
--- clang/test/Analysis/iterator-range.cpp
+++ clang/test/Analysis/iterator-range.cpp
@@ -939,3 +939,10 @@
   auto i0 = c.begin(), i1 = c.end();
   ptrdiff_t len = i1 - i0; // no-crash
 }
+
+int uninit_var(int n) {
+  int uninit; // expected-note{{'uninit' declared without an initial value}}
+  return n - uninit; // no-crash
+  // expected-warning@-1 {{The right operand of '-' is a garbage value}}
+  // expected-note@-2 {{The right operand of '-' is a garbage value}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
@@ -228,7 +228,7 @@
 Value = State->getRawSVal(*ValAsLoc);
   }
 
-  if (Value.isUnknown())
+  if (Value.isUnknownOrUndef())
 return;
 
   // Incremention or decremention by 0 is never a bug.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D98552: [NFC] Adjust SmallVector.h header to workaround XL build compiler issue

2021-03-12 Thread 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 rG0bf2da53c12b: [NFC] Adjust SmallVector.h header to 
workaround XL build compiler issue (authored by xling-Liao 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98552

Files:
  clang/include/clang/Basic/LLVM.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -663,7 +663,7 @@
   // Generate arguments from the dummy invocation. If Generate is the
   // inverse of Parse, the newly generated arguments must have the same
   // semantics as the original.
-  SmallVector GeneratedArgs1;
+  SmallVector GeneratedArgs1;
   Generate(DummyInvocation, GeneratedArgs1, SA);
 
   // Run the second parse, now on the generated arguments, and with the real
@@ -683,7 +683,7 @@
 
   // Generate arguments again, this time from the options we will end up using
   // for the rest of the compilation.
-  SmallVector GeneratedArgs2;
+  SmallVector GeneratedArgs2;
   Generate(RealInvocation, GeneratedArgs2, SA);
 
   // Compares two lists of generated arguments.
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -1913,7 +1913,7 @@
 emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap,
  llvm::ArrayRef Args) {
   // Append the closure context to the argument.
-  llvm::SmallVector EffectiveArgs;
+  SmallVector EffectiveArgs;
   EffectiveArgs.reserve(Args.size() + 1);
   llvm::append_range(EffectiveArgs, Args);
   EffectiveArgs.push_back(Cap.second);
Index: clang/include/clang/Basic/LLVM.h
===
--- clang/include/clang/Basic/LLVM.h
+++ clang/include/clang/Basic/LLVM.h
@@ -22,6 +22,9 @@
 // None.h includes an enumerator that is desired & cannot be forward declared
 // without a definition of NoneType.
 #include "llvm/ADT/None.h"
+// Add this header as a workaround to prevent `too few template arguments for
+// class template 'SmallVector'` building error with build compilers like XL.
+#include "llvm/ADT/SmallVector.h"
 
 namespace llvm {
   // ADT's.


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -663,7 +663,7 @@
   // Generate arguments from the dummy invocation. If Generate is the
   // inverse of Parse, the newly generated arguments must have the same
   // semantics as the original.
-  SmallVector GeneratedArgs1;
+  SmallVector GeneratedArgs1;
   Generate(DummyInvocation, GeneratedArgs1, SA);
 
   // Run the second parse, now on the generated arguments, and with the real
@@ -683,7 +683,7 @@
 
   // Generate arguments again, this time from the options we will end up using
   // for the rest of the compilation.
-  SmallVector GeneratedArgs2;
+  SmallVector GeneratedArgs2;
   Generate(RealInvocation, GeneratedArgs2, SA);
 
   // Compares two lists of generated arguments.
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -1913,7 +1913,7 @@
 emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap,
  llvm::ArrayRef Args) {
   // Append the closure context to the argument.
-  llvm::SmallVector EffectiveArgs;
+  SmallVector EffectiveArgs;
   EffectiveArgs.reserve(Args.size() + 1);
   llvm::append_range(EffectiveArgs, Args);
   EffectiveArgs.push_back(Cap.second);
Index: clang/include/clang/Basic/LLVM.h
===
--- clang/include/clang/Basic/LLVM.h
+++ clang/include/clang/Basic/LLVM.h
@@ -22,6 +22,9 @@
 // None.h includes an enumerator that is desired & cannot be forward declared
 // without a definition of NoneType.
 #include "llvm/ADT/None.h"
+// Add this header as a workaround to prevent `too few template arguments for
+// class template 'SmallVector'` building error with build compilers like XL.
+#include "llvm/ADT/SmallVector.h"
 
 namespace llvm {
   // ADT's.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112420: [clang][ARM] PACBTI-M assembly support

2021-11-30 Thread 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 rG5cff77c23f43: [clang][ARM] PACBTI-M assembly support 
(authored by stuij, committed by Zeno ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112420

Files:
  clang/test/Driver/armv8.1m.main.c
  llvm/include/llvm/Support/ARMTargetParser.def
  llvm/include/llvm/Support/ARMTargetParser.h
  llvm/lib/Target/ARM/ARM.td
  llvm/lib/Target/ARM/ARMInstrThumb2.td
  llvm/lib/Target/ARM/ARMPredicates.td
  llvm/lib/Target/ARM/ARMRegisterInfo.td
  llvm/lib/Target/ARM/ARMSubtarget.h
  llvm/lib/Target/ARM/ARMSystemRegister.td
  llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
  llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp
  llvm/test/CodeGen/Thumb/high-reg-clobber.mir
  llvm/test/MC/ARM/armv8.1m-pacbti-error.s
  llvm/test/MC/ARM/armv8.1m-pacbti.s
  llvm/test/MC/ARM/implicit-it-generation-v8.s
  llvm/test/MC/Disassembler/ARM/armv8.1m-pacbti.txt

Index: llvm/test/MC/Disassembler/ARM/armv8.1m-pacbti.txt
===
--- /dev/null
+++ llvm/test/MC/Disassembler/ARM/armv8.1m-pacbti.txt
@@ -0,0 +1,137 @@
+# RUN: llvm-mc -triple thumbv8.1m.main-arm-none-eabi -mattr=+pacbti -disassemble %s 2> /dev/null | FileCheck %s
+
+0x51,0xfb,0x02,0x0f
+0x5e,0xfb,0x0d,0xcf
+0xaf,0xf3,0x2d,0x80
+0x51,0xfb,0x12,0x0f
+0xaf,0xf3,0x0f,0x80
+0x61,0xfb,0x02,0xf0
+0x6e,0xfb,0x0d,0xfc
+0xaf,0xf3,0x1d,0x80
+0xaf,0xf3,0x0d,0x80
+0x80,0xf3,0x20,0x88
+0x80,0xf3,0x21,0x88
+0x80,0xf3,0x22,0x88
+0x80,0xf3,0x23,0x88
+0x80,0xf3,0x24,0x88
+0x80,0xf3,0x25,0x88
+0x80,0xf3,0x26,0x88
+0x80,0xf3,0x27,0x88
+0x80,0xf3,0xa0,0x88
+0x80,0xf3,0xa1,0x88
+0x80,0xf3,0xa2,0x88
+0x80,0xf3,0xa3,0x88
+0x80,0xf3,0xa4,0x88
+0x80,0xf3,0xa5,0x88
+0x80,0xf3,0xa6,0x88
+0x80,0xf3,0xa7,0x88
+0xef,0xf3,0x20,0x80
+0xef,0xf3,0x21,0x80
+0xef,0xf3,0x22,0x80
+0xef,0xf3,0x23,0x80
+0xef,0xf3,0x24,0x80
+0xef,0xf3,0x25,0x80
+0xef,0xf3,0x26,0x80
+0xef,0xf3,0x27,0x80
+0xef,0xf3,0xa0,0x80
+0xef,0xf3,0xa1,0x80
+0xef,0xf3,0xa2,0x80
+0xef,0xf3,0xa3,0x80
+0xef,0xf3,0xa4,0x80
+0xef,0xf3,0xa5,0x80
+0xef,0xf3,0xa6,0x80
+0xef,0xf3,0xa7,0x80
+
+# Test softfail encodings
+0xa7,0xf3,0x1d,0x80
+0xab,0xf3,0x1d,0x80
+0xad,0xf3,0x1d,0x80
+0xae,0xf3,0x1d,0x80
+0xaf,0xf3,0x1d,0x88
+0xaf,0xf3,0x1d,0xa0
+0xaf,0xf3,0x2d,0x80
+0xab,0xf3,0x2d,0x80
+0xad,0xf3,0x2d,0x80
+0xae,0xf3,0x2d,0x80
+0xaf,0xf3,0x2d,0x88
+0xaf,0xf3,0x2d,0xa0
+0xa7,0xf3,0x0f,0x80
+0xab,0xf3,0x0f,0x80
+0xad,0xf3,0x0f,0x80
+0xae,0xf3,0x0f,0x80
+0xaf,0xf3,0x0f,0x88
+0xaf,0xf3,0x0f,0xa0
+0xa7,0xf3,0x0d,0x80
+0xab,0xf3,0x0d,0x80
+0xad,0xf3,0x0d,0x80
+0xae,0xf3,0x0d,0x80
+0xaf,0xf3,0x0d,0x88
+0xaf,0xf3,0x0d,0xa0
+
+# CHECK: autg	r0, r1, r2
+# CHECK: autg r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: bxautr0, r1, r2
+# CHECK: bti
+# CHECK: pacg	r0, r1, r2
+# CHECK: pacg	r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
+# CHECK: msr	pac_key_p_0, r0
+# CHECK: msr	pac_key_p_1, r0
+# CHECK: msr	pac_key_p_2, r0
+# CHECK: msr	pac_key_p_3, r0
+# CHECK: msr	pac_key_u_0, r0
+# CHECK: msr	pac_key_u_1, r0
+# CHECK: msr	pac_key_u_2, r0
+# CHECK: msr	pac_key_u_3, r0
+# CHECK: msr	pac_key_p_0_ns, r0
+# CHECK: msr	pac_key_p_1_ns, r0
+# CHECK: msr	pac_key_p_2_ns, r0
+# CHECK: msr	pac_key_p_3_ns, r0
+# CHECK: msr	pac_key_u_0_ns, r0
+# CHECK: msr	pac_key_u_1_ns, r0
+# CHECK: msr	pac_key_u_2_ns, r0
+# CHECK: msr	pac_key_u_3_ns, r0
+# CHECK: mrs	r0, pac_key_p_0
+# CHECK: mrs	r0, pac_key_p_1
+# CHECK: mrs	r0, pac_key_p_2
+# CHECK: mrs	r0, pac_key_p_3
+# CHECK: mrs	r0, pac_key_u_0
+# CHECK: mrs	r0, pac_key_u_1
+# CHECK: mrs	r0, pac_key_u_2
+# CHECK: mrs	r0, pac_key_u_3
+# CHECK: mrs	r0, pac_key_p_0_ns
+# CHECK: mrs	r0, pac_key_p_1_ns
+# CHECK: mrs	r0, pac_key_p_2_ns
+# CHECK: mrs	r0, pac_key_p_3_ns
+# CHECK: mrs	r0, pac_key_u_0_ns
+# CHECK: mrs	r0, pac_key_u_1_ns
+# CHECK: mrs	r0, pac_key_u_2_ns
+# CHECK: mrs	r0, pac_key_u_3_ns
+
+# Softfail encodings
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: bti
+# CHECK: bti
+# CHECK: bti
+# CHECK: bti
+# CHECK: bti
+# CHECK: bti
+# CHECK: pacbti   r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
Index: llvm/test/MC/ARM/implicit-it-generation-v8.s
===
--- /dev/null
+++ llvm/test/MC/ARM/implicit-it-generation-v8.s
@@ -0,0 +1,9 @@
+@ RUN: llvm-mc -triple thumbv8.1

[PATCH] D135908: [clang][LTO] Setting Desired Default AIX Debugging Options

2022-10-18 Thread 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 rG04615b695aad: [clang][LTO] Setting Desired Default AIX 
Debugging Options (authored by Qiongsi Wu ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135908

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/lto-aix.c


Index: clang/test/Driver/lto-aix.c
===
--- clang/test/Driver/lto-aix.c
+++ clang/test/Driver/lto-aix.c
@@ -4,3 +4,30 @@
 //
 // LTOPATH: "-bplugin:{{.*}}libLTO.{{so|dll|dylib}}"
 // MCPUOPTLEVEL: "-bplugin_opt:-mcpu={{.*}}" "-bplugin_opt:-O3"
+//
+// Test debugging options
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g 2>&1 \
+// RUN:   | FileCheck -check-prefixes=STRICT,NODEBUGGER-TUNE %s
+// RUN: %clang --target=powerpc64-ibm-aix-xcoff -### %s -flto -g 2>&1 \
+// RUN:   | FileCheck -check-prefixes=STRICT,NODEBUGGER-TUNE %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -gdbx 2>&1 \
+// RUN:   | FileCheck -check-prefix=DBX -check-prefix=STRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -ggdb 2>&1 \
+// RUN:   | FileCheck -check-prefix=GDB -check-prefix=STRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -ggdb0 2>&1 \
+// RUN:   | FileCheck -check-prefix=GDB -check-prefix=NOSTRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -ggdb1 2>&1 \
+// RUN:   | FileCheck -check-prefix=GDB -check-prefix=STRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -g0 2>&1 \
+// RUN:   | FileCheck -check-prefix=NOSTRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g 
-gno-strict-dwarf 2>&1 \
+// RUN:   | FileCheck -check-prefix=NOSTRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -gstrict-dwarf 
2>&1 \
+// RUN:   | FileCheck -check-prefix=NOSTRICT %s
+//
+// DBX:"-bplugin_opt:-debugger-tune=dbx"
+// GDB:"-bplugin_opt:-debugger-tune=gdb"
+// NODEBUGGER-TUNE-NOT: "-bplugin_opt:-debugger-tune="
+//
+// STRICT:   "-bplugin_opt:-strict-dwarf=true"
+// NOSTRICT-NOT: "-bplugin_opt:-strict-dwarf=true"
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -589,6 +589,18 @@
   Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb"));
   }
 
+  if (IsOSAIX) {
+// On AIX, clang assumes strict-dwarf is true if any debug option is
+// specified, unless it is told explicitly not to assume so.
+Arg *A = Args.getLastArg(options::OPT_g_Group);
+bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
+   !A->getOption().matches(options::OPT_ggdb0);
+if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf,
+options::OPT_gno_strict_dwarf, true))
+  CmdArgs.push_back(
+  Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
+  }
+
   bool UseSeparateSections =
   isUseSeparateSections(ToolChain.getEffectiveTriple());
 


Index: clang/test/Driver/lto-aix.c
===
--- clang/test/Driver/lto-aix.c
+++ clang/test/Driver/lto-aix.c
@@ -4,3 +4,30 @@
 //
 // LTOPATH: "-bplugin:{{.*}}libLTO.{{so|dll|dylib}}"
 // MCPUOPTLEVEL: "-bplugin_opt:-mcpu={{.*}}" "-bplugin_opt:-O3"
+//
+// Test debugging options
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g 2>&1 \
+// RUN:   | FileCheck -check-prefixes=STRICT,NODEBUGGER-TUNE %s
+// RUN: %clang --target=powerpc64-ibm-aix-xcoff -### %s -flto -g 2>&1 \
+// RUN:   | FileCheck -check-prefixes=STRICT,NODEBUGGER-TUNE %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -gdbx 2>&1 \
+// RUN:   | FileCheck -check-prefix=DBX -check-prefix=STRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -ggdb 2>&1 \
+// RUN:   | FileCheck -check-prefix=GDB -check-prefix=STRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -ggdb0 2>&1 \
+// RUN:   | FileCheck -check-prefix=GDB -check-prefix=NOSTRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -ggdb1 2>&1 \
+// RUN:   | FileCheck -check-prefix=GDB -check-prefix=STRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -g0 2>&1 \
+// RUN:   | FileCheck -check-prefix=NOSTRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g -gno-strict-dwarf 2>&1 \
+// RUN:   | FileCheck -check-prefix=NOSTRICT %s
+// RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -gstrict-dwarf 2>&1 \
+// RUN:   | FileCheck -check-prefix=NOSTRICT %s
+//
+// DBX:"-bplugin_opt:-debugger-tune=dbx"

[PATCH] D135695: [OMPIRBuilder] Support depend clause for task construct

2022-10-19 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG614958912784: [OMPIRBuilder] Support depend clause for task 
(authored by psoni2628, committed by Prabhdeep Singh Soni (A) 
).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135695

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPConstants.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp

Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -5092,6 +5092,81 @@
   EXPECT_FALSE(verifyModule(*M, &errs()));
 }
 
+TEST_F(OpenMPIRBuilderTest, CreateTaskDepend) {
+  using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.initialize();
+  F->setName("func");
+  IRBuilder<> Builder(BB);
+  auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {};
+  BasicBlock *AllocaBB = Builder.GetInsertBlock();
+  BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "alloca.split");
+  OpenMPIRBuilder::LocationDescription Loc(
+  InsertPointTy(BodyBB, BodyBB->getFirstInsertionPt()), DL);
+  AllocaInst *InDep = Builder.CreateAlloca(Type::getInt32Ty(M->getContext()));
+  OpenMPIRBuilder::DependData DDIn(RTLDependenceKindTy::DepIn,
+   Type::getInt32Ty(M->getContext()), InDep);
+  SmallVector DDS;
+  DDS.push_back(&DDIn);
+  Builder.restoreIP(OMPBuilder.createTask(
+  Loc, InsertPointTy(AllocaBB, AllocaBB->getFirstInsertionPt()), BodyGenCB,
+  /*Tied=*/false, /*Final*/ nullptr, /*IfCondition*/ nullptr, DDS));
+  OMPBuilder.finalize();
+  Builder.CreateRetVoid();
+
+  // Check for the `NumDeps` argument
+  CallInst *TaskAllocCall = dyn_cast(
+  OMPBuilder
+  .getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps)
+  ->user_back());
+  ASSERT_NE(TaskAllocCall, nullptr);
+  ConstantInt *NumDeps = dyn_cast(TaskAllocCall->getArgOperand(3));
+  ASSERT_NE(NumDeps, nullptr);
+  EXPECT_EQ(NumDeps->getZExtValue(), 1U);
+
+  // Check for the `DepInfo` array argument
+  BitCastInst *DepArrayPtr =
+  dyn_cast(TaskAllocCall->getOperand(4));
+  ASSERT_NE(DepArrayPtr, nullptr);
+  AllocaInst *DepArray = dyn_cast(DepArrayPtr->getOperand(0));
+  ASSERT_NE(DepArray, nullptr);
+  Value::user_iterator DepArrayI = DepArray->user_begin();
+  EXPECT_EQ(*DepArrayI, DepArrayPtr);
+  ++DepArrayI;
+  Value::user_iterator DepInfoI = DepArrayI->user_begin();
+  // Check for the `DependKind` flag in the `DepInfo` array
+  Value *Flag = findStoredValue(*DepInfoI);
+  ASSERT_NE(Flag, nullptr);
+  ConstantInt *FlagInt = dyn_cast(Flag);
+  ASSERT_NE(FlagInt, nullptr);
+  EXPECT_EQ(FlagInt->getZExtValue(),
+static_cast(RTLDependenceKindTy::DepIn));
+  ++DepInfoI;
+  // Check for the size in the `DepInfo` array
+  Value *Size = findStoredValue(*DepInfoI);
+  ASSERT_NE(Size, nullptr);
+  ConstantInt *SizeInt = dyn_cast(Size);
+  ASSERT_NE(SizeInt, nullptr);
+  EXPECT_EQ(SizeInt->getZExtValue(), 4U);
+  ++DepInfoI;
+  // Check for the variable address in the `DepInfo` array
+  Value *AddrStored = findStoredValue(*DepInfoI);
+  ASSERT_NE(AddrStored, nullptr);
+  PtrToIntInst *AddrInt = dyn_cast(AddrStored);
+  ASSERT_NE(AddrInt, nullptr);
+  Value *Addr = AddrInt->getPointerOperand();
+  EXPECT_EQ(Addr, InDep);
+
+  ConstantInt *NumDepsNoAlias =
+  dyn_cast(TaskAllocCall->getArgOperand(5));
+  ASSERT_NE(NumDepsNoAlias, nullptr);
+  EXPECT_EQ(NumDepsNoAlias->getZExtValue(), 0U);
+  EXPECT_EQ(TaskAllocCall->getOperand(6),
+ConstantPointerNull::get(Type::getInt8PtrTy(M->getContext(;
+
+  EXPECT_FALSE(verifyModule(*M, &errs()));
+}
+
 TEST_F(OpenMPIRBuilderTest, CreateTaskFinal) {
   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
   OpenMPIRBuilder OMPBuilder(*M);
Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -1290,7 +1290,8 @@
 OpenMPIRBuilder::InsertPointTy
 OpenMPIRBuilder::createTask(const LocationDescription &Loc,
 InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB,
-bool Tied, Value *Final, Value *IfCondition) {
+bool Tied, Value *Final, Value *IfCondition,
+ArrayRef Dependencies) {
   if (!updateToLocation(Loc))
 return InsertPointTy();
 
@@ -1322,8 +1323,8 @@
   OI.EntryBB = TaskAllocaBB;
   OI.OuterAllocaBB 

[PATCH] D136187: [clang][AIX] Omitting Explicit Debugger Tuning Option

2022-10-20 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf911598bd440: [clang][AIX] Omitting Explicit Debugger Tuning 
Option (authored by Qiongsi Wu ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136187

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/debug-options.c


Index: clang/test/Driver/debug-options.c
===
--- clang/test/Driver/debug-options.c
+++ clang/test/Driver/debug-options.c
@@ -116,11 +116,19 @@
 // RUN: %clang -### %s -g -target x86_64-scei-ps5 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
 
-// On the AIX, -g defaults to -gdbx and limited debug info.
+// On the AIX, -g defaults to limited debug info.
 // RUN: %clang -### -c -g %s -target powerpc-ibm-aix-xcoff 2>&1 \
-// RUN: | FileCheck -check-prefix=G_LIMITED -check-prefix=G_DBX %s
+// RUN: | FileCheck -check-prefix=G_LIMITED %s
 // RUN: %clang -### -c -g %s -target powerpc64-ibm-aix-xcoff 2>&1 \
-// RUN: | FileCheck -check-prefix=G_LIMITED -check-prefix=G_DBX %s
+// RUN: | FileCheck -check-prefix=G_LIMITED %s
+// RUN: %clang -### -c -g %s -target powerpc-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefix=G_NOTUNING %s
+// RUN: %clang -### -c -g %s -target powerpc64-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefix=G_NOTUNING %s
+// RUN: %clang -### -c -g -gdbx %s -target powerpc-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefixes=G_LIMITED,G_DBX %s
+// RUN: %clang -### -c -g -gdbx %s -target powerpc64-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefixes=G_LIMITED,G_DBX %s
 
 // For DBX, -g defaults to -gstrict-dwarf.
 // RUN: %clang -### -c -g %s -target powerpc-ibm-aix-xcoff 2>&1 \
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4187,8 +4187,10 @@
   }
 
   // If a debugger tuning argument appeared, remember it.
+  bool HasDebuggerTuning = false;
   if (const Arg *A =
   Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) 
{
+HasDebuggerTuning = true;
 if (checkDebugInfoOption(A, Args, D, TC)) {
   if (A->getOption().matches(options::OPT_glldb))
 DebuggerTuning = llvm::DebuggerKind::LLDB;
@@ -4364,8 +4366,12 @@
   // Adjust the debug info kind for the given toolchain.
   TC.adjustDebugInfoKind(DebugInfoKind, Args);
 
+  // On AIX, the debugger tuning option can be omitted if it is not explicitly
+  // set.
   RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
-  DebuggerTuning);
+  T.isOSAIX() && !HasDebuggerTuning
+  ? llvm::DebuggerKind::Default
+  : DebuggerTuning);
 
   // -fdebug-macro turns on macro debug info generation.
   if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,


Index: clang/test/Driver/debug-options.c
===
--- clang/test/Driver/debug-options.c
+++ clang/test/Driver/debug-options.c
@@ -116,11 +116,19 @@
 // RUN: %clang -### %s -g -target x86_64-scei-ps5 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
 
-// On the AIX, -g defaults to -gdbx and limited debug info.
+// On the AIX, -g defaults to limited debug info.
 // RUN: %clang -### -c -g %s -target powerpc-ibm-aix-xcoff 2>&1 \
-// RUN: | FileCheck -check-prefix=G_LIMITED -check-prefix=G_DBX %s
+// RUN: | FileCheck -check-prefix=G_LIMITED %s
 // RUN: %clang -### -c -g %s -target powerpc64-ibm-aix-xcoff 2>&1 \
-// RUN: | FileCheck -check-prefix=G_LIMITED -check-prefix=G_DBX %s
+// RUN: | FileCheck -check-prefix=G_LIMITED %s
+// RUN: %clang -### -c -g %s -target powerpc-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefix=G_NOTUNING %s
+// RUN: %clang -### -c -g %s -target powerpc64-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefix=G_NOTUNING %s
+// RUN: %clang -### -c -g -gdbx %s -target powerpc-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefixes=G_LIMITED,G_DBX %s
+// RUN: %clang -### -c -g -gdbx %s -target powerpc64-ibm-aix-xcoff 2>&1 \
+// RUN: | FileCheck -check-prefixes=G_LIMITED,G_DBX %s
 
 // For DBX, -g defaults to -gstrict-dwarf.
 // RUN: %clang -### -c -g %s -target powerpc-ibm-aix-xcoff 2>&1 \
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4187,8 +4187,10 @@
   }
 
   // If a debugger tuning argument appeared, 

[PATCH] D135885: [clang][LTO][NFC] Adding More Tests for AIX Options

2022-10-22 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbdd11bbace5e: [clang][LTO][NFC] Adding More Tests for AIX 
Options (authored by Qiongsi Wu ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135885

Files:
  clang/test/Driver/lto-aix.c


Index: clang/test/Driver/lto-aix.c
===
--- clang/test/Driver/lto-aix.c
+++ clang/test/Driver/lto-aix.c
@@ -5,7 +5,33 @@
 // LTOPATH: "-bplugin:{{.*}}libLTO.{{so|dll|dylib}}"
 // MCPUOPTLEVEL: "-bplugin_opt:-mcpu={{.*}}" "-bplugin_opt:-O3"
 //
+// More opt level option tests
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O1 -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Og -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O2 -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Os -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Oz -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O3 -### 2>&1 | FileCheck --check-prefix=O3 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Ofast -### 2>&1 | FileCheck --check-prefix=O3 %s
+//
+// O1: "-bplugin_opt:-O1"
+// O2: "-bplugin_opt:-O2"
+// O3: "-bplugin_opt:-O3"
+//
 // Test debugging options
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -gdbx 2>&1 \
+// RUN:   | FileCheck -check-prefix=DBX %s
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -g 2>&1 \
+// RUN:   | FileCheck -check-prefix=NODEBUGGER-TUNE %s
 // RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g 2>&1 \
 // RUN:   | FileCheck -check-prefixes=STRICT,NODEBUGGER-TUNE %s
 // RUN: %clang --target=powerpc64-ibm-aix-xcoff -### %s -flto -g 2>&1 \


Index: clang/test/Driver/lto-aix.c
===
--- clang/test/Driver/lto-aix.c
+++ clang/test/Driver/lto-aix.c
@@ -5,7 +5,33 @@
 // LTOPATH: "-bplugin:{{.*}}libLTO.{{so|dll|dylib}}"
 // MCPUOPTLEVEL: "-bplugin_opt:-mcpu={{.*}}" "-bplugin_opt:-O3"
 //
+// More opt level option tests
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O1 -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Og -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O2 -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Os -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Oz -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -O3 -### 2>&1 | FileCheck --check-prefix=O3 %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -Ofast -### 2>&1 | FileCheck --check-prefix=O3 %s
+//
+// O1: "-bplugin_opt:-O1"
+// O2: "-bplugin_opt:-O2"
+// O3: "-bplugin_opt:-O3"
+//
 // Test debugging options
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -gdbx 2>&1 \
+// RUN:   | FileCheck -check-prefix=DBX %s
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -g 2>&1 \
+// RUN:   | FileCheck -check-prefix=NODEBUGGER-TUNE %s
 // RUN: %clang --target=powerpc-ibm-aix-xcoff -### %s -flto -g 2>&1 \
 // RUN:   | FileCheck -check-prefixes=STRICT,NODEBUGGER-TUNE %s
 // RUN: %clang --target=powerpc64-ibm-aix-xcoff -### %s -flto -g 2>&1 \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136604: Add clang_CXXMethod_isCopyAssignmentOperator to libclang

2022-10-26 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG476a497f729a: Add clang_CXXMethod_isCopyAssignmentOperator 
to libclang (authored by diseraluca, committed by Luca Di Sera 
).

Changed prior to commit:
  https://reviews.llvm.org/D136604?vs=470151&id=471020#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136604

Files:
  clang/bindings/python/clang/cindex.py
  clang/docs/ReleaseNotes.rst
  clang/include/clang-c/Index.h
  clang/test/Index/copy-assignment-operator.cpp
  clang/test/Index/get-cursor.cpp
  clang/tools/c-index-test/c-index-test.c
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/libclang.map

Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -410,6 +410,7 @@
 clang_getUnqualifiedType;
 clang_getNonReferenceType;
 clang_CXXMethod_isDeleted;
+clang_CXXMethod_isCopyAssignmentOperator;
 };
 
 # Example of how to add a new symbol version entry.  If you do add a new symbol
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -8899,6 +8899,17 @@
   return (Method && Method->isVirtual()) ? 1 : 0;
 }
 
+unsigned clang_CXXMethod_isCopyAssignmentOperator(CXCursor C) {
+  if (!clang_isDeclaration(C.kind))
+return 0;
+
+  const Decl *D = cxcursor::getCursorDecl(C);
+  const CXXMethodDecl *Method =
+  D ? dyn_cast_or_null(D->getAsFunction()) : nullptr;
+
+  return (Method && Method->isCopyAssignmentOperator()) ? 1 : 0;
+}
+
 unsigned clang_CXXRecord_isAbstract(CXCursor C) {
   if (!clang_isDeclaration(C.kind))
 return 0;
Index: clang/tools/c-index-test/c-index-test.c
===
--- clang/tools/c-index-test/c-index-test.c
+++ clang/tools/c-index-test/c-index-test.c
@@ -910,6 +910,8 @@
   printf(" (const)");
 if (clang_CXXMethod_isPureVirtual(Cursor))
   printf(" (pure)");
+if (clang_CXXMethod_isCopyAssignmentOperator(Cursor))
+  printf(" (copy-assignment operator)");
 if (clang_CXXRecord_isAbstract(Cursor))
   printf(" (abstract)");
 if (clang_EnumDecl_isScoped(Cursor))
Index: clang/test/Index/get-cursor.cpp
===
--- clang/test/Index/get-cursor.cpp
+++ clang/test/Index/get-cursor.cpp
@@ -226,7 +226,7 @@
 // RUN: c-index-test -cursor-at=%s:69:3 -cursor-at=%s:70:11 -cursor-at=%s:73:6 -cursor-at=%s:74:6 -cursor-at=%s:77:8 -cursor-at=%s:78:8 -cursor-at=%s:79:8 -cursor-at=%s:80:8 -cursor-at=%s:81:8 -cursor-at=%s:82:8 -cursor-at=%s:85:6 -cursor-at=%s:86:6 -cursor-at=%s:87:6 -cursor-at=%s:88:6 -cursor-at=%s:91:5 -cursor-at=%s:92:5 -cursor-at=%s:93:5 -cursor-at=%s:94:5 -cursor-at=%s:95:5 -cursor-at=%s:96:5 -cursor-at=%s:97:5 -cursor-at=%s:98:5 -cursor-at=%s:100:5 -cursor-at=%s:101:5 -cursor-at=%s:104:6 -cursor-at=%s:105:6 -cursor-at=%s:106:6 -cursor-at=%s:107:6 -cursor-at=%s:108:6 -cursor-at=%s:109:6 -cursor-at=%s:110:6 -cursor-at=%s:111:6 -cursor-at=%s:113:6 -cursor-at=%s:114:6 -cursor-at=%s:117:8 -cursor-at=%s:118:8 -cursor-at=%s:120:8 -cursor-at=%s:121:8 -cursor-at=%s:122:8 -cursor-at=%s:123:8 -cursor-at=%s:124:8 -cursor-at=%s:125:8 -cursor-at=%s:128:6 -cursor-at=%s:129:6 -cursor-at=%s:130:6 -cursor-at=%s:132:3 -cursor-at=%s:146:15 -cursor-at=%s:149:6 -cursor-at=%s:150:25 -cursor-at=%s:151:6 -cursor-at=%s:152:6 -cursor-at=%s:153:6 -cursor-at=%s:154:6 -cursor-at=%s:155:6 -std=c++11 %s | FileCheck -check-prefix=CHECK-SPELLING %s
 // CHECK-SPELLING: 69:3 CXXConstructor=A:69:3 (default constructor) Extent=[69:3 - 69:6] Spelling=A ([69:3 - 69:4])
 // CHECK-SPELLING: 70:11 CXXDestructor=~A:70:11 (virtual) Extent=[70:3 - 70:15] Spelling=~A ([70:11 - 70:13])
-// CHECK-SPELLING: 73:6 CXXMethod=operator=:73:6 Extent=[73:3 - 73:25] Spelling=operator= ([73:6 - 73:15])
+// CHECK-SPELLING: 73:6 CXXMethod=operator=:73:6 (copy-assignment operator) Extent=[73:3 - 73:25] Spelling=operator= ([73:6 - 73:15])
 // CHECK-SPELLING: 74:6 CXXMethod=operator=:74:6 (noexcept) Extent=[74:3 - 74:29] Spelling=operator= ([74:6 - 74:15])
 // CHECK-SPELLING: 77:8 CXXMethod=operator+:77:8 (const) Extent=[77:3 - 77:25] Spelling=operator+ ([77:8 - 77:17])
 // CHECK-SPELLING: 78:8 CXXMethod=operator-:78:8 (const) Extent=[78:3 - 78:25] Spelling=operator- ([78:8 - 78:17])
Index: clang/test/Index/copy-assignment-operator.cpp
===
--- /dev/null
+++ clang/test/Index/copy-assignment-operator.cpp
@@ -0,0 +1,47 @@
+struct Foo {
+// Those are copy-assignment operators
+bool operator=(const Foo&);
+bool operator=(Foo&);
+bool operator=(volatile Foo&);
+bool operator=(const volatile Foo&)

[PATCH] D136874: [clang][LTO] Passing vec-extabi to the Backend on AIX

2022-10-28 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfd448bbedce9: [clang][LTO] Passing vec-extabi to the Backend 
on AIX (authored by Qiongsi Wu ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136874

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/lto-aix.c


Index: clang/test/Driver/lto-aix.c
===
--- clang/test/Driver/lto-aix.c
+++ clang/test/Driver/lto-aix.c
@@ -27,6 +27,16 @@
 // O2: "-bplugin_opt:-O2"
 // O3: "-bplugin_opt:-O3"
 //
+// vec-extabi option
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -mabi=vec-extabi -### 2>&1 \
+// RUN:   | FileCheck --check-prefix=VECEXTABI %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -### 2>&1 | FileCheck --check-prefix=NOVECEXTABI %s
+//
+// VECEXTABI: "-bplugin_opt:-vec-extabi"
+// NOVECEXTABI-NOT: "-bplugin_opt:-vec-extabi"
+//
 // Test debugging options
 // RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -gdbx 2>&1 \
 // RUN:   | FileCheck -check-prefix=DBX %s
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -599,6 +599,10 @@
 options::OPT_gno_strict_dwarf, true))
   CmdArgs.push_back(
   Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
+
+if (Args.getLastArg(options::OPT_mabi_EQ_vec_extabi))
+  CmdArgs.push_back(
+  Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi"));
   }
 
   bool UseSeparateSections =


Index: clang/test/Driver/lto-aix.c
===
--- clang/test/Driver/lto-aix.c
+++ clang/test/Driver/lto-aix.c
@@ -27,6 +27,16 @@
 // O2: "-bplugin_opt:-O2"
 // O3: "-bplugin_opt:-O3"
 //
+// vec-extabi option
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -mabi=vec-extabi -### 2>&1 \
+// RUN:   | FileCheck --check-prefix=VECEXTABI %s
+// RUN: %clang --target=powerpc-ibm-aix --sysroot %S/Inputs/aix_ppc_tree %s \
+// RUN:   -fuse-ld=ld -flto -### 2>&1 | FileCheck --check-prefix=NOVECEXTABI %s
+//
+// VECEXTABI: "-bplugin_opt:-vec-extabi"
+// NOVECEXTABI-NOT: "-bplugin_opt:-vec-extabi"
+//
 // Test debugging options
 // RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -gdbx 2>&1 \
 // RUN:   | FileCheck -check-prefix=DBX %s
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -599,6 +599,10 @@
 options::OPT_gno_strict_dwarf, true))
   CmdArgs.push_back(
   Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
+
+if (Args.getLastArg(options::OPT_mabi_EQ_vec_extabi))
+  CmdArgs.push_back(
+  Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi"));
   }
 
   bool UseSeparateSections =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131750: [clang-format] Distinguish logical and after bracket from reference

2022-08-12 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGef71383b0cfb: [clang-format] Distinguish logical and after 
bracket from reference (authored by jackh ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131750

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -88,6 +88,10 @@
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
 
+  Tokens = annotate("bool b = 3 == int{3} && true;\n");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::ampamp, TT_BinaryOperator);
+
   Tokens = annotate("struct {\n"
 "} *ptr;");
   EXPECT_EQ(Tokens.size(), 7u) << Tokens;
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10474,6 +10474,7 @@
   verifyFormat("class {\n"
"}&& ptr = {};",
Style);
+  verifyFormat("bool b = 3 == int{3} && true;");
 
   Style.PointerAlignment = FormatStyle::PAS_Middle;
   verifyFormat("struct {\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2365,25 +2365,6 @@
 !PrevToken->MatchingParen)
   return TT_PointerOrReference;
 
-// For "} &&"
-if (PrevToken->is(tok::r_brace) && Tok.is(tok::ampamp)) {
-  const FormatToken *MatchingLBrace = PrevToken->MatchingParen;
-
-  // We check whether there is a TemplateCloser(">") to indicate it's a
-  // template or not. If it's not a template, "&&" is likely a reference
-  // operator.
-  //   struct {} &&ref = {};
-  if (!MatchingLBrace)
-return TT_PointerOrReference;
-  FormatToken *BeforeLBrace = MatchingLBrace->getPreviousNonComment();
-  if (!BeforeLBrace || BeforeLBrace->isNot(TT_TemplateCloser))
-return TT_PointerOrReference;
-
-  // If it is a template, "&&" is a binary operator.
-  //   enable_if<>{} && ...
-  return TT_BinaryOperator;
-}
-
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
tok::kw_false, tok::r_brace)) {


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -88,6 +88,10 @@
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
 
+  Tokens = annotate("bool b = 3 == int{3} && true;\n");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::ampamp, TT_BinaryOperator);
+
   Tokens = annotate("struct {\n"
 "} *ptr;");
   EXPECT_EQ(Tokens.size(), 7u) << Tokens;
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10474,6 +10474,7 @@
   verifyFormat("class {\n"
"}&& ptr = {};",
Style);
+  verifyFormat("bool b = 3 == int{3} && true;");
 
   Style.PointerAlignment = FormatStyle::PAS_Middle;
   verifyFormat("struct {\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2365,25 +2365,6 @@
 !PrevToken->MatchingParen)
   return TT_PointerOrReference;
 
-// For "} &&"
-if (PrevToken->is(tok::r_brace) && Tok.is(tok::ampamp)) {
-  const FormatToken *MatchingLBrace = PrevToken->MatchingParen;
-
-  // We check whether there is a TemplateCloser(">") to indicate it's a
-  // template or not. If it's not a template, "&&" is likely a reference
-  // operator.
-  //   struct {} &&ref = {};
-  if (!MatchingLBrace)
-return TT_PointerOrReference;
-  FormatToken *BeforeLBrace = MatchingLBrace->getPreviousNonComment();
-  if (!BeforeLBrace || BeforeLBrace->isNot(TT_TemplateCloser))
-return TT_PointerOrReference;
-
-  // If it is a template, "&&" is a binary operator.
-  //   enable_if<>{} && ...
-  return TT_BinaryOperator;
-}
-
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
tok::kw_fa

[PATCH] D134284: [AIX] change "llvm-nm" to "env OBJECT_MODE=any llvm-nm" in clang/test for AIX OS

2022-09-21 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd47f0be0e82b: [AIX] change "llvm-nm" to "env 
OBJECT_MODE=any llvm-nm" in clang/test for AIX OS (authored by zhijian 
).

Changed prior to commit:
  https://reviews.llvm.org/D134284?vs=461598&id=461879#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134284

Files:
  clang/test/lit.cfg.py


Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -276,3 +276,13 @@
 config.environment['AIXTHREAD_STK'] = os.environ['AIXTHREAD_STK']
 elif platform.system() == 'AIX':
 config.environment['AIXTHREAD_STK'] = '4194304'
+
+# The llvm-nm tool supports an environment variable "OBJECT_MODE" on AIX OS, 
which
+# controls the kind of objects they will support. If there is no "OBJECT_MODE"
+# environment variable specified, the default behaviour is to support 32-bit
+# objects only. In order to not affect most test cases, which expect to support
+# 32-bit and 64-bit objects by default, set the environment variable
+# "OBJECT_MODE" to 'any' for llvm-nm on AIX OS.
+
+if 'system-aix' in config.available_features:
+config.substitutions.append(('llvm-nm', 'env OBJECT_MODE=any llvm-nm'))


Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -276,3 +276,13 @@
 config.environment['AIXTHREAD_STK'] = os.environ['AIXTHREAD_STK']
 elif platform.system() == 'AIX':
 config.environment['AIXTHREAD_STK'] = '4194304'
+
+# The llvm-nm tool supports an environment variable "OBJECT_MODE" on AIX OS, which
+# controls the kind of objects they will support. If there is no "OBJECT_MODE"
+# environment variable specified, the default behaviour is to support 32-bit
+# objects only. In order to not affect most test cases, which expect to support
+# 32-bit and 64-bit objects by default, set the environment variable
+# "OBJECT_MODE" to 'any' for llvm-nm on AIX OS.
+
+if 'system-aix' in config.available_features:
+config.substitutions.append(('llvm-nm', 'env OBJECT_MODE=any llvm-nm'))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D134668: [LTO][clang] Using Single Dash Consistently when Passing LTO Options

2022-09-27 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG86cd3535206d: [LTO][clang] Using Single Dash Consistently 
when Passing LTO Options (authored by Qiongsi Wu 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134668

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/opt-record.c

Index: clang/test/Driver/opt-record.c
===
--- clang/test/Driver/opt-record.c
+++ clang/test/Driver/opt-record.c
@@ -53,28 +53,28 @@
 // RUN: %clang -target x86_64-linux -### -o FOO -fuse-ld=lld -flto=thin -fdiagnostics-hotness-threshold=100 -Rpass=inline -Rpass-missed=inline -Rpass-analysis=inline %s 2>&1 | FileCheck %s -check-prefix=CHECK-PASS-RPASS
 // RUN: %clang -target x86_64-linux -### -o FOO -fuse-ld=lld -flto=thin -fdiagnostics-hotness-threshold=auto -Rpass=inline -Rpass-missed=inline -Rpass-analysis=inline %s 2>&1 | FileCheck %s -check-prefix=CHECK-PASS-AUTO
 
-// CHECK-NOPASS-NOT: "--plugin-opt=opt-remarks-filename="
-// CHECK-NOPASS-NOT: "--plugin-opt=opt-remarks-passes=inline"
-// CHECK-NOPASS-NOT: "--plugin-opt=opt-remarks-format=yaml"
-// CHECK-NOPASS-NOT: "--plugin-opt=opt-remarks-hotness-threshold=100"
-
-// CHECK-PASS-A:  "--plugin-opt=opt-remarks-filename=a.out.opt.ld.yaml"
-// CHECK-PASS-A-SAME: "--plugin-opt=opt-remarks-passes=inline"
-// CHECK-PASS-A-SAME: "--plugin-opt=opt-remarks-format=yaml"
-// CHECK-PASS-A-SAME: "--plugin-opt=opt-remarks-hotness-threshold=100"
-
-// CHECK-PASS:  "--plugin-opt=opt-remarks-filename=FOO.opt.ld.yaml"
-// CHECK-PASS-SAME: "--plugin-opt=opt-remarks-passes=inline"
-// CHECK-PASS-SAME: "--plugin-opt=opt-remarks-format=yaml"
-// CHECK-PASS-SAME: "--plugin-opt=opt-remarks-hotness-threshold=100"
-
-// CHECK-PASS-CUSTOM:  "--plugin-opt=opt-remarks-filename=FOO.txt.opt.ld.some-format"
-// CHECK-PASS-CUSTOM-SAME: "--plugin-opt=opt-remarks-format=some-format"
-// CHECK-PASS-CUSTOM-SAME: "--plugin-opt=opt-remarks-hotness-threshold=100"
-
-// CHECK-PASS-RPASS:  "--plugin-opt=-pass-remarks=inline"
-// CHECK-PASS-RPASS-SAME: "--plugin-opt=-pass-remarks-missed=inline"
-// CHECK-PASS-RPASS-SAME: "--plugin-opt=-pass-remarks-analysis=inline"
-// CHECK-PASS-RPASS-SAME: "--plugin-opt=opt-remarks-hotness-threshold=100"
-
-// CHECK-PASS-AUTO:   "--plugin-opt=opt-remarks-hotness-threshold=auto"
+// CHECK-NOPASS-NOT: "-plugin-opt=opt-remarks-filename="
+// CHECK-NOPASS-NOT: "-plugin-opt=opt-remarks-passes=inline"
+// CHECK-NOPASS-NOT: "-plugin-opt=opt-remarks-format=yaml"
+// CHECK-NOPASS-NOT: "-plugin-opt=opt-remarks-hotness-threshold=100"
+
+// CHECK-PASS-A:  "-plugin-opt=opt-remarks-filename=a.out.opt.ld.yaml"
+// CHECK-PASS-A-SAME: "-plugin-opt=opt-remarks-passes=inline"
+// CHECK-PASS-A-SAME: "-plugin-opt=opt-remarks-format=yaml"
+// CHECK-PASS-A-SAME: "-plugin-opt=opt-remarks-hotness-threshold=100"
+
+// CHECK-PASS:  "-plugin-opt=opt-remarks-filename=FOO.opt.ld.yaml"
+// CHECK-PASS-SAME: "-plugin-opt=opt-remarks-passes=inline"
+// CHECK-PASS-SAME: "-plugin-opt=opt-remarks-format=yaml"
+// CHECK-PASS-SAME: "-plugin-opt=opt-remarks-hotness-threshold=100"
+
+// CHECK-PASS-CUSTOM:  "-plugin-opt=opt-remarks-filename=FOO.txt.opt.ld.some-format"
+// CHECK-PASS-CUSTOM-SAME: "-plugin-opt=opt-remarks-format=some-format"
+// CHECK-PASS-CUSTOM-SAME: "-plugin-opt=opt-remarks-hotness-threshold=100"
+
+// CHECK-PASS-RPASS:  "-plugin-opt=-pass-remarks=inline"
+// CHECK-PASS-RPASS-SAME: "-plugin-opt=-pass-remarks-missed=inline"
+// CHECK-PASS-RPASS-SAME: "-plugin-opt=-pass-remarks-analysis=inline"
+// CHECK-PASS-RPASS-SAME: "-plugin-opt=opt-remarks-hotness-threshold=100"
+
+// CHECK-PASS-AUTO:   "-plugin-opt=opt-remarks-hotness-threshold=auto"
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -67,16 +67,16 @@
 
 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
-CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
+CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=-pass-remarks=") +
  A->getValue()));
 
   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
 CmdArgs.push_back(Args.MakeArgString(
-Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
+Twine("-plugin-opt=-pass-remarks-missed=") + A->getValue()));
 
   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
 CmdArgs.push_back(Args.MakeArgString(
-Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
+Twine("-plugin-opt=-pass-remarks-analysis=") + A->getValue

[PATCH] D134042: [clang-format] Fix alignment in #else preprocessor blocks

2022-09-27 Thread 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 rGc0779756a0c4: [clang-format] Fix alignment in #else 
preprocessor blocks (authored by mitchell 
<56368743+mitchell-stel...@users.noreply.github.com>).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134042

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -5825,6 +5825,98 @@
Style);
 }
 
+TEST_F(FormatTest, FormatAlignInsidePreprocessorElseBlock) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveAssignments.Enabled = true;
+  Style.AlignConsecutiveDeclarations.Enabled = true;
+
+  // Test with just #if blocks.
+  verifyFormat("void f1() {\n"
+   "#if 1\n"
+   "  int foo= 1;\n"
+   "  int foobar = 2;\n"
+   "#endif\n"
+   "}\n"
+   "#if 1\n"
+   "int baz = 3;\n"
+   "#endif\n"
+   "void f2() {\n"
+   "#if 1\n"
+   "  char *foobarbaz = \"foobarbaz\";\n"
+   "  int   quux  = 4;\n"
+   "}",
+   Style);
+
+  // Test with just #else blocks.
+  verifyFormat("void f1() {\n"
+   "#if 1\n"
+   "#else\n"
+   "  int foo= 1;\n"
+   "  int foobar = 2;\n"
+   "#endif\n"
+   "}\n"
+   "#if 1\n"
+   "#else\n"
+   "int baz = 3;\n"
+   "#endif\n"
+   "void f2() {\n"
+   "#if 1\n"
+   "#else\n"
+   "  char *foobarbaz = \"foobarbaz\";\n"
+   "  int   quux  = 4;\n"
+   "}",
+   Style);
+
+  // Test with a mix of #if and #else blocks.
+  verifyFormat("void f1() {\n"
+   "#if 1\n"
+   "#else\n"
+   "  int foo= 1;\n"
+   "  int foobar = 2;\n"
+   "#endif\n"
+   "}\n"
+   "#if 1\n"
+   "int baz = 3;\n"
+   "#endif\n"
+   "void f2() {\n"
+   "#if 1\n"
+   "#else\n"
+   "  // prevent alignment with #else in f1\n"
+   "  char *foobarbaz = \"foobarbaz\";\n"
+   "  int   quux  = 4;\n"
+   "}",
+   Style);
+
+  // Test with nested #if and #else blocks.
+  verifyFormat("void f1() {\n"
+   "#if 1\n"
+   "#else\n"
+   "#if 2\n"
+   "#else\n"
+   "  int foo= 1;\n"
+   "  int foobar = 2;\n"
+   "#endif\n"
+   "#endif\n"
+   "}\n"
+   "#if 1\n"
+   "#else\n"
+   "#if 2\n"
+   "int baz = 3;\n"
+   "#endif\n"
+   "#endif\n"
+   "void f2() {\n"
+   "#if 1\n"
+   "#if 2\n"
+   "#else\n"
+   "  // prevent alignment with #else in f1\n"
+   "  char *foobarbaz = \"foobarbaz\";\n"
+   "  int   quux  = 4;\n"
+   "#endif\n"
+   "#endif\n"
+   "}",
+   Style);
+}
+
 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
   verifyFormat("{\n  { a #c; }\n}");
 }
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -522,6 +522,13 @@
? Changes[StartAt].indentAndNestingLevel()
: std::tuple();
 
+  // Keep track if the first token has a non-zero indent and nesting level.
+  // This can happen when aligning the contents of "#else" preprocessor blocks,
+  // which is done separately.
+  bool HasInitialIndentAndNesting =
+  StartAt == 0 &&
+  IndentAndNestingLevel > std::tuple();
+
   // Keep track of the number of commas before the matching tokens, we will only
   // align a sequence of matching tokens if they are preceded by the same number
   // of commas.
@@ -556,8 +563,19 @@
 
   unsigned i = StartAt;
   for (unsigned e = Changes.size(); i != e; ++i) {
-if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel)
-  break;
+if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel) {
+  if (!HasInitialIndentAndNesting)
+break;
+  // The contents of preprocessor blocks are aligned separately.
+  // If the initial preprocessor block is indented or nested (e.g. it's in
+  // a function), do not alig

[PATCH] D135400: [clang][LTO] Remove the use of `--` for arange option

2022-10-06 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb924c8c71daa: [clang][LTO] Remove the use of `--` for arange 
option (authored by Qiongsi Wu ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135400

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/debug-options-aranges.c


Index: clang/test/Driver/debug-options-aranges.c
===
--- clang/test/Driver/debug-options-aranges.c
+++ clang/test/Driver/debug-options-aranges.c
@@ -3,4 +3,4 @@
 /// Check that the linker plugin will get -generate-arange-section.
 // RUN: %clang -### -g --target=x86_64-linux -flto  -gdwarf-aranges %s 
2>&1 | FileCheck %s
 // RUN: %clang -### -g --target=x86_64-linux -flto=thin -gdwarf-aranges %s 
2>&1 | FileCheck %s
-// CHECK: --plugin-opt=-generate-arange-section
+// CHECK: "-plugin-opt=-generate-arange-section"
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -514,7 +514,7 @@
   // the way out.
   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
 CmdArgs.push_back(
-Args.MakeArgString("--plugin-opt=-generate-arange-section"));
+Args.MakeArgString("-plugin-opt=-generate-arange-section"));
   }
 
   // Try to pass driver level flags relevant to LTO code generation down to


Index: clang/test/Driver/debug-options-aranges.c
===
--- clang/test/Driver/debug-options-aranges.c
+++ clang/test/Driver/debug-options-aranges.c
@@ -3,4 +3,4 @@
 /// Check that the linker plugin will get -generate-arange-section.
 // RUN: %clang -### -g --target=x86_64-linux -flto  -gdwarf-aranges %s 2>&1 | FileCheck %s
 // RUN: %clang -### -g --target=x86_64-linux -flto=thin -gdwarf-aranges %s 2>&1 | FileCheck %s
-// CHECK: --plugin-opt=-generate-arange-section
+// CHECK: "-plugin-opt=-generate-arange-section"
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -514,7 +514,7 @@
   // the way out.
   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
 CmdArgs.push_back(
-Args.MakeArgString("--plugin-opt=-generate-arange-section"));
+Args.MakeArgString("-plugin-opt=-generate-arange-section"));
   }
 
   // Try to pass driver level flags relevant to LTO code generation down to
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D134820: [LTO][clang] Teaching Clang to Pass Plugin Options to the AIX Linker

2022-10-12 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGec94f372d1c1: [LTO][clang] Teaching Clang to Pass Plugin 
Options to the AIX Linker (authored by Qiongsi Wu ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134820

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/lib/Driver/ToolChains/AIX.h
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/test/Driver/lto-aix.c

Index: clang/test/Driver/lto-aix.c
===
--- /dev/null
+++ clang/test/Driver/lto-aix.c
@@ -0,0 +1,6 @@
+// Test LTO path, mcpu and opt level options
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fuse-ld=ld -O3 2>&1 \
+// RUN:   | FileCheck -check-prefixes=LTOPATH,MCPUOPTLEVEL %s
+//
+// LTOPATH: "-bplugin:{{.*}}libLTO.{{so|dll|dylib}}"
+// MCPUOPTLEVEL: "-bplugin_opt:-mcpu={{.*}}" "-bplugin_opt:-O3"
Index: clang/lib/Driver/ToolChains/CommonArgs.h
===
--- clang/lib/Driver/ToolChains/CommonArgs.h
+++ clang/lib/Driver/ToolChains/CommonArgs.h
@@ -190,7 +190,8 @@
  Multilib::flags_list &Flags);
 
 void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args,
-   llvm::opt::ArgStringList &CmdArgs, bool IsLTO);
+   llvm::opt::ArgStringList &CmdArgs, bool IsLTO,
+   const StringRef PluginOptPrefix = "");
 
 void checkAMDGPUCodeObjectVersion(const Driver &D,
   const llvm::opt::ArgList &Args);
@@ -203,7 +204,8 @@
 
 void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args,
 llvm::opt::ArgStringList &CmdArgs,
-const llvm::Triple &Triple, bool IsLTO);
+const llvm::Triple &Triple, bool IsLTO,
+const StringRef PluginOptPrefix = "");
 
 void addOpenMPDeviceRTL(const Driver &D, const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args,
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -65,24 +65,26 @@
 using namespace clang;
 using namespace llvm::opt;
 
-static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
+static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs,
+   const StringRef PluginOptPrefix) {
   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
-CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=-pass-remarks=") +
- A->getValue()));
+CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
+ "-pass-remarks=" + A->getValue()));
 
   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
 CmdArgs.push_back(Args.MakeArgString(
-Twine("-plugin-opt=-pass-remarks-missed=") + A->getValue()));
+Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue()));
 
   if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
 CmdArgs.push_back(Args.MakeArgString(
-Twine("-plugin-opt=-pass-remarks-analysis=") + A->getValue()));
+Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue()));
 }
 
 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
  const llvm::Triple &Triple,
  const InputInfo &Input,
- const InputInfo &Output) {
+ const InputInfo &Output,
+ const StringRef PluginOptPrefix) {
   StringRef Format = "yaml";
   if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
 Format = A->getValue();
@@ -96,29 +98,32 @@
 
   assert(!F.empty() && "Cannot determine remarks output name.");
   // Append "opt.ld." to the end of the file name.
-  CmdArgs.push_back(
-  Args.MakeArgString(Twine("-plugin-opt=opt-remarks-filename=") + F +
- Twine(".opt.ld.") + Format));
+  CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
+   "opt-remarks-filename=" + F +
+   ".opt.ld." + Format));
 
   if (const Arg *A =
   Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
 CmdArgs.push_back(Args.MakeArgString(
-Twine("-plugin-opt=opt-remarks-passes=") + A->getValue()));
+Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue()));
 
-  CmdArgs.push_back(Args.MakeArgString(
-  Twin

[PATCH] D142627: [analyzer] Fix crash exposed by D140059

2023-01-26 Thread 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 rGf027dd55f32a: [analyzer] Fix crash exposed by D140059 
(authored by einvbri ).

Changed prior to commit:
  https://reviews.llvm.org/D142627?vs=492432&id=492521#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142627

Files:
  clang/test/Analysis/z3-crosscheck.c
  llvm/lib/Support/Z3Solver.cpp


Index: llvm/lib/Support/Z3Solver.cpp
===
--- llvm/lib/Support/Z3Solver.cpp
+++ llvm/lib/Support/Z3Solver.cpp
@@ -729,7 +729,7 @@
 const Z3_sort Z3Sort = toZ3Sort(*getBitvectorSort(BitWidth)).Sort;
 
 // Slow path, when 64 bits are not enough.
-if (LLVM_UNLIKELY(Int.getBitWidth() > 64u)) {
+if (LLVM_UNLIKELY(!Int.isRepresentableByInt64())) {
   SmallString<40> Buffer;
   Int.toString(Buffer, 10);
   return newExprRef(Z3Expr(
Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -77,3 +77,15 @@
 // expected-warning@-1{{garbage}}
   }
 }
+
+// don't crash, and also produce a core.CallAndMessage finding
+void a(int);
+typedef struct {
+  int b;
+} c;
+c *d;
+void e() {
+  (void)d->b;
+  int f;
+  a(f); // expected-warning {{1st function call argument is an uninitialized 
value [core.CallAndMessage]}}
+}


Index: llvm/lib/Support/Z3Solver.cpp
===
--- llvm/lib/Support/Z3Solver.cpp
+++ llvm/lib/Support/Z3Solver.cpp
@@ -729,7 +729,7 @@
 const Z3_sort Z3Sort = toZ3Sort(*getBitvectorSort(BitWidth)).Sort;
 
 // Slow path, when 64 bits are not enough.
-if (LLVM_UNLIKELY(Int.getBitWidth() > 64u)) {
+if (LLVM_UNLIKELY(!Int.isRepresentableByInt64())) {
   SmallString<40> Buffer;
   Int.toString(Buffer, 10);
   return newExprRef(Z3Expr(
Index: clang/test/Analysis/z3-crosscheck.c
===
--- clang/test/Analysis/z3-crosscheck.c
+++ clang/test/Analysis/z3-crosscheck.c
@@ -77,3 +77,15 @@
 // expected-warning@-1{{garbage}}
   }
 }
+
+// don't crash, and also produce a core.CallAndMessage finding
+void a(int);
+typedef struct {
+  int b;
+} c;
+c *d;
+void e() {
+  (void)d->b;
+  int f;
+  a(f); // expected-warning {{1st function call argument is an uninitialized value [core.CallAndMessage]}}
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D140756: Add clang_CXXMethod_isExplicit to libclang

2023-01-27 Thread 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 rG0a51bc731bcc: Add clang_CXXMethod_isExplicit to libclang 
(authored by Luca Di Sera ).

Changed prior to commit:
  https://reviews.llvm.org/D140756?vs=492042&id=492702#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140756

Files:
  clang/bindings/python/clang/cindex.py
  clang/bindings/python/tests/cindex/test_cursor.py
  clang/include/clang-c/Index.h
  clang/test/Index/explicit-constructor.cpp
  clang/test/Index/explicit-conversion-function.cpp
  clang/test/Index/get-cursor.cpp
  clang/test/Index/index-file.cpp
  clang/test/Index/recursive-cxx-member-calls.cpp
  clang/tools/c-index-test/c-index-test.c
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/libclang.map

Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -416,6 +416,7 @@
 clang_disposeAPISet;
 clang_getSymbolGraphForCursor;
 clang_getSymbolGraphForUSR;
+clang_CXXMethod_isExplicit;
 };
 
 # Example of how to add a new symbol version entry.  If you do add a new symbol
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -8947,6 +8947,25 @@
   return (Method && Method->isMoveAssignmentOperator()) ? 1 : 0;
 }
 
+unsigned clang_CXXMethod_isExplicit(CXCursor C) {
+  if (!clang_isDeclaration(C.kind))
+return 0;
+
+  const Decl *D = cxcursor::getCursorDecl(C);
+  const FunctionDecl *FD = D->getAsFunction();
+
+  if (!FD)
+return 0;
+
+  if (const auto *Ctor = dyn_cast(FD))
+return Ctor->isExplicit();
+
+  if (const auto *Conv = dyn_cast(FD))
+return Conv->isExplicit();
+
+  return 0;
+}
+
 unsigned clang_CXXRecord_isAbstract(CXCursor C) {
   if (!clang_isDeclaration(C.kind))
 return 0;
Index: clang/tools/c-index-test/c-index-test.c
===
--- clang/tools/c-index-test/c-index-test.c
+++ clang/tools/c-index-test/c-index-test.c
@@ -916,6 +916,8 @@
   printf(" (copy-assignment operator)");
 if (clang_CXXMethod_isMoveAssignmentOperator(Cursor))
   printf(" (move-assignment operator)");
+if (clang_CXXMethod_isExplicit(Cursor))
+  printf(" (explicit)");
 if (clang_CXXRecord_isAbstract(Cursor))
   printf(" (abstract)");
 if (clang_EnumDecl_isScoped(Cursor))
Index: clang/test/Index/recursive-cxx-member-calls.cpp
===
--- clang/test/Index/recursive-cxx-member-calls.cpp
+++ clang/test/Index/recursive-cxx-member-calls.cpp
@@ -824,7 +824,7 @@
 // CHECK-tokens: Keyword: "public" [86:1 - 86:7] CXXAccessSpecifier=:86:1 (Definition)
 // CHECK-tokens: Punctuation: ":" [86:7 - 86:8] CXXAccessSpecifier=:86:1 (Definition)
 // CHECK-tokens: Keyword: "explicit" [87:3 - 87:11] CXXConstructor=StringSwitch:87:12 (Definition)
-// CHECK-tokens: Identifier: "StringSwitch" [87:12 - 87:24] CXXConstructor=StringSwitch:87:12 (Definition)
+// CHECK-tokens: Identifier: "StringSwitch" [87:12 - 87:24] CXXConstructor=StringSwitch:87:12 (Definition) (explicit)
 // CHECK-tokens: Punctuation: "(" [87:24 - 87:25] CXXConstructor=StringSwitch:87:12 (Definition)
 // CHECK-tokens: Identifier: "StringRef" [87:25 - 87:34] TypeRef=class llvm::StringRef:38:7
 // CHECK-tokens: Identifier: "Str" [87:35 - 87:38] ParmDecl=Str:87:35 (Definition)
@@ -1839,7 +1839,7 @@
 // CHECK: 84:3: TypeRef=class llvm::StringRef:38:7 Extent=[84:3 - 84:12]
 // CHECK: 85:12: FieldDecl=Result:85:12 (Definition) Extent=[85:3 - 85:18]
 // CHECK: 86:1: CXXAccessSpecifier=:86:1 (Definition) Extent=[86:1 - 86:8]
-// CHECK: 87:12: CXXConstructor=StringSwitch:87:12 (Definition) Extent=[87:3 - 87:64]
+// CHECK: 87:12: CXXConstructor=StringSwitch:87:12 (Definition) (explicit) Extent=[87:3 - 87:64]
 // CHECK: 87:35: ParmDecl=Str:87:35 (Definition) Extent=[87:25 - 87:38]
 // CHECK: 87:25: TypeRef=class llvm::StringRef:38:7 Extent=[87:25 - 87:34]
 // CHECK: 87:42: MemberRef=Str:84:13 Extent=[87:42 - 87:45]
Index: clang/test/Index/index-file.cpp
===
--- clang/test/Index/index-file.cpp
+++ clang/test/Index/index-file.cpp
@@ -53,4 +53,4 @@
 // CHECK: [indexDeclaration]: kind: constructor | name: B | {{.*}} | loc: 33:12
 // CHECK: [indexDeclaration]: kind: constructor | name: B | {{.*}} (copy constructor) (converting constructor) | loc: 34:3
 // CHECK: [indexDeclaration]: kind: constructor | name: B | {{.*}} (move constructor) (converting constructor) | loc: 35:3
-// CHECK: [indexDeclaration]: kind: constructor | name: C | {{.*}} (copy constructor) | loc: 39:12
+// CHEC

[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2022-05-24 Thread 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 rG232bf8189ef7: [OpenMP] atomic compare fail : Parser & 
AST support (authored by koops, committed by Chi-Chun, Chen 
).
Herald added a project: Flang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -199,6 +199,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -569,7 +570,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1807,6 +1807,7 @@
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2368,6 +2368,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,24 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+1 {{expected '(' after 'fail'}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')' after 'atomic compare fail'}}
+ // expected-warning@+1 {{extra tokens at the end of '#pragma omp atomic' are ignored}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return mixed();
Index: clang/test/OpenMP/atomic_ast_print.cpp
===
--- clang/test/OpenMP/atomic_ast_print.cpp
+++ clang/test/OpenMP/atomic_ast_print.cpp
@@ -226,6 +226,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic compare capture hint(6)
   { v = a == b; if (v) a = c; }
+#pragma omp atomic compare fail(acq_rel)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(acquire)
+  { 

[PATCH] D123286: [Clang][OpenMP] Support for omp nothing

2022-05-24 Thread 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 rGca27f3e3b26e: [Clang][OpenMP] Support for omp nothing 
(authored by koops, committed by Chi-Chun, Chen 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123286

Files:
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/test/OpenMP/nothing_messages.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td


Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -629,6 +629,7 @@
 VersionedClause
   ];
 }
+def OMP_Nothing : Directive<"nothing"> {}
 def OMP_TargetData : Directive<"target data"> {
   let allowedClauses = [
 VersionedClause,
Index: clang/test/OpenMP/nothing_messages.cpp
===
--- /dev/null
+++ clang/test/OpenMP/nothing_messages.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -verify=expected -fopenmp -ferror-limit 100 %s 
-Wuninitialized
+
+int mixed() {
+  int x = 0;
+  int d = 4;
+
+#pragma omp nothing
+  x=d;
+
+  if(!x) {
+#pragma omp nothing
+x=d;
+  }
+
+// expected-error@+2 {{#pragma omp nothing' cannot be an immediate 
substatement}}
+  if(!x)
+#pragma omp nothing
+x=d;
+
+// expected-warning@+2 {{extra tokens at the end of '#pragma omp nothing' are 
ignored}}
+  if(!x) {
+#pragma omp nothing seq_cst
+x=d;
+  }
+
+  return 0;
+}
Index: clang/lib/Parse/ParseOpenMP.cpp
===
--- clang/lib/Parse/ParseOpenMP.cpp
+++ clang/lib/Parse/ParseOpenMP.cpp
@@ -2488,6 +2488,16 @@
   bool HasAssociatedStatement = true;
 
   switch (DKind) {
+  case OMPD_nothing:
+if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
+ParsedStmtContext())
+  Diag(Tok, diag::err_omp_immediate_directive)
+<< getOpenMPDirectiveName(DKind) << 0;
+ConsumeToken();
+skipUntilPragmaOpenMPEnd(DKind);
+if (Tok.is(tok::annot_pragma_openmp_end))
+  ConsumeAnnotationToken();
+break;
   case OMPD_metadirective: {
 ConsumeToken();
 SmallVector VMIs;
Index: clang/lib/Basic/OpenMPKinds.cpp
===
--- clang/lib/Basic/OpenMPKinds.cpp
+++ clang/lib/Basic/OpenMPKinds.cpp
@@ -730,6 +730,9 @@
   case OMPD_teams_loop:
 CaptureRegions.push_back(OMPD_teams);
 break;
+  case OMPD_nothing:
+CaptureRegions.push_back(OMPD_nothing);
+break;
   case OMPD_loop:
 // TODO: 'loop' may require different capture regions depending on the bind
 // clause or the parent directive when there is no bind clause. Use


Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -629,6 +629,7 @@
 VersionedClause
   ];
 }
+def OMP_Nothing : Directive<"nothing"> {}
 def OMP_TargetData : Directive<"target data"> {
   let allowedClauses = [
 VersionedClause,
Index: clang/test/OpenMP/nothing_messages.cpp
===
--- /dev/null
+++ clang/test/OpenMP/nothing_messages.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -verify=expected -fopenmp -ferror-limit 100 %s -Wuninitialized
+
+int mixed() {
+  int x = 0;
+  int d = 4;
+
+#pragma omp nothing
+  x=d;
+
+  if(!x) {
+#pragma omp nothing
+x=d;
+  }
+
+// expected-error@+2 {{#pragma omp nothing' cannot be an immediate substatement}}
+  if(!x)
+#pragma omp nothing
+x=d;
+
+// expected-warning@+2 {{extra tokens at the end of '#pragma omp nothing' are ignored}}
+  if(!x) {
+#pragma omp nothing seq_cst
+x=d;
+  }
+
+  return 0;
+}
Index: clang/lib/Parse/ParseOpenMP.cpp
===
--- clang/lib/Parse/ParseOpenMP.cpp
+++ clang/lib/Parse/ParseOpenMP.cpp
@@ -2488,6 +2488,16 @@
   bool HasAssociatedStatement = true;
 
   switch (DKind) {
+  case OMPD_nothing:
+if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
+ParsedStmtContext())
+  Diag(Tok, diag::err_omp_immediate_directive)
+<< getOpenMPDirectiveName(DKind) << 0;
+ConsumeToken();
+skipUntilPragmaOpenMPEnd(DKind);
+if (Tok.is(tok::annot_pragma_openmp_end))
+  ConsumeAnnotationToken();
+break;
   case OMPD_metadirective: {
 ConsumeToken();
 SmallVector VMIs;
Index: clang/lib/Basic/OpenMPKinds.cpp
===
--- clang/lib/Basic/OpenMPKinds.cpp
+++ clang/lib/Basic/OpenMPKinds.cpp
@@ -730,6 +730,9 @@
   case OMPD_teams_loop:
 CaptureRegions.push_back(OMPD_teams);
 break;
+ 

[PATCH] D127105: [analyzer] Fix null pointer deref in CastValueChecker

2022-06-07 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc7fa4e8a8bc4: [analyzer] Fix null pointer deref in 
CastValueChecker (authored by vabridgers, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127105

Files:
  clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
  clang/test/Analysis/cast-value-notes.cpp
  clang/test/Analysis/cast-value-state-dump.cpp

Index: clang/test/Analysis/cast-value-state-dump.cpp
===
--- clang/test/Analysis/cast-value-state-dump.cpp
+++ clang/test/Analysis/cast-value-state-dump.cpp
@@ -18,12 +18,12 @@
 
 void evalNonNullParamNonNullReturn(const Shape *S) {
   const auto *C = dyn_cast_or_null(S);
-  // expected-note@-1 {{Assuming 'S' is a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is a 'const class clang::Circle *'}}
   // expected-note@-2 {{'C' initialized here}}
 
   // FIXME: We assumed that 'S' is a 'Circle' therefore it is not a 'Square'.
   if (dyn_cast_or_null(S)) {
-// expected-note@-1 {{Assuming 'S' is not a 'Square'}}
+// expected-note@-1 {{Assuming 'S' is not a 'const class clang::Square *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
Index: clang/test/Analysis/cast-value-notes.cpp
===
--- clang/test/Analysis/cast-value-notes.cpp
+++ clang/test/Analysis/cast-value-notes.cpp
@@ -73,7 +73,7 @@
 #if defined(X86)
 void evalReferences(const Shape &S) {
   const auto &C = dyn_cast(S);
-  // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is not a 'const class clang::Circle &'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
   clang_analyzer_printState();
@@ -93,7 +93,7 @@
 #if defined(NOT_SUPPRESSED)
 void evalReferences_addrspace(const Shape &S) {
   const auto &C = dyn_cast(S);
-  // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is not a 'const __attribute__((address_space(3))) class clang::Circle &'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
   clang_analyzer_printState();
@@ -105,7 +105,7 @@
 #elif defined(MIPS)
 void evalReferences(const Shape &S) {
   const auto &C = dyn_cast(S);
-  // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is not a 'const class clang::Circle &'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
 }
@@ -122,25 +122,25 @@
   // expected-note@-1 {{'C' initialized here}}
 
   if (!dyn_cast_or_null(C)) {
-// expected-note@-1 {{'C' is a 'Circle'}}
+// expected-note@-1 {{Assuming 'C' is a 'const class clang::Circle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Triangle'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Triangle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Rectangle'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Rectangle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Hexagon'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Hexagon *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
@@ -176,29 +176,29 @@
 
 void evalNonNullParamNonNullReturn(const Shape *S) {
   const auto *C = cast(S);
-  // expected-note@-1 {{'S' is a 'Circle'}}
+  // expected-note@-1 {{'S' is a 'const class clang::Circle *'}}
   // expected-note@-2 {{'C' initialized here}}
 
   if (!dyn_cast_or_null(C)) {
-// expected-note@-1 {{'C' is a 'Circle'}}
+// expected-note@-1 {{Assuming 'C' is a 'const class clang::Circle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Triangle'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Triangle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Rectangle'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Rectangle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Hexagon'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Hexagon *'}}
 // expected-note@-2 {{Taking false br

[PATCH] D159519: [clang][AST][ASTImporter] improve AST comparasion on VarDecl & GotoStmt

2023-09-20 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb8f056de025f: [clang][AST][ASTImporter] improve AST 
comparasion on VarDecl & GotoStmt (#66976) (authored by jcsxky, committed 
by GitHub ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159519

Files:
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -1,5 +1,6 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTStructuralEquivalence.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Frontend/ASTUnit.h"
@@ -1801,10 +1802,10 @@
 TEST_F(StructuralEquivalenceCacheTest, ReturnStmtNonEq) {
   auto TU = makeTuDecls(
   R"(
-  bool x(){ return true; }
+  bool x() { return true; }
   )",
   R"(
-  bool x(){ return false; }
+  bool x() { return false; }
   )",
   Lang_CXX03);
 
@@ -1817,6 +1818,60 @@
 
 }
 
+TEST_F(StructuralEquivalenceCacheTest, VarDeclNoEq) {
+  auto TU = makeTuDecls(
+  R"(
+  int p;
+  )",
+  R"(
+  int q;
+  )",
+  Lang_CXX03);
+
+  StructuralEquivalenceContext Ctx(
+  get<0>(TU)->getASTContext(), get<1>(TU)->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default, false, false);
+
+  auto Var = findDeclPair(TU, varDecl());
+  EXPECT_FALSE(Ctx.IsEquivalent(Var.first, Var.second));
+}
+
+TEST_F(StructuralEquivalenceCacheTest, VarDeclWithDifferentStorageClassNoEq) {
+  auto TU = makeTuDecls(
+  R"(
+  int p;
+  )",
+  R"(
+  static int p;
+  )",
+  Lang_CXX03);
+
+  StructuralEquivalenceContext Ctx(
+  get<0>(TU)->getASTContext(), get<1>(TU)->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default, false, false);
+
+  auto Var = findDeclPair(TU, varDecl());
+  EXPECT_FALSE(Ctx.IsEquivalent(Var.first, Var.second));
+}
+
+TEST_F(StructuralEquivalenceCacheTest, VarDeclWithInitNoEq) {
+  auto TU = makeTuDecls(
+  R"(
+  int p = 1;
+  )",
+  R"(
+  int p = 2;
+  )",
+  Lang_CXX03);
+
+  StructuralEquivalenceContext Ctx(
+  get<0>(TU)->getASTContext(), get<1>(TU)->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default, false, false);
+
+  auto Var = findDeclPair(TU, varDecl());
+  EXPECT_FALSE(Ctx.IsEquivalent(Var.first, Var.second));
+}
+
 TEST_F(StructuralEquivalenceCacheTest, SpecialNonEq) {
   auto TU = makeTuDecls(
   R"(
@@ -2320,5 +2375,23 @@
   EXPECT_TRUE(testStructuralMatch(t));
 }
 
+TEST_F(StructuralEquivalenceCacheTest, GotoStmtNoEq) {
+  auto S = makeStmts(
+  R"(
+  void foo() {
+goto L1;
+L1: foo();
+  }
+  )",
+  R"(
+  void foo() {
+goto L2;
+L2: foo();
+  }
+  )",
+  Lang_CXX03, gotoStmt());
+  EXPECT_FALSE(testStructuralMatch(S));
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/lib/AST/ASTStructuralEquivalence.cpp
===
--- clang/lib/AST/ASTStructuralEquivalence.cpp
+++ clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -277,6 +277,17 @@
 
   bool IsStmtEquivalent(const Stmt *S1, const Stmt *S2) { return true; }
 
+  bool IsStmtEquivalent(const GotoStmt *S1, const GotoStmt *S2) {
+LabelDecl *L1 = S1->getLabel();
+LabelDecl *L2 = S2->getLabel();
+if (!L1 || !L2)
+  return L1 == L2;
+
+IdentifierInfo *Name1 = L1->getIdentifier();
+IdentifierInfo *Name2 = L2->getIdentifier();
+return ::IsStructurallyEquivalent(Name1, Name2);
+  }
+
   bool IsStmtEquivalent(const SourceLocExpr *E1, const SourceLocExpr *E2) {
 return E1->getIdentKind() == E2->getIdentKind();
   }
@@ -1295,6 +1306,22 @@
   return true;
 }
 
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
+ VarDecl *D1, VarDecl *D2) {
+  if (D1->getStorageClass() != D2->getStorageClass())
+return false;
+
+  IdentifierInfo *Name1 = D1->getIdentifier();
+  IdentifierInfo *Name2 = D2->getIdentifier();
+  if (!::IsStructurallyEquivalent(Name1, Name2))
+return false;
+
+  if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType()))
+return false;
+
+  return IsStructurallyEquivalent(Context, D1->getInit(), D2->getInit());
+}
+
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
  FieldDecl *Field1, FieldDecl *Field2,
  QualType Owner2Type) {
___
cfe-commits mailing list
cfe

[PATCH] D152206: [Basic] Support 64-bit x86 target for UEFI

2023-09-27 Thread 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 rG315a407086b0: [Basic] Support 64-bit x86 target for UEFI 
(authored by prabhukr ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152206

Files:
  llvm/lib/IR/DataLayout.cpp
  llvm/lib/TargetParser/Triple.cpp
  llvm/unittests/IR/DataLayoutTest.cpp
  llvm/unittests/TargetParser/TripleTest.cpp


Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -462,6 +462,7 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UEFI, T.getOS());
   EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
+  EXPECT_EQ(Triple::COFF, T.getObjectFormat());
 
   T = Triple("wasm32-unknown-unknown");
   EXPECT_EQ(Triple::wasm32, T.getArch());
Index: llvm/unittests/IR/DataLayoutTest.cpp
===
--- llvm/unittests/IR/DataLayoutTest.cpp
+++ llvm/unittests/IR/DataLayoutTest.cpp
@@ -11,6 +11,7 @@
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Type.h"
+#include "llvm/TargetParser/Triple.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 
@@ -104,4 +105,11 @@
   EXPECT_EQ(Align(4 * 8), DL->getPrefTypeAlign(V8F32Ty));
 }
 
+TEST(DataLayoutTest, UEFI) {
+  Triple TT = Triple("x86_64-unknown-uefi");
+
+  // Test UEFI X86_64 Mangling Component.
+  EXPECT_STREQ(DataLayout::getManglingComponent(TT), "-m:w");
+}
+
 } // anonymous namespace
Index: llvm/lib/TargetParser/Triple.cpp
===
--- llvm/lib/TargetParser/Triple.cpp
+++ llvm/lib/TargetParser/Triple.cpp
@@ -799,6 +799,8 @@
   case Triple::x86_64:
 if (T.isOSWindows())
   return Triple::COFF;
+else if (T.isUEFI())
+  return Triple::COFF;
 return Triple::ELF;
 
   case Triple::aarch64_be:
Index: llvm/lib/IR/DataLayout.cpp
===
--- llvm/lib/IR/DataLayout.cpp
+++ llvm/lib/IR/DataLayout.cpp
@@ -171,7 +171,7 @@
 return "-m:l";
   if (T.isOSBinFormatMachO())
 return "-m:o";
-  if (T.isOSWindows() && T.isOSBinFormatCOFF())
+  if ((T.isOSWindows() || T.isUEFI()) && T.isOSBinFormatCOFF())
 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
   if (T.isOSBinFormatXCOFF())
 return "-m:a";


Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -462,6 +462,7 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UEFI, T.getOS());
   EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
+  EXPECT_EQ(Triple::COFF, T.getObjectFormat());
 
   T = Triple("wasm32-unknown-unknown");
   EXPECT_EQ(Triple::wasm32, T.getArch());
Index: llvm/unittests/IR/DataLayoutTest.cpp
===
--- llvm/unittests/IR/DataLayoutTest.cpp
+++ llvm/unittests/IR/DataLayoutTest.cpp
@@ -11,6 +11,7 @@
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Type.h"
+#include "llvm/TargetParser/Triple.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 
@@ -104,4 +105,11 @@
   EXPECT_EQ(Align(4 * 8), DL->getPrefTypeAlign(V8F32Ty));
 }
 
+TEST(DataLayoutTest, UEFI) {
+  Triple TT = Triple("x86_64-unknown-uefi");
+
+  // Test UEFI X86_64 Mangling Component.
+  EXPECT_STREQ(DataLayout::getManglingComponent(TT), "-m:w");
+}
+
 } // anonymous namespace
Index: llvm/lib/TargetParser/Triple.cpp
===
--- llvm/lib/TargetParser/Triple.cpp
+++ llvm/lib/TargetParser/Triple.cpp
@@ -799,6 +799,8 @@
   case Triple::x86_64:
 if (T.isOSWindows())
   return Triple::COFF;
+else if (T.isUEFI())
+  return Triple::COFF;
 return Triple::ELF;
 
   case Triple::aarch64_be:
Index: llvm/lib/IR/DataLayout.cpp
===
--- llvm/lib/IR/DataLayout.cpp
+++ llvm/lib/IR/DataLayout.cpp
@@ -171,7 +171,7 @@
 return "-m:l";
   if (T.isOSBinFormatMachO())
 return "-m:o";
-  if (T.isOSWindows() && T.isOSBinFormatCOFF())
+  if ((T.isOSWindows() || T.isUEFI()) && T.isOSBinFormatCOFF())
 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
   if (T.isOSBinFormatXCOFF())
 return "-m:a";
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152206: [Basic] Support 64-bit x86 target for UEFI

2023-09-28 Thread 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 rG720e3bacbd9f: [Basic] Support 64-bit x86 target for UEFI 
(authored by prabhukr ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152206

Files:
  llvm/lib/IR/DataLayout.cpp
  llvm/lib/TargetParser/Triple.cpp
  llvm/unittests/IR/DataLayoutTest.cpp
  llvm/unittests/TargetParser/TripleTest.cpp


Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -462,6 +462,7 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UEFI, T.getOS());
   EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
+  EXPECT_EQ(Triple::COFF, T.getObjectFormat());
 
   T = Triple("wasm32-unknown-unknown");
   EXPECT_EQ(Triple::wasm32, T.getArch());
Index: llvm/unittests/IR/DataLayoutTest.cpp
===
--- llvm/unittests/IR/DataLayoutTest.cpp
+++ llvm/unittests/IR/DataLayoutTest.cpp
@@ -11,6 +11,7 @@
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Type.h"
+#include "llvm/TargetParser/Triple.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 
@@ -104,4 +105,11 @@
   EXPECT_EQ(Align(4 * 8), DL->getPrefTypeAlign(V8F32Ty));
 }
 
+TEST(DataLayoutTest, UEFI) {
+  Triple TT = Triple("x86_64-unknown-uefi");
+
+  // Test UEFI X86_64 Mangling Component.
+  EXPECT_STREQ(DataLayout::getManglingComponent(TT), "-m:w");
+}
+
 } // anonymous namespace
Index: llvm/lib/TargetParser/Triple.cpp
===
--- llvm/lib/TargetParser/Triple.cpp
+++ llvm/lib/TargetParser/Triple.cpp
@@ -799,6 +799,8 @@
   case Triple::x86_64:
 if (T.isOSWindows())
   return Triple::COFF;
+else if (T.isUEFI())
+  return Triple::COFF;
 return Triple::ELF;
 
   case Triple::aarch64_be:
Index: llvm/lib/IR/DataLayout.cpp
===
--- llvm/lib/IR/DataLayout.cpp
+++ llvm/lib/IR/DataLayout.cpp
@@ -171,7 +171,7 @@
 return "-m:l";
   if (T.isOSBinFormatMachO())
 return "-m:o";
-  if (T.isOSWindows() && T.isOSBinFormatCOFF())
+  if ((T.isOSWindows() || T.isUEFI()) && T.isOSBinFormatCOFF())
 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
   if (T.isOSBinFormatXCOFF())
 return "-m:a";


Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -462,6 +462,7 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UEFI, T.getOS());
   EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
+  EXPECT_EQ(Triple::COFF, T.getObjectFormat());
 
   T = Triple("wasm32-unknown-unknown");
   EXPECT_EQ(Triple::wasm32, T.getArch());
Index: llvm/unittests/IR/DataLayoutTest.cpp
===
--- llvm/unittests/IR/DataLayoutTest.cpp
+++ llvm/unittests/IR/DataLayoutTest.cpp
@@ -11,6 +11,7 @@
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Type.h"
+#include "llvm/TargetParser/Triple.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 
@@ -104,4 +105,11 @@
   EXPECT_EQ(Align(4 * 8), DL->getPrefTypeAlign(V8F32Ty));
 }
 
+TEST(DataLayoutTest, UEFI) {
+  Triple TT = Triple("x86_64-unknown-uefi");
+
+  // Test UEFI X86_64 Mangling Component.
+  EXPECT_STREQ(DataLayout::getManglingComponent(TT), "-m:w");
+}
+
 } // anonymous namespace
Index: llvm/lib/TargetParser/Triple.cpp
===
--- llvm/lib/TargetParser/Triple.cpp
+++ llvm/lib/TargetParser/Triple.cpp
@@ -799,6 +799,8 @@
   case Triple::x86_64:
 if (T.isOSWindows())
   return Triple::COFF;
+else if (T.isUEFI())
+  return Triple::COFF;
 return Triple::ELF;
 
   case Triple::aarch64_be:
Index: llvm/lib/IR/DataLayout.cpp
===
--- llvm/lib/IR/DataLayout.cpp
+++ llvm/lib/IR/DataLayout.cpp
@@ -171,7 +171,7 @@
 return "-m:l";
   if (T.isOSBinFormatMachO())
 return "-m:o";
-  if (T.isOSWindows() && T.isOSBinFormatCOFF())
+  if ((T.isOSWindows() || T.isUEFI()) && T.isOSBinFormatCOFF())
 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
   if (T.isOSBinFormatXCOFF())
 return "-m:a";
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155339: Enable zba and zbs for RISCV64 Android

2023-07-17 Thread 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 rGf7623f4f692d: Enable zba and zbs for RISCV64 Android 
(authored by AdityaK <1894981+hiradi...@users.noreply.github.com>).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155339

Files:
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/test/Driver/riscv-features.c


Index: clang/test/Driver/riscv-features.c
===
--- clang/test/Driver/riscv-features.c
+++ clang/test/Driver/riscv-features.c
@@ -10,7 +10,9 @@
 // RUN: %clang --target=riscv32-unknown-elf -### %s -mrelax 2>&1 | FileCheck 
%s -check-prefix=RELAX
 // RUN: %clang --target=riscv32-unknown-elf -### %s -mno-relax 2>&1 | 
FileCheck %s -check-prefix=NO-RELAX
 
+// ANDROID: "-target-feature" "+zba"
 // ANDROID: "-target-feature" "+zbb"
+// ANDROID: "-target-feature" "+zbs"
 // RELAX: "-target-feature" "+relax"
 // NO-RELAX: "-target-feature" "-relax"
 // DEFAULT: "-target-feature" "+relax"
Index: clang/lib/Driver/ToolChains/Arch/RISCV.cpp
===
--- clang/lib/Driver/ToolChains/Arch/RISCV.cpp
+++ clang/lib/Driver/ToolChains/Arch/RISCV.cpp
@@ -294,7 +294,7 @@
   return "rv32imafdc";
 else if (MABI.starts_with_insensitive("lp64")) {
   if (Triple.isAndroid())
-return "rv64imafdc_zbb";
+return "rv64imafdc_zba_zbb_zbs";
 
   return "rv64imafdc";
 }
@@ -314,7 +314,7 @@
 if (Triple.getOS() == llvm::Triple::UnknownOS)
   return "rv64imac";
 else if (Triple.isAndroid())
-  return "rv64imafdc_zbb";
+  return "rv64imafdc_zba_zbb_zbs";
 else
   return "rv64imafdc";
   }


Index: clang/test/Driver/riscv-features.c
===
--- clang/test/Driver/riscv-features.c
+++ clang/test/Driver/riscv-features.c
@@ -10,7 +10,9 @@
 // RUN: %clang --target=riscv32-unknown-elf -### %s -mrelax 2>&1 | FileCheck %s -check-prefix=RELAX
 // RUN: %clang --target=riscv32-unknown-elf -### %s -mno-relax 2>&1 | FileCheck %s -check-prefix=NO-RELAX
 
+// ANDROID: "-target-feature" "+zba"
 // ANDROID: "-target-feature" "+zbb"
+// ANDROID: "-target-feature" "+zbs"
 // RELAX: "-target-feature" "+relax"
 // NO-RELAX: "-target-feature" "-relax"
 // DEFAULT: "-target-feature" "+relax"
Index: clang/lib/Driver/ToolChains/Arch/RISCV.cpp
===
--- clang/lib/Driver/ToolChains/Arch/RISCV.cpp
+++ clang/lib/Driver/ToolChains/Arch/RISCV.cpp
@@ -294,7 +294,7 @@
   return "rv32imafdc";
 else if (MABI.starts_with_insensitive("lp64")) {
   if (Triple.isAndroid())
-return "rv64imafdc_zbb";
+return "rv64imafdc_zba_zbb_zbs";
 
   return "rv64imafdc";
 }
@@ -314,7 +314,7 @@
 if (Triple.getOS() == llvm::Triple::UnknownOS)
   return "rv64imac";
 else if (Triple.isAndroid())
-  return "rv64imafdc_zbb";
+  return "rv64imafdc_zba_zbb_zbs";
 else
   return "rv64imafdc";
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154701: [ASTImporter] Fix 'isVirtual()' assert failure while importing overridden methods

2023-07-18 Thread 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 rG5b99aa57f74e: [ASTImporter] Fix 'isVirtual()' 
assert failure while import overridden methods (authored by dingfei 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154701

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


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -2332,6 +2332,43 @@
   EXPECT_EQ(ToDFOutOfClass->getPreviousDecl(), ToDFInClass);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportVirtualOverriddenMethodOnALoopTest) {
+  // B::f() calls => f1() ==> C ==> C::f()
+  // \
+  //  \ A::f()
+  //
+  // C::f()'s ImportOverriddenMethods() asserts B::isVirtual(), so B::f()'s
+  // ImportOverriddenMethods() should be completed before B::f()'s body
+  const char *Code =
+  R"(
+  void f1();
+  class A {
+virtual void f(){}
+  };
+  class B: public A {
+void f() override {
+  f1();
+}
+  };
+  class C: public B {
+void f() override {}
+  };
+  void f1() { C c; }
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);
+
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, cxxMethodDecl(hasName("B::f")));
+
+  auto *ToBF = Import(FromF, Lang_CXX11);
+  EXPECT_TRUE(ToBF->isVirtual());
+
+  auto *ToCF = FirstDeclMatcher().match(
+  ToBF->getTranslationUnitDecl(), cxxMethodDecl(hasName("C::f")));
+  EXPECT_TRUE(ToCF->isVirtual());
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportVariableChainInC) {
 std::string Code = "static int v; static int v = 0;";
 auto Pattern = varDecl(hasName("v"));
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3782,6 +3782,11 @@
   if (Error Err = ImportTemplateInformation(D, ToFunction))
 return std::move(Err);
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+if (Error Err = ImportOverriddenMethods(cast(ToFunction),
+FromCXXMethod))
+  return std::move(Err);
+
   if (D->doesThisDeclarationHaveABody()) {
 Error Err = ImportFunctionDeclBody(D, ToFunction);
 
@@ -3805,11 +3810,6 @@
 
   addDeclToContexts(D, ToFunction);
 
-  if (auto *FromCXXMethod = dyn_cast(D))
-if (Error Err = ImportOverriddenMethods(cast(ToFunction),
-FromCXXMethod))
-  return std::move(Err);
-
   // Import the rest of the chain. I.e. import all subsequent declarations.
   for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -2332,6 +2332,43 @@
   EXPECT_EQ(ToDFOutOfClass->getPreviousDecl(), ToDFInClass);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportVirtualOverriddenMethodOnALoopTest) {
+  // B::f() calls => f1() ==> C ==> C::f()
+  // \
+  //  \ A::f()
+  //
+  // C::f()'s ImportOverriddenMethods() asserts B::isVirtual(), so B::f()'s
+  // ImportOverriddenMethods() should be completed before B::f()'s body
+  const char *Code =
+  R"(
+  void f1();
+  class A {
+virtual void f(){}
+  };
+  class B: public A {
+void f() override {
+  f1();
+}
+  };
+  class C: public B {
+void f() override {}
+  };
+  void f1() { C c; }
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);
+
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, cxxMethodDecl(hasName("B::f")));
+
+  auto *ToBF = Import(FromF, Lang_CXX11);
+  EXPECT_TRUE(ToBF->isVirtual());
+
+  auto *ToCF = FirstDeclMatcher().match(
+  ToBF->getTranslationUnitDecl(), cxxMethodDecl(hasName("C::f")));
+  EXPECT_TRUE(ToCF->isVirtual());
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportVariableChainInC) {
 std::string Code = "static int v; static int v = 0;";
 auto Pattern = varDecl(hasName("v"));
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3782,6 +3782,11 @@
   if (Error Err = ImportTemplateInformation(D, ToFunction))
 return std::move(Err);
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+if (Error Err = ImportOverriddenMethods(cast(ToFunction),
+FromCXXMethod))
+  return std::move(Err);
+
   if (D->doe

[PATCH] D154764: [ASTImporter] Fields are imported first and reordered for correct layout.

2023-07-18 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe9536698720e: [ASTImporter] Fields are imported first and 
reordered for correct layout (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154764

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

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8007,6 +8007,27 @@
 ToDGOther);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportFieldsFirstForCorrectRecordLayoutTest) {
+  // UnaryOperator(&) triggers RecordLayout computation, which relies on
+  // correctly imported fields.
+  auto Code =
+  R"(
+  class A {
+int m() {
+  return &((A *)0)->f1 - &((A *)0)->f2;
+}
+int f1;
+int f2;
+  };
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11);
+
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, cxxMethodDecl(hasName("A::m")));
+  Import(FromF, Lang_CXX11);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase,
ImportRecordWithLayoutRequestingExpr) {
   TranslationUnitDecl *FromTU = getTuDecl(
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -433,6 +433,7 @@
 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
 
+Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To);
 Expected ImportCastPath(CastExpr *E);
 Expected ImportAPValue(const APValue &FromValue);
 
@@ -1850,52 +1851,33 @@
   // different values in two distinct translation units.
   ChildErrorHandlingStrategy HandleChildErrors(FromDC);
 
+  auto MightNeedReordering = [](const Decl *D) {
+return isa(D) || isa(D) || isa(D);
+  };
+
+  // Import everything that might need reordering first.
   Error ChildErrors = Error::success();
   for (auto *From : FromDC->decls()) {
+if (!MightNeedReordering(From))
+  continue;
+
 ExpectedDecl ImportedOrErr = import(From);
 
 // If we are in the process of ImportDefinition(...) for a RecordDecl we
 // want to make sure that we are also completing each FieldDecl. There
 // are currently cases where this does not happen and this is correctness
 // fix since operations such as code generation will expect this to be so.
-if (ImportedOrErr) {
-  FieldDecl *FieldFrom = dyn_cast_or_null(From);
-  Decl *ImportedDecl = *ImportedOrErr;
-  FieldDecl *FieldTo = dyn_cast_or_null(ImportedDecl);
-  if (FieldFrom && FieldTo) {
-RecordDecl *FromRecordDecl = nullptr;
-RecordDecl *ToRecordDecl = nullptr;
-// If we have a field that is an ArrayType we need to check if the array
-// element is a RecordDecl and if so we need to import the definition.
-if (FieldFrom->getType()->isArrayType()) {
-  // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
-  FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
-  ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
-}
-
-if (!FromRecordDecl || !ToRecordDecl) {
-  const RecordType *RecordFrom =
-  FieldFrom->getType()->getAs();
-  const RecordType *RecordTo = FieldTo->getType()->getAs();
-
-  if (RecordFrom && RecordTo) {
-FromRecordDecl = RecordFrom->getDecl();
-ToRecordDecl = RecordTo->getDecl();
-  }
-}
-
-if (FromRecordDecl && ToRecordDecl) {
-  if (FromRecordDecl->isCompleteDefinition() &&
-  !ToRecordDecl->isCompleteDefinition()) {
-Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
-HandleChildErrors.handleChildImportResult(ChildErrors,
-  std::move(Err));
-  }
-}
-  }
-} else {
+if (!ImportedOrErr) {
   HandleChildErrors.handleChildImportResult(ChildErrors,
 ImportedOrErr.takeError());
+  continue;
+}
+FieldDecl *FieldFrom = dyn_cast_or_null(From);
+Decl *ImportedDecl = *ImportedOrErr;
+FieldDecl *FieldTo = dyn_cast_or_null(ImportedDecl);
+if (FieldFrom && FieldTo) {
+  Error Err = ImportFieldDeclDefinition(FieldFrom, FieldTo);
+  HandleChildErrors.handleChildImportResult(ChildErrors, std::move(Err));
 }
   }
 
@@ -1910,7 +1892,7 @@
   // During the import of `a` we import first the dependencies in sequence,
   // thus the order would be `c`, `b`, `

[PATCH] D154983: [clang-extdef-mapping] register necessary targest for ms-style asm block

2023-07-18 Thread 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 rG2c651184a2b0: [clang-extdef-mapping] register necessary 
targest for ms-style asm block (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154983

Files:
  clang/test/Tooling/ms-asm-clang-extdef-mapping.c
  clang/tools/clang-extdef-mapping/CMakeLists.txt
  clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp


Index: clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
===
--- clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
+++ clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
@@ -23,6 +23,7 @@
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/TargetSelect.h"
 #include 
 #include 
 #include 
@@ -214,6 +215,10 @@
   }
   CommonOptionsParser &OptionsParser = ExpectedParser.get();
 
+  llvm::InitializeAllTargetInfos();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmParsers();
+
   return HandleFiles(OptionsParser.getSourcePathList(),
  OptionsParser.getCompilations());
 }
Index: clang/tools/clang-extdef-mapping/CMakeLists.txt
===
--- clang/tools/clang-extdef-mapping/CMakeLists.txt
+++ clang/tools/clang-extdef-mapping/CMakeLists.txt
@@ -1,5 +1,8 @@
 set(LLVM_LINK_COMPONENTS
   ${LLVM_TARGETS_TO_BUILD}
+  AllTargetsAsmParsers
+  AllTargetsDescs
+  AllTargetsInfos
   support
   )
 
Index: clang/test/Tooling/ms-asm-clang-extdef-mapping.c
===
--- /dev/null
+++ clang/test/Tooling/ms-asm-clang-extdef-mapping.c
@@ -0,0 +1,7 @@
+// RUN: clang-extdef-mapping "%s" -- -fasm-blocks 2>&1 | FileCheck %s
+
+void Break() {
+  __asm { int 3 }
+}
+
+// CHECK: {{c:@F@Break .*}}


Index: clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
===
--- clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
+++ clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
@@ -23,6 +23,7 @@
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/TargetSelect.h"
 #include 
 #include 
 #include 
@@ -214,6 +215,10 @@
   }
   CommonOptionsParser &OptionsParser = ExpectedParser.get();
 
+  llvm::InitializeAllTargetInfos();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmParsers();
+
   return HandleFiles(OptionsParser.getSourcePathList(),
  OptionsParser.getCompilations());
 }
Index: clang/tools/clang-extdef-mapping/CMakeLists.txt
===
--- clang/tools/clang-extdef-mapping/CMakeLists.txt
+++ clang/tools/clang-extdef-mapping/CMakeLists.txt
@@ -1,5 +1,8 @@
 set(LLVM_LINK_COMPONENTS
   ${LLVM_TARGETS_TO_BUILD}
+  AllTargetsAsmParsers
+  AllTargetsDescs
+  AllTargetsInfos
   support
   )
 
Index: clang/test/Tooling/ms-asm-clang-extdef-mapping.c
===
--- /dev/null
+++ clang/test/Tooling/ms-asm-clang-extdef-mapping.c
@@ -0,0 +1,7 @@
+// RUN: clang-extdef-mapping "%s" -- -fasm-blocks 2>&1 | FileCheck %s
+
+void Break() {
+  __asm { int 3 }
+}
+
+// CHECK: {{c:@F@Break .*}}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155576: [NFC][clang-extdef-mapping] fix test failure on nonsupported targets

2023-07-18 Thread Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc24f0f9bd6f4: [NFC][clang-extdef-mapping] fix test failure 
on unsupported targets (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155576

Files:
  clang/test/Tooling/ms-asm-clang-extdef-mapping.c


Index: clang/test/Tooling/ms-asm-clang-extdef-mapping.c
===
--- clang/test/Tooling/ms-asm-clang-extdef-mapping.c
+++ clang/test/Tooling/ms-asm-clang-extdef-mapping.c
@@ -1,7 +1,9 @@
-// RUN: clang-extdef-mapping "%s" -- -fasm-blocks 2>&1 | FileCheck %s
+// RUN: clang-extdef-mapping "%s" -- -fasm-blocks \
+// RUN:   -target x86_64-apple-darwin10 2>&1 | FileCheck %s
+// REQUIRES: x86-registered-target
 
 void Break() {
   __asm { int 3 }
 }
 
-// CHECK: {{c:@F@Break .*}}
+// CHECK: {{10:c:@F@Break}}


Index: clang/test/Tooling/ms-asm-clang-extdef-mapping.c
===
--- clang/test/Tooling/ms-asm-clang-extdef-mapping.c
+++ clang/test/Tooling/ms-asm-clang-extdef-mapping.c
@@ -1,7 +1,9 @@
-// RUN: clang-extdef-mapping "%s" -- -fasm-blocks 2>&1 | FileCheck %s
+// RUN: clang-extdef-mapping "%s" -- -fasm-blocks \
+// RUN:   -target x86_64-apple-darwin10 2>&1 | FileCheck %s
+// REQUIRES: x86-registered-target
 
 void Break() {
   __asm { int 3 }
 }
 
-// CHECK: {{c:@F@Break .*}}
+// CHECK: {{10:c:@F@Break}}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155396: [Sema][ObjC] Invalidate BlockDecl with invalid return expr & its parent BlockExpr

2023-07-24 Thread 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 rG106bde9ab2bd: [Sema][ObjC] Invalidate BlockDecl with invalid 
return expr & its parent… (authored by dingfei ).

Changed prior to commit:
  https://reviews.llvm.org/D155396?vs=543010&id=543447#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155396

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/test/AST/ast-dump-recovery.m


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast 
-frecovery-ast-type -ast-dump %s | FileCheck -strict-whitespace %s
+// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast 
-frecovery-ast-type -fblocks -ast-dump %s | FileCheck -strict-whitespace %s
 
 @interface Foo
 - (void)method:(int)n;
@@ -16,3 +16,11 @@
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'foo'
   foo.undef;
 }
+
+// CHECK:  |-VarDecl {{.*}} 'int (^)()' cinit
+// CHECK-NEXT: | `-RecoveryExpr {{.*}} ' (^)(void)' 
contains-errors lvalue
+// CHECK-NEXT: |   `-BlockExpr {{.*}} ' (^)(void)'
+// CHECK-NEXT: | `-BlockDecl {{.*}} invalid
+int (^gh63863)() = ^() {
+  return undef;
+};
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3730,6 +3730,11 @@
   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
 
+  if (auto *CurBlock = dyn_cast(CurCap);
+  CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
+  RetValExp->containsErrors())
+CurBlock->TheDecl->setInvalidDecl();
+
   return Result;
 }
 
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17159,6 +17159,9 @@
   if (getCurFunction())
 getCurFunction()->addBlock(BD);
 
+  if (BD->isInvalidDecl())
+return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
+  {Result}, Result->getType());
   return Result;
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@
 - Correcly diagnose jumps into statement expressions.
   This ensures the behavior of Clang is consistent with GCC.
   (`#63682 `_)
+- Invalidate BlockDecl with implicit return type, in case any of the return
+  value exprs is invalid. Propagating the error info up by replacing BlockExpr
+  with a RecoveryExpr. This fixes:
+  (`#63863 _`)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast -frecovery-ast-type -ast-dump %s | FileCheck -strict-whitespace %s
+// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast -frecovery-ast-type -fblocks -ast-dump %s | FileCheck -strict-whitespace %s
 
 @interface Foo
 - (void)method:(int)n;
@@ -16,3 +16,11 @@
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'foo'
   foo.undef;
 }
+
+// CHECK:  |-VarDecl {{.*}} 'int (^)()' cinit
+// CHECK-NEXT: | `-RecoveryExpr {{.*}} ' (^)(void)' contains-errors lvalue
+// CHECK-NEXT: |   `-BlockExpr {{.*}} ' (^)(void)'
+// CHECK-NEXT: | `-BlockDecl {{.*}} invalid
+int (^gh63863)() = ^() {
+  return undef;
+};
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3730,6 +3730,11 @@
   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
 
+  if (auto *CurBlock = dyn_cast(CurCap);
+  CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
+  RetValExp->containsErrors())
+CurBlock->TheDecl->setInvalidDecl();
+
   return Result;
 }
 
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17159,6 +17159,9 @@
   if (getCurFunction())
 getCurFunction()->addBlock(BD);
 
+  if (BD->isInvalidDecl())
+return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
+  {Result}, Resul

[PATCH] D155984: [Sema][ObjC] Invalidate BlockDecl with invalid ParmVarDecl

2023-07-24 Thread 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 rG3cb16f6d2ddd: [Sema][ObjC] Invalidate BlockDecl with invalid 
ParmVarDecl (authored by dingfei ).

Changed prior to commit:
  https://reviews.llvm.org/D155984?vs=543005&id=543451#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155984

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/ast-dump-recovery.m


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -24,3 +24,9 @@
 int (^gh63863)() = ^() {
   return undef;
 };
+
+// CHECK:  `-BlockExpr {{.*}} 'int (^)(int, int)'
+// CHECK-NEXT:   `-BlockDecl {{.*}} invalid
+int (^gh64005)(int, int) = ^(int, undefined b) {
+   return 1;
+};
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -16959,6 +16959,9 @@
 
   PushOnScopeChains(AI, CurBlock->TheScope);
 }
+
+if (AI->isInvalidDecl())
+  CurBlock->TheDecl->setInvalidDecl();
   }
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -674,6 +674,8 @@
   value exprs is invalid. Propagating the error info up by replacing BlockExpr
   with a RecoveryExpr. This fixes:
   (`#63863 _`)
+- Invalidate BlockDecl with invalid ParmVarDecl
+  (`#64005 _`)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -24,3 +24,9 @@
 int (^gh63863)() = ^() {
   return undef;
 };
+
+// CHECK:  `-BlockExpr {{.*}} 'int (^)(int, int)'
+// CHECK-NEXT:   `-BlockDecl {{.*}} invalid
+int (^gh64005)(int, int) = ^(int, undefined b) {
+   return 1;
+};
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -16959,6 +16959,9 @@
 
   PushOnScopeChains(AI, CurBlock->TheScope);
 }
+
+if (AI->isInvalidDecl())
+  CurBlock->TheDecl->setInvalidDecl();
   }
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -674,6 +674,8 @@
   value exprs is invalid. Propagating the error info up by replacing BlockExpr
   with a RecoveryExpr. This fixes:
   (`#63863 _`)
+- Invalidate BlockDecl with invalid ParmVarDecl
+  (`#64005 _`)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155985: [clang][ASTDumper] Remove redundant dump of BlockDecl's ParmVarDecl

2023-07-24 Thread 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 rG4b15bb9a317e: [clang][ASTDumper] Remove redundant dump of 
BlockDecl's ParmVarDecl (authored by dingfei ).

Changed prior to commit:
  https://reviews.llvm.org/D155985?vs=543003&id=543453#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155985

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/test/AST/ast-dump-decl-json.m
  clang/test/AST/ast-dump-decl.m


Index: clang/test/AST/ast-dump-decl.m
===
--- clang/test/AST/ast-dump-decl.m
+++ clang/test/AST/ast-dump-decl.m
@@ -142,12 +142,17 @@
 
 void TestBlockDecl(int x) {
   ^(int y, ...){ x; };
+  int z;
 }
 // CHECK:  FunctionDecl{{.*}}TestBlockDecl
 // CHECK:  BlockDecl {{.+}}  col:3 variadic
 // CHECK-NEXT:   ParmVarDecl{{.*}} y 'int'
 // CHECK-NEXT:   capture ParmVar{{.*}} 'x' 'int'
 // CHECK-NEXT:   CompoundStmt
+// CHECK-NEXT: ImplicitCastExpr
+// CHECK-NEXT:   DeclRefExpr{{.*}} 'x'
+// CHECK-NEXT: DeclStmt
+// CHECK-NEXT:   VarDecl{{.*}} z
 
 @interface B
 + (int) foo;
Index: clang/test/AST/ast-dump-decl-json.m
===
--- clang/test/AST/ast-dump-decl-json.m
+++ clang/test/AST/ast-dump-decl-json.m
@@ -1924,31 +1924,6 @@
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
 // CHECK-NEXT:]
-// CHECK-NEXT:   },
-// CHECK-NEXT:   {
-// CHECK-NEXT:"id": "0x{{.*}}",
-// CHECK-NEXT:"kind": "ParmVarDecl",
-// CHECK-NEXT:"loc": {
-// CHECK-NEXT: "offset": {{[0-9]+}},
-// CHECK-NEXT: "col": 9,
-// CHECK-NEXT: "tokLen": 1
-// CHECK-NEXT:},
-// CHECK-NEXT:"range": {
-// CHECK-NEXT: "begin": {
-// CHECK-NEXT:  "offset": {{[0-9]+}},
-// CHECK-NEXT:  "col": 5,
-// CHECK-NEXT:  "tokLen": 3
-// CHECK-NEXT: },
-// CHECK-NEXT: "end": {
-// CHECK-NEXT:  "offset": {{[0-9]+}},
-// CHECK-NEXT:  "col": 9,
-// CHECK-NEXT:  "tokLen": 1
-// CHECK-NEXT: }
-// CHECK-NEXT:},
-// CHECK-NEXT:"name": "y",
-// CHECK-NEXT:"type": {
-// CHECK-NEXT: "qualType": "int"
-// CHECK-NEXT:}
 // CHECK-NEXT:   }
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
Index: clang/include/clang/AST/ASTNodeTraverser.h
===
--- clang/include/clang/AST/ASTNodeTraverser.h
+++ clang/include/clang/AST/ASTNodeTraverser.h
@@ -104,7 +104,8 @@
 Visit(Comment, Comment);
 
   // Decls within functions are visited by the body.
-  if (!isa(*D) && !isa(*D)) {
+  if (!isa(*D) && !isa(*D) &&
+  !isa(*D)) {
 if (Traversal != TK_AsIs) {
   if (const auto *CTSD = dyn_cast(D)) 
{
 auto SK = CTSD->getSpecializationKind();
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -674,7 +674,8 @@
   value exprs is invalid. Propagating the error info up by replacing BlockExpr
   with a RecoveryExpr. This fixes:
   (`#63863 _`)
-- Invalidate BlockDecl with invalid ParmVarDecl
+- Invalidate BlockDecl with invalid ParmVarDecl. Remove redundant dump of
+  BlockDecl's ParmVarDecl
   (`#64005 _`)
 
 Bug Fixes to Compiler Builtins


Index: clang/test/AST/ast-dump-decl.m
===
--- clang/test/AST/ast-dump-decl.m
+++ clang/test/AST/ast-dump-decl.m
@@ -142,12 +142,17 @@
 
 void TestBlockDecl(int x) {
   ^(int y, ...){ x; };
+  int z;
 }
 // CHECK:  FunctionDecl{{.*}}TestBlockDecl
 // CHECK:  BlockDecl {{.+}}  col:3 variadic
 // CHECK-NEXT:   ParmVarDecl{{.*}} y 'int'
 // CHECK-NEXT:   capture ParmVar{{.*}} 'x' 'int'
 // CHECK-NEXT:   CompoundStmt
+// CHECK-NEXT: ImplicitCastExpr
+// CHECK-NEXT:   DeclRefExpr{{.*}} 'x'
+// CHECK-NEXT: DeclStmt
+// CHECK-NEXT:   VarDecl{{.*}} z
 
 @interface B
 + (int) foo;
Index: clang/test/AST/ast-dump-decl-json.m
===
--- clang/test/AST/ast-dump-decl-json.m
+++ clang/test/AST/ast-dump-decl-json.m
@@ -1924,31 +1924,6 @@
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
 // CHECK-NEXT:]
-// CHECK-NEXT:   },
-// CHECK-NEXT:   {
-// CHECK-NEXT:"id": "0x{{.*}}",
-// CHECK-NEXT:"kind": "ParmVarDecl",
-// CHECK-NEXT:"loc": {
-//

[PATCH] D157584: [clang][Sema] Skip access check on arrays of zero-length element

2023-08-11 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0f73a2406a16: [clang][Sema] Skip access check on arrays of 
zero-length element (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157584

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/array-bounds-zero-length-elem-gh64564.c


Index: clang/test/Sema/array-bounds-zero-length-elem-gh64564.c
===
--- /dev/null
+++ clang/test/Sema/array-bounds-zero-length-elem-gh64564.c
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple i686-apple-darwin -verify %s
+
+int a[][0]; // expected-warning {{tentative array definition assumed to have 
one element}}
+void gh64564_1(void) {
+  int b = a[0x1][0];
+}
+
+typedef struct {} S;
+S s[]; // expected-warning {{tentative array definition assumed to have one 
element}}
+void gh64564_2(void) {
+  S t = s[0x1];
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -17146,7 +17146,7 @@
   ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
   // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
   // pointer) bounds-checking isn't meaningful.
-  if (!ElemCharUnits)
+  if (!ElemCharUnits || ElemCharUnits->isZero())
 return;
   llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
   // If index has more active bits than address space, we already know
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -185,6 +185,8 @@
   terminated. Clang should now also recover better when an @end is missing
   between blocks.
   `Issue 64065 `_
+- Fixed a crash when check array access on zero-length element.
+  `Issue 64564 `_
 
 Target Specific Changes
 ---


Index: clang/test/Sema/array-bounds-zero-length-elem-gh64564.c
===
--- /dev/null
+++ clang/test/Sema/array-bounds-zero-length-elem-gh64564.c
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple i686-apple-darwin -verify %s
+
+int a[][0]; // expected-warning {{tentative array definition assumed to have one element}}
+void gh64564_1(void) {
+  int b = a[0x1][0];
+}
+
+typedef struct {} S;
+S s[]; // expected-warning {{tentative array definition assumed to have one element}}
+void gh64564_2(void) {
+  S t = s[0x1];
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -17146,7 +17146,7 @@
   ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
   // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
   // pointer) bounds-checking isn't meaningful.
-  if (!ElemCharUnits)
+  if (!ElemCharUnits || ElemCharUnits->isZero())
 return;
   llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
   // If index has more active bits than address space, we already know
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -185,6 +185,8 @@
   terminated. Clang should now also recover better when an @end is missing
   between blocks.
   `Issue 64065 `_
+- Fixed a crash when check array access on zero-length element.
+  `Issue 64564 `_
 
 Target Specific Changes
 ---
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157637: [ASTImporter][NFC] Fix typo in testcase

2023-08-11 Thread 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 rGafff91de082d: [ASTImporter][NFC] Fix typo in testcase 
(authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157637

Files:
  clang/unittests/AST/StructuralEquivalenceTest.cpp


Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -992,8 +992,8 @@
 
 TEST_F(StructuralEquivalenceRecordContextTest, NamespaceInlineTopLevel) {
   auto Decls =
-  makeNamedDecls("inline namespace A { class X; } }",
- "inline namespace B { class X; } }", Lang_CXX17, "X");
+  makeNamedDecls("inline namespace A { class X; }",
+ "inline namespace B { class X; }", Lang_CXX17, "X");
   EXPECT_TRUE(testStructuralMatch(Decls));
 }
 


Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -992,8 +992,8 @@
 
 TEST_F(StructuralEquivalenceRecordContextTest, NamespaceInlineTopLevel) {
   auto Decls =
-  makeNamedDecls("inline namespace A { class X; } }",
- "inline namespace B { class X; } }", Lang_CXX17, "X");
+  makeNamedDecls("inline namespace A { class X; }",
+ "inline namespace B { class X; }", Lang_CXX17, "X");
   EXPECT_TRUE(testStructuralMatch(Decls));
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157777: [ASTMatcher] Add matcher for 'MacroQualifiedType'

2023-08-16 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGec483c29a95c: [clang][ASTMatcher] Add matcher for 
'MacroQualifiedType' (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D15

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/ReleaseNotes.rst
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1838,6 +1838,20 @@
 namesType(typedefType()));
 }
 
+TEST_P(ASTMatchersTest, MacroQualifiedType) {
+  EXPECT_TRUE(matches(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  typedefDecl(hasType(pointerType(pointee(macroQualifiedType()));
+  EXPECT_TRUE(notMatches(
+  R"(
+typedef void (__attribute__((cdecl)) *Y)();
+  )",
+  typedefDecl(hasType(pointerType(pointee(macroQualifiedType()));
+}
+
 TEST_P(ASTMatchersTest, TemplateSpecializationType) {
   if (!GetParam().isCXX()) {
 return;
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -485,6 +485,7 @@
   REGISTER_MATCHER(lambdaCapture);
   REGISTER_MATCHER(lambdaExpr);
   REGISTER_MATCHER(linkageSpecDecl);
+  REGISTER_MATCHER(macroQualifiedType);
   REGISTER_MATCHER(materializeTemporaryExpr);
   REGISTER_MATCHER(member);
   REGISTER_MATCHER(memberExpr);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -1058,6 +1058,7 @@
 const AstTypeMatcher functionProtoType;
 const AstTypeMatcher parenType;
 const AstTypeMatcher blockPointerType;
+const AstTypeMatcher macroQualifiedType;
 const AstTypeMatcher memberPointerType;
 const AstTypeMatcher pointerType;
 const AstTypeMatcher objcObjectPointerType;
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7258,6 +7258,18 @@
 ///   matches "typedef int X"
 extern const AstTypeMatcher typedefType;
 
+/// Matches qualified types when the qualifier is applied via a macro.
+///
+/// Given
+/// \code
+///   #define CDECL __attribute__((cdecl))
+///   typedef void (CDECL *X)();
+///   typedef void (__attribute__((cdecl)) *Y)();
+/// \endcode
+/// macroQualifiedType()
+///   matches the type of the typedef declaration of \c X but not \c Y.
+extern const AstTypeMatcher macroQualifiedType;
+
 /// Matches enum types.
 ///
 /// Given
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -252,6 +252,7 @@
 
 - Add ``convertVectorExpr``.
 - Add ``dependentSizedExtVectorType``.
+- Add ``macroQualifiedType``.
 
 clang-format
 
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -2648,6 +2648,18 @@
 
 
 
+MatcherType>macroQualifiedTypeMatcherMacroQualifiedType>...
+Matches qualified types when the qualifier is applied via a macro.
+
+Given
+  #define CDECL __attribute__((cdecl))
+  typedef void (CDECL *X)();
+  typedef void (__attribute__((cdecl)) *Y)();
+macroQualifiedType()
+  matches the type of the typedef declaration of X but not Y.
+
+
+
 MatcherType>memberPointerTypeMatcherMemberPointerType>...
 Matches member pointer types.
 Given
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157780: [ASTImporter] Add import of MacroQualifiedType

2023-08-16 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b0eeb6cdbd7: [clang][ASTImporter] Add import of 
'MacroQualifiedType' (authored by dingfei ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157780

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


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8638,6 +8638,24 @@
   EXPECT_TRUE(ToCtx.hasSameType(ToInjTypedef, ToInjParmVar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportMacroQualifiedType) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromTy =
+  FirstDeclMatcher().match(From, macroQualifiedType());
+  auto *ToTy =
+  FirstDeclMatcher().match(To, macroQualifiedType());
+
+  EXPECT_TRUE(isa(FromTy->getUnderlyingType()));
+  EXPECT_TRUE(isa(ToTy->getUnderlyingType()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplateName) {
   constexpr auto TestCode = R"(
   template 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -419,6 +419,7 @@
 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
+ExpectedType VisitMacroQualifiedType(const MacroQualifiedType *T);
 
 // Importing declarations
 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
@@ -1701,6 +1702,17 @@
   return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
 }
 
+ExpectedType
+ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
+  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
+  if (!ToUnderlyingTypeOrErr)
+return ToUnderlyingTypeOrErr.takeError();
+
+  IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
+  return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
+   ToIdentifier);
+}
+
 //
 // Import Declarations
 //


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8638,6 +8638,24 @@
   EXPECT_TRUE(ToCtx.hasSameType(ToInjTypedef, ToInjParmVar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportMacroQualifiedType) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(
+  R"(
+#define CDECL __attribute__((cdecl))
+typedef void (CDECL *X)();
+  )",
+  Lang_CXX03, "", Lang_CXX03, "X");
+
+  auto *FromTy =
+  FirstDeclMatcher().match(From, macroQualifiedType());
+  auto *ToTy =
+  FirstDeclMatcher().match(To, macroQualifiedType());
+
+  EXPECT_TRUE(isa(FromTy->getUnderlyingType()));
+  EXPECT_TRUE(isa(ToTy->getUnderlyingType()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplateName) {
   constexpr auto TestCode = R"(
   template 
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -419,6 +419,7 @@
 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
+ExpectedType VisitMacroQualifiedType(const MacroQualifiedType *T);
 
 // Importing declarations
 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
@@ -1701,6 +1702,17 @@
   return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
 }
 
+ExpectedType
+ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
+  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
+  if (!ToUnderlyingTypeOrErr)
+return ToUnderlyingTypeOrErr.takeError();
+
+  IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
+  return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
+   ToIdentifier);
+}
+
 //
 // Import Declarations
 //---

  1   2   3   4   5   6   7   8   9   10   >