[PATCH] D124373: [clang] add parameter pack/pack expansion matchers

2022-05-01 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj abandoned this revision.
upsj added a comment.

I think we should be able to do this without adding new matchers globally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124373

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


[PATCH] D124730: [RISCV][NFC] Refactor RISC-V vector intrinsic utils.

2022-05-01 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 426276.
kito-cheng added a comment.

Changes:

- Extract more utils functions to RISCVVIntrinsicUtils


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124730

Files:
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -32,9 +32,6 @@
 class RVVEmitter {
 private:
   RecordKeeper &Records;
-  // Concat BasicType, LMUL and Proto as key
-  StringMap LegalTypes;
-  StringSet<> IllegalTypes;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -48,20 +45,11 @@
   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
   void createCodeGen(raw_ostream &o);
 
-  std::string getSuffixStr(char Type, int Log2LMUL, StringRef Prototypes);
-
 private:
   /// Create all intrinsics and add them to \p Out
   void createRVVIntrinsics(std::vector> &Out);
   /// Print HeaderCode in RVVHeader Record to \p Out
   void printHeaderCode(raw_ostream &OS);
-  /// Compute output and input types by applying different config (basic type
-  /// and LMUL with type transformers). It also record result of type in legal
-  /// or illegal set to avoid compute the  same config again. The result maybe
-  /// have illegal RVVType.
-  Optional computeTypes(BasicType BT, int Log2LMUL, unsigned NF,
-  ArrayRef PrototypeSeq);
-  Optional computeType(BasicType BT, int Log2LMUL, StringRef Proto);
 
   /// Emit Acrh predecessor definitions and body, assume the element of Defs are
   /// sorted by extension.
@@ -73,14 +61,39 @@
   // non-empty string.
   bool emitMacroRestrictionStr(RISCVPredefinedMacroT PredefinedMacros,
raw_ostream &o);
-  // Slice Prototypes string into sub prototype string and process each sub
-  // prototype string individually in the Handler.
-  void parsePrototypes(StringRef Prototypes,
-   std::function Handler);
 };
 
 } // namespace
 
+static BasicType ParseBasicType(char c) {
+  switch (c) {
+  case 'c':
+return BasicType::Int8;
+break;
+  case 's':
+return BasicType::Int16;
+break;
+  case 'i':
+return BasicType::Int32;
+break;
+  case 'l':
+return BasicType::Int64;
+break;
+  case 'x':
+return BasicType::Float16;
+break;
+  case 'f':
+return BasicType::Float32;
+break;
+  case 'd':
+return BasicType::Float64;
+break;
+
+  default:
+return BasicType::Unknown;
+  }
+}
+
 void emitCodeGenSwitchBody(const RVVIntrinsic *RVVI, raw_ostream &OS) {
   if (!RVVI->getIRName().empty())
 OS << "  ID = Intrinsic::riscv_" + RVVI->getIRName() + ";\n";
@@ -202,24 +215,28 @@
   constexpr int Log2LMULs[] = {-3, -2, -1, 0, 1, 2, 3};
   // Print RVV boolean types.
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('c', Log2LMUL, "m");
+auto T = RVVType::computeType(BasicType::Int8, Log2LMUL, TypeProfile::Mask);
 if (T.hasValue())
   printType(T.getValue());
   }
   // Print RVV int/float types.
   for (char I : StringRef("csil")) {
+BasicType BT = ParseBasicType(I);
 for (int Log2LMUL : Log2LMULs) {
-  auto T = computeType(I, Log2LMUL, "v");
+  auto T = RVVType::computeType(BT, Log2LMUL, TypeProfile::Vector);
   if (T.hasValue()) {
 printType(T.getValue());
-auto UT = computeType(I, Log2LMUL, "Uv");
+auto UT = RVVType::computeType(
+BT, Log2LMUL,
+TypeProfile(PrimitiveType::Vector, TypeModifier::UnsignedInteger));
 printType(UT.getValue());
   }
 }
   }
   OS << "#if defined(__riscv_zvfh)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('x', Log2LMUL, "v");
+auto T =
+RVVType::computeType(BasicType::Float16, Log2LMUL, TypeProfile::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -227,7 +244,8 @@
 
   OS << "#if defined(__riscv_f)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('f', Log2LMUL, "v");
+auto T =
+RVVType::computeType(BasicType::Float32, Log2LMUL, TypeProfile::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -235,7 +253,8 @@
 
   OS << "#if defined(__riscv_d)\n";
   for (int Log2LMUL : Log2LMULs) {
-auto T = computeType('d', Log2LMUL, "v");
+auto T =
+RVVType::computeType(BasicType::Float64, Log2LMUL, TypeProfile::Vector);
 if (T.hasValue())
   printType(T.getValue());
   }
@@ -359,32 +378,6 @@
   OS << "\n";
 }
 
-void RVVEmitter::parsePrototypes(StringRef Prototypes,
- std::function Handler) {
-  const StringRef Primaries("evwqom0ztul");
-  while (!Prototypes.empty()) {
-size_t Idx = 

[clang] 43c146c - [clang-format] Take out common code for parsing blocks NFC

2022-05-01 Thread via cfe-commits

Author: sstwcw
Date: 2022-05-01T08:58:40Z
New Revision: 43c146c96d8e4607266f2c2ef74c17d4170fc248

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

LOG: [clang-format] Take out common code for parsing blocks NFC

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 1e2f4d6761e1e..d20cead7d3212 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2713,55 +2713,49 @@ void UnwrappedLineParser::parseNew() {
   } while (!eof());
 }
 
-void UnwrappedLineParser::parseForOrWhileLoop() {
-  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
- "'for', 'while' or foreach macro expected");
-  nextToken();
-  // JS' for await ( ...
-  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
-nextToken();
-  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
-nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
-
+void UnwrappedLineParser::parseLoopBody(bool TryRemoveBraces,
+bool WrapRightBrace) {
   keepAncestorBraces();
 
   if (FormatTok->is(tok::l_brace)) {
 FormatToken *LeftBrace = FormatTok;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
-if (Style.RemoveBracesLLVM) {
+if (TryRemoveBraces) {
   assert(!NestedTooDeep.empty());
   if (!NestedTooDeep.back())
 markOptionalBraces(LeftBrace);
 }
-addUnwrappedLine();
+if (WrapRightBrace)
+  addUnwrappedLine();
   } else {
 parseUnbracedBody();
   }
 
-  if (Style.RemoveBracesLLVM)
+  if (TryRemoveBraces)
 NestedTooDeep.pop_back();
 }
 
-void UnwrappedLineParser::parseDoWhile() {
-  assert(FormatTok->is(tok::kw_do) && "'do' expected");
+void UnwrappedLineParser::parseForOrWhileLoop() {
+  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
+ "'for', 'while' or foreach macro expected");
   nextToken();
+  // JS' for await ( ...
+  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
+nextToken();
+  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
+nextToken();
+  if (FormatTok->is(tok::l_paren))
+parseParens();
 
-  keepAncestorBraces();
+  parseLoopBody(Style.RemoveBracesLLVM, true);
+}
 
-  if (FormatTok->is(tok::l_brace)) {
-CompoundStatementIndenter Indenter(this, Style, Line->Level);
-parseBlock();
-if (Style.BraceWrapping.BeforeWhile)
-  addUnwrappedLine();
-  } else {
-parseUnbracedBody();
-  }
+void UnwrappedLineParser::parseDoWhile() {
+  assert(FormatTok->is(tok::kw_do) && "'do' expected");
+  nextToken();
 
-  if (Style.RemoveBracesLLVM)
-NestedTooDeep.pop_back();
+  parseLoopBody(false, Style.BraceWrapping.BeforeWhile);
 
   // FIXME: Add error handling.
   if (!FormatTok->is(tok::kw_while)) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 798bae24ad075..3334b5bad97b4 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -125,6 +125,7 @@ class UnwrappedLineParser {
   bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
+  void parseLoopBody(bool TryRemoveBraces, bool WrapRightBrace);
   void parseForOrWhileLoop();
   void parseDoWhile();
   void parseLabel(bool LeftAlignLabel = false);



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


[PATCH] D121757: [clang-format] Take out common code for parsing blocks NFC

2022-05-01 Thread sstwcw via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG43c146c96d8e: [clang-format] Take out common code for 
parsing blocks NFC (authored by sstwcw).

Changed prior to commit:
  https://reviews.llvm.org/D121757?vs=420653&id=426277#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121757

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h


Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -125,6 +125,7 @@
   bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
+  void parseLoopBody(bool TryRemoveBraces, bool WrapRightBrace);
   void parseForOrWhileLoop();
   void parseDoWhile();
   void parseLabel(bool LeftAlignLabel = false);
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2713,55 +2713,49 @@
   } while (!eof());
 }
 
-void UnwrappedLineParser::parseForOrWhileLoop() {
-  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
- "'for', 'while' or foreach macro expected");
-  nextToken();
-  // JS' for await ( ...
-  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
-nextToken();
-  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
-nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
-
+void UnwrappedLineParser::parseLoopBody(bool TryRemoveBraces,
+bool WrapRightBrace) {
   keepAncestorBraces();
 
   if (FormatTok->is(tok::l_brace)) {
 FormatToken *LeftBrace = FormatTok;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
-if (Style.RemoveBracesLLVM) {
+if (TryRemoveBraces) {
   assert(!NestedTooDeep.empty());
   if (!NestedTooDeep.back())
 markOptionalBraces(LeftBrace);
 }
-addUnwrappedLine();
+if (WrapRightBrace)
+  addUnwrappedLine();
   } else {
 parseUnbracedBody();
   }
 
-  if (Style.RemoveBracesLLVM)
+  if (TryRemoveBraces)
 NestedTooDeep.pop_back();
 }
 
-void UnwrappedLineParser::parseDoWhile() {
-  assert(FormatTok->is(tok::kw_do) && "'do' expected");
+void UnwrappedLineParser::parseForOrWhileLoop() {
+  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
+ "'for', 'while' or foreach macro expected");
   nextToken();
+  // JS' for await ( ...
+  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
+nextToken();
+  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
+nextToken();
+  if (FormatTok->is(tok::l_paren))
+parseParens();
 
-  keepAncestorBraces();
+  parseLoopBody(Style.RemoveBracesLLVM, true);
+}
 
-  if (FormatTok->is(tok::l_brace)) {
-CompoundStatementIndenter Indenter(this, Style, Line->Level);
-parseBlock();
-if (Style.BraceWrapping.BeforeWhile)
-  addUnwrappedLine();
-  } else {
-parseUnbracedBody();
-  }
+void UnwrappedLineParser::parseDoWhile() {
+  assert(FormatTok->is(tok::kw_do) && "'do' expected");
+  nextToken();
 
-  if (Style.RemoveBracesLLVM)
-NestedTooDeep.pop_back();
+  parseLoopBody(false, Style.BraceWrapping.BeforeWhile);
 
   // FIXME: Add error handling.
   if (!FormatTok->is(tok::kw_while)) {


Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -125,6 +125,7 @@
   bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
+  void parseLoopBody(bool TryRemoveBraces, bool WrapRightBrace);
   void parseForOrWhileLoop();
   void parseDoWhile();
   void parseLabel(bool LeftAlignLabel = false);
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2713,55 +2713,49 @@
   } while (!eof());
 }
 
-void UnwrappedLineParser::parseForOrWhileLoop() {
-  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
- "'for', 'while' or foreach macro expected");
-  nextToken();
-  // JS' for await ( ...
-  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
-nextToken();
-  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
-nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
-
+void UnwrappedLineParser::parseLoopBody(bool TryRemoveBraces,
+bool WrapRightBrace) {
   keepAncestorBraces();
 
   if (F

[PATCH] D124736: [CodeGen] Use ABI alignment for placement new

2022-05-01 Thread Daniel Bertalan via Phabricator via cfe-commits
BertalanD created this revision.
Herald added a project: All.
BertalanD requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If we do not know the alignment of the operand, we can't assume it has
the preferred alignment. It might be e.g. a pointer to a struct member
which follows ABI alignment rules.

This makes UBSAN no longer report "constructor call on misaligned
address" when constructing a double into a struct field of type double
on i686. The psABI specifies an alignment of 4 bytes, but the preferred
alignment used by Clang is 8 bytes.

Fixes #54845


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124736

Files:
  clang/lib/CodeGen/CGExprCXX.cpp


Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -1573,7 +1573,7 @@
   llvm::Value *allocSize =
 EmitCXXNewAllocSize(*this, E, minElements, numElements,
 allocSizeWithoutCookie);
-  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+  CharUnits allocAlign;
 
   // Emit the allocation call.  If the allocator is a global placement
   // operator, just "inline" it directly.
@@ -1583,6 +1583,8 @@
 assert(E->getNumPlacementArgs() == 1);
 const Expr *arg = *E->placement_arguments().begin();
 
+allocAlign = getContext().getTypeAlignInChars(allocType);
+
 LValueBaseInfo BaseInfo;
 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
 
@@ -1605,6 +1607,8 @@
   allocator->getType()->castAs();
 unsigned ParamsToSkip = 0;
 
+allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+
 // The allocation size is the first argument.
 QualType sizeType = getContext().getSizeType();
 allocatorArgs.add(RValue::get(allocSize), sizeType);


Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -1573,7 +1573,7 @@
   llvm::Value *allocSize =
 EmitCXXNewAllocSize(*this, E, minElements, numElements,
 allocSizeWithoutCookie);
-  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+  CharUnits allocAlign;
 
   // Emit the allocation call.  If the allocator is a global placement
   // operator, just "inline" it directly.
@@ -1583,6 +1583,8 @@
 assert(E->getNumPlacementArgs() == 1);
 const Expr *arg = *E->placement_arguments().begin();
 
+allocAlign = getContext().getTypeAlignInChars(allocType);
+
 LValueBaseInfo BaseInfo;
 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
 
@@ -1605,6 +1607,8 @@
   allocator->getType()->castAs();
 unsigned ParamsToSkip = 0;
 
+allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+
 // The allocation size is the first argument.
 QualType sizeType = getContext().getSizeType();
 allocatorArgs.add(RValue::get(allocSize), sizeType);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-05-01 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 426281.
kito-cheng marked 2 inline comments as done.
kito-cheng added a comment.

Changes:

- Split out refactor part to D124730 .
- Add more comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

Files:
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaRVVLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h

Index: clang/utils/TableGen/TableGenBackends.h
===
--- clang/utils/TableGen/TableGenBackends.h
+++ clang/utils/TableGen/TableGenBackends.h
@@ -110,6 +110,7 @@
 void EmitRVVHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltins(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitRVVBuiltinSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
 void EmitCdeHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitCdeBuiltinDef(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -88,6 +88,7 @@
   GenRISCVVectorHeader,
   GenRISCVVectorBuiltins,
   GenRISCVVectorBuiltinCG,
+  GenRISCVVectorBuiltinSema,
   GenAttrDocs,
   GenDiagDocs,
   GenOptDocs,
@@ -243,6 +244,8 @@
"Generate riscv_vector_builtins.inc for clang"),
 clEnumValN(GenRISCVVectorBuiltinCG, "gen-riscv-vector-builtin-codegen",
"Generate riscv_vector_builtin_cg.inc for clang"),
+clEnumValN(GenRISCVVectorBuiltinSema, "gen-riscv-vector-builtin-sema",
+   "Generate riscv_vector_builtin_sema.inc for clang"),
 clEnumValN(GenAttrDocs, "gen-attr-docs",
"Generate attribute documentation"),
 clEnumValN(GenDiagDocs, "gen-diag-docs",
@@ -458,6 +461,9 @@
   case GenRISCVVectorBuiltinCG:
 EmitRVVBuiltinCG(Records, OS);
 break;
+  case GenRISCVVectorBuiltinSema:
+EmitRVVBuiltinSema(Records, OS);
+break;
   case GenAttrDocs:
 EmitClangAttrDocs(Records, OS);
 break;
Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
@@ -29,9 +30,30 @@
 using namespace clang::RISCV;
 
 namespace {
+struct SemaRecord {
+  std::string Name;
+  std::string MangledName;
+  std::string TypeRange;
+  std::vector Log2LMULList;
+  std::vector RequiredFeatures;
+
+  SmallVector ProtoSeq;
+  SmallVector ProtoMaskSeq;
+  SmallVector SuffixProto;
+  SmallVector MangledSuffixProto;
+
+  unsigned NF;
+};
+
 class RVVEmitter {
 private:
   RecordKeeper &Records;
+  // Concat BasicType, LMUL and Proto as key
+  StringMap LegalTypes;
+  StringSet<> IllegalTypes;
+
+  std::vector SemaRecords;
+  std::vector SemaSignatureTable;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -45,22 +67,20 @@
   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
   void createCodeGen(raw_ostream &o);
 
+  /// Emit all the information needed by SemaRVVLookup.cpp.
+  void createSema(raw_ostream &o);
+
 private:
   /// Create all intrinsics and add them to \p Out
   void createRVVIntrinsics(std::vector> &Out);
+  unsigned GetSemaSignatureIndex(const SmallVector &Signature);
   /// Print HeaderCode in RVVHeader Record to \p Out
   void printHeaderCode(raw_ostream &OS);
 
-  /// Emit Acrh predecessor definitions and body, assume the element of Defs are
-  /// sorted by extension.
-  void emitArchMacroAndBody(
-  std::vector> &Defs, raw_ostream &o,
-  std::function);
+  void ConstructSemaSignatureTable();
 
-  // Emit the architecture preprocessor definitions. Return true when emits
-  // non-empty string.
-  bool emitMacroRestrictionStr(RISCVPredefinedMacroT PredefinedMacros,
-   raw_ostream &o);
+  void EmitSemaRecords(raw_ostream &OS);
+  void EmitSemaSignatureTable(raw_ostream &OS);
 };
 
 } // namespace
@@ -174,7 +194,6 @@
 // RVVEmitter implementation
 //===--

[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

2022-05-01 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:586
+
+  auto Not = hasOperatorName("!");
+  auto Or = hasOperatorName("||");

This whole implementation would be alot simpler(and likely faster) if you 
matched on the generic case then in the check callback work out what 
replacement you need.
```lang=c++
Finder->addMatcher(
unaryOperator(
Not,
hasUnaryOperand(binaryOperator(
hasAnyOperatorName("&&", "||"),
hasEitherOperand(unaryOperator(Not).bind(Demorgan),
this);
```



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:598-599
+  auto UnlessNotLHS = unless(hasLHS(NotOp));
+  // match !(!a || b)
+  Finder->addMatcher(unaryOperator(Not, hasUnaryOperand(binaryOperator(
+Or, UnlessNotRHS, NotLHS, RHS)))

Maybe I'm overthinking this, but how come you don't need the match on the 
ParenExpr?
Is there some traversal mode?



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:139
 
+- Expanded :doc:`readability-simplify-boolean-expr
+  ` to simplify 
expressions

Eugene.Zelenko wrote:
> Please use alphabetical order for such entries.
@LegalizeAdulthood I've pushed the change to alphabetize the list in 
rG8a9e2dd48d81 seperately, please rebase.


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

https://reviews.llvm.org/D124650

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


[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-05-01 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 426284.
kito-cheng marked 4 inline comments as done.
kito-cheng added a comment.

Changes:

- Add more comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

Files:
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaRVVLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h

Index: clang/utils/TableGen/TableGenBackends.h
===
--- clang/utils/TableGen/TableGenBackends.h
+++ clang/utils/TableGen/TableGenBackends.h
@@ -110,6 +110,7 @@
 void EmitRVVHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltins(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitRVVBuiltinSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
 void EmitCdeHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitCdeBuiltinDef(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -88,6 +88,7 @@
   GenRISCVVectorHeader,
   GenRISCVVectorBuiltins,
   GenRISCVVectorBuiltinCG,
+  GenRISCVVectorBuiltinSema,
   GenAttrDocs,
   GenDiagDocs,
   GenOptDocs,
@@ -243,6 +244,8 @@
"Generate riscv_vector_builtins.inc for clang"),
 clEnumValN(GenRISCVVectorBuiltinCG, "gen-riscv-vector-builtin-codegen",
"Generate riscv_vector_builtin_cg.inc for clang"),
+clEnumValN(GenRISCVVectorBuiltinSema, "gen-riscv-vector-builtin-sema",
+   "Generate riscv_vector_builtin_sema.inc for clang"),
 clEnumValN(GenAttrDocs, "gen-attr-docs",
"Generate attribute documentation"),
 clEnumValN(GenDiagDocs, "gen-diag-docs",
@@ -458,6 +461,9 @@
   case GenRISCVVectorBuiltinCG:
 EmitRVVBuiltinCG(Records, OS);
 break;
+  case GenRISCVVectorBuiltinSema:
+EmitRVVBuiltinSema(Records, OS);
+break;
   case GenAttrDocs:
 EmitClangAttrDocs(Records, OS);
 break;
Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
@@ -29,9 +30,48 @@
 using namespace clang::RISCV;
 
 namespace {
+struct SemaRecord {
+  // Intrinsic name, e.g. vadd_vv
+  std::string Name;
+
+  // Overloaded intrinsic name, could be empty if can be computed from Name
+  // e.g. vadd
+  std::string OverloadedName;
+
+  // Supported type, mask of BasicType
+  unsigned TypeRangeMask;
+
+  // Supported LMUL.
+  unsigned Log2LMULMask;
+
+  // Required target features for this intrinsic.
+  std::vector RequiredFeatures;
+
+  // Prototype for this intrinsic.
+  SmallVector Prototype;
+
+  // Prototype for masked intrinsic.
+  SmallVector MaskedPrototype;
+
+  // Suffix of intrinsic name.
+  SmallVector Suffix;
+
+  // Suffix of overloaded intrinsic name.
+  SmallVector OverloadedSuffix;
+
+  // Number of field, large than 1 if it's segment load/store.
+  unsigned NF;
+};
+
 class RVVEmitter {
 private:
   RecordKeeper &Records;
+  // Concat BasicType, LMUL and Proto as key
+  StringMap LegalTypes;
+  StringSet<> IllegalTypes;
+
+  std::vector SemaRecords;
+  std::vector SemaSignatureTable;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -45,22 +85,27 @@
   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
   void createCodeGen(raw_ostream &o);
 
+  /// Emit all the information needed by SemaRVVLookup.cpp.
+  /// We've large number of intrinsic function for RVV, creating a customized
+  /// could speed up the compilation time.
+  void createSema(raw_ostream &o);
+
 private:
   /// Create all intrinsics and add them to \p Out
   void createRVVIntrinsics(std::vector> &Out);
   /// Print HeaderCode in RVVHeader Record to \p Out
   void printHeaderCode(raw_ostream &OS);
 
-  /// Emit Acrh predecessor definitions and body, assume the element of Defs are
-  /// sorted by extension.
-  void emitArchMacroAndBody(
-  std::vector> &Defs, raw_ostream &o,
-  std::function);
+  ///

[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-05-01 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added inline comments.



Comment at: clang/lib/Sema/SemaRVVLookup.cpp:91
+struct RVVIntrinsicDef {
+  std::string Name;
+  std::string GenericName;

khchen wrote:
> why do we need to declare Name as std::string here but RVVIntrinsicRecord use 
> `const char*`?
`RVVIntrinsicRecord::Name` is raw name of a intrinsic, `RVVIntrinsicDef::Name` 
is expanded with type infos, e.g. `RVVIntrinsicRecord::Name` is `vadd` and  
`RVVIntrinsicDef::Name` is `vadd_vv_i32m1`.



Comment at: clang/lib/Sema/SemaRVVLookup.cpp:92
+  std::string Name;
+  std::string GenericName;
+  std::string BuiltinName;

khchen wrote:
> Nit: I think we use the `overload` terminology rather than `generic`.
Updated.



Comment at: clang/lib/Sema/SemaRVVLookup.cpp:359-371
+  if (!Record.MangledName)
+MangledName = StringRef(Record.Name).split("_").first.str();
+  else
+MangledName = Record.MangledName;
+  if (!SuffixStr.empty())
+Name += "_" + SuffixStr.str();
+  if (!MangledSuffixStr.empty())

khchen wrote:
> IIUC, above code initialize the BuiltinName, Name and MangledName same with 
> RVVIntrinsic::RVVIntrinsic did, right?
> If yes, I think we need to have some comment note that.
More comment added.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

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


[PATCH] D111617: [RISCV] Lazily add RVV C intrinsics.

2022-05-01 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 426285.
kito-cheng marked 2 inline comments as done.
kito-cheng added a comment.

Changes:

- Minor tweak.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111617

Files:
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaRVVLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h

Index: clang/utils/TableGen/TableGenBackends.h
===
--- clang/utils/TableGen/TableGenBackends.h
+++ clang/utils/TableGen/TableGenBackends.h
@@ -110,6 +110,7 @@
 void EmitRVVHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltins(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitRVVBuiltinCG(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitRVVBuiltinSema(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
 void EmitCdeHeader(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitCdeBuiltinDef(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -88,6 +88,7 @@
   GenRISCVVectorHeader,
   GenRISCVVectorBuiltins,
   GenRISCVVectorBuiltinCG,
+  GenRISCVVectorBuiltinSema,
   GenAttrDocs,
   GenDiagDocs,
   GenOptDocs,
@@ -243,6 +244,8 @@
"Generate riscv_vector_builtins.inc for clang"),
 clEnumValN(GenRISCVVectorBuiltinCG, "gen-riscv-vector-builtin-codegen",
"Generate riscv_vector_builtin_cg.inc for clang"),
+clEnumValN(GenRISCVVectorBuiltinSema, "gen-riscv-vector-builtin-sema",
+   "Generate riscv_vector_builtin_sema.inc for clang"),
 clEnumValN(GenAttrDocs, "gen-attr-docs",
"Generate attribute documentation"),
 clEnumValN(GenDiagDocs, "gen-diag-docs",
@@ -458,6 +461,9 @@
   case GenRISCVVectorBuiltinCG:
 EmitRVVBuiltinCG(Records, OS);
 break;
+  case GenRISCVVectorBuiltinSema:
+EmitRVVBuiltinSema(Records, OS);
+break;
   case GenAttrDocs:
 EmitClangAttrDocs(Records, OS);
 break;
Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
@@ -29,9 +30,48 @@
 using namespace clang::RISCV;
 
 namespace {
+struct SemaRecord {
+  // Intrinsic name, e.g. vadd_vv
+  std::string Name;
+
+  // Overloaded intrinsic name, could be empty if can be computed from Name
+  // e.g. vadd
+  std::string OverloadedName;
+
+  // Supported type, mask of BasicType
+  unsigned TypeRangeMask;
+
+  // Supported LMUL.
+  unsigned Log2LMULMask;
+
+  // Required target features for this intrinsic.
+  std::vector RequiredFeatures;
+
+  // Prototype for this intrinsic.
+  SmallVector Prototype;
+
+  // Prototype for masked intrinsic.
+  SmallVector MaskedPrototype;
+
+  // Suffix of intrinsic name.
+  SmallVector Suffix;
+
+  // Suffix of overloaded intrinsic name.
+  SmallVector OverloadedSuffix;
+
+  // Number of field, large than 1 if it's segment load/store.
+  unsigned NF;
+};
+
 class RVVEmitter {
 private:
   RecordKeeper &Records;
+  // Concat BasicType, LMUL and Proto as key
+  StringMap LegalTypes;
+  StringSet<> IllegalTypes;
+
+  std::vector SemaRecords;
+  std::vector SemaSignatureTable;
 
 public:
   RVVEmitter(RecordKeeper &R) : Records(R) {}
@@ -45,22 +85,27 @@
   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
   void createCodeGen(raw_ostream &o);
 
+  /// Emit all the information needed by SemaRVVLookup.cpp.
+  /// We've large number of intrinsic function for RVV, creating a customized
+  /// could speed up the compilation time.
+  void createSema(raw_ostream &o);
+
 private:
   /// Create all intrinsics and add them to \p Out
   void createRVVIntrinsics(std::vector> &Out);
   /// Print HeaderCode in RVVHeader Record to \p Out
   void printHeaderCode(raw_ostream &OS);
 
-  /// Emit Acrh predecessor definitions and body, assume the element of Defs are
-  /// sorted by extension.
-  void emitArchMacroAndBody(
-  std::vector> &Defs, raw_ostream &o,
-  std::function);
+  /// Const

[clang] 57c5516 - [analyzer] Fix return of llvm::StringRef to destroyed std::string

2022-05-01 Thread Andrew Ng via cfe-commits

Author: Andrew Ng
Date: 2022-05-01T12:24:32+01:00
New Revision: 57c55165ebe8283b71ea785d2b0217119f8c5c51

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

LOG: [analyzer] Fix return of llvm::StringRef to destroyed std::string

This issue was discovered whilst testing with ASAN.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
index c8eab32880943..514f53b4804f5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
@@ -98,11 +98,13 @@ class ObjCAutoreleaseWriteChecker : public 
Checker {
 };
 }
 
-static inline std::vector toRefs(std::vector V) {
+static inline std::vector
+toRefs(const std::vector &V) {
   return std::vector(V.begin(), V.end());
 }
 
-static decltype(auto) callsNames(std::vector FunctionNames) {
+static decltype(auto)
+callsNames(const std::vector &FunctionNames) {
   return callee(functionDecl(hasAnyName(toRefs(FunctionNames;
 }
 



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


[PATCH] D124683: [analyzer] Fix return of llvm::StringRef to destroyed std::string

2022-05-01 Thread Andrew Ng via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG57c55165ebe8: [analyzer] Fix return of llvm::StringRef to 
destroyed std::string (authored by andrewng).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124683

Files:
  clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
@@ -98,11 +98,13 @@
 };
 }
 
-static inline std::vector toRefs(std::vector V) {
+static inline std::vector
+toRefs(const std::vector &V) {
   return std::vector(V.begin(), V.end());
 }
 
-static decltype(auto) callsNames(std::vector FunctionNames) {
+static decltype(auto)
+callsNames(const std::vector &FunctionNames) {
   return callee(functionDecl(hasAnyName(toRefs(FunctionNames;
 }
 


Index: clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
@@ -98,11 +98,13 @@
 };
 }
 
-static inline std::vector toRefs(std::vector V) {
+static inline std::vector
+toRefs(const std::vector &V) {
   return std::vector(V.begin(), V.end());
 }
 
-static decltype(auto) callsNames(std::vector FunctionNames) {
+static decltype(auto)
+callsNames(const std::vector &FunctionNames) {
   return callee(functionDecl(hasAnyName(toRefs(FunctionNames;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3484189 , @rjmccall wrote:

> IIRC, the reason it works it that way is that "warnings which default to an 
> error" are really "errors which you can explicitly downgrade to a warning".  
> Maybe those ought to be different categories, or maybe we ought to just be 
> telling people to downgrade this specific diagnostic instead of generally 
> using `-Wno-error`.

Thanks for the background John! That seems defensible, but I think we're still 
in a confused state that we should do something about. A warning which default 
to an error is not sufficiently warning-like to be disabled via `-w` but isn't 
sufficiently error-like to be disabled via `-Wno-error`. IMO, one or the other 
of those options should work with a diagnostic like this.

However, for the time being, the advice is to use 
`-Wno-error=implicit-function-declaration`, which is what's documented in the 
release note. The commit message had a shorthand suggesting -Wno-error, but my 
intent was to suggest people narrowly disable the error instead of broadly 
disable them all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-01 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: clang/include/clang/Driver/Options.td:3989
 Group;
-def save_temps_EQ : Joined<["-", "--"], "save-temps=">, Flags<[CC1Option, 
NoXarchOption]>,
+def save_temps_EQ : Joined<["-", "--"], "save-temps=">, 
Flags<[CC1Option,FlangOption,NoXarchOption]>,
   HelpText<"Save intermediate compilation results.">;

schweitz wrote:
> nit: I noticed that this is getting rid of spaces after commas on a few 
> lines. Is there any sense of a prior style being used in that regard?
I swear that somebody recently requested that I remove a space in one of my 
patches. I've tried finding it and failed ... I must have dreamed it!

Thanks Eric, I'll revert this change :)



Comment at: clang/include/clang/Driver/Options.td:4131
 def : Flag<["-"], "no-integrated-as">, Alias,
-  Flags<[CC1Option, NoXarchOption]>;
+  Flags<[CC1Option,FlangOption,NoXarchOption]>;
 

unterumarmung wrote:
> Why not to add `FC1Option` here and elsewhere like it's done for `CC1Option`?
I'm not 100% sure what `-fno-integrated-as` controls in Clang's frontend 
driver, `clang -cc1`. I'm guessing that it might related to using/not-using 
LLVM's MCAsmParser. Perhaps for inline assembly?

In Flang, I'm only focusing on `-save-temps` for which I need to make sure that 
we don't try to call `flang-new -fc1as` or something similar (it does not 
exist). Instead, `-save-temps` will have to rely on an external assembler.

So, we basically don't require -`fno-integrated-as` in `flang-new -fc1` just 
yet (that's what `FC1Option` is for - marking an option as available in the 
frontend driver).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

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


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

2022-05-01 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:586
+
+  auto Not = hasOperatorName("!");
+  auto Or = hasOperatorName("||");

njames93 wrote:
> This whole implementation would be alot simpler(and likely faster) if you 
> matched on the generic case then in the check callback work out what 
> replacement you need.
> ```lang=c++
> Finder->addMatcher(
> unaryOperator(
> Not,
> hasUnaryOperand(binaryOperator(
> hasAnyOperatorName("&&", "||"),
> hasEitherOperand(unaryOperator(Not).bind(Demorgan),
> this);
> ```
Come to think of it, you wouldn't even need to work out which. Just remove the 
outer `!`, Exchange `||` with `&&` and invert each side of the binary operator.


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

https://reviews.llvm.org/D124650

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


[clang] 955a05a - [clang][dataflow] Optimize flow condition representation

2022-05-01 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-05-01T16:25:29Z
New Revision: 955a05a2782ee19d6f4bce6bf5d1c4a8f591f0f3

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

LOG: [clang][dataflow] Optimize flow condition representation

Enable efficient implementation of context-aware joining of distinct
boolean values. It can be used to join distinct boolean values while
preserving flow condition information.

Flow conditions are represented as Token <=> Clause iff formulas. To
perform context-aware joining, one can simply add the tokens of flow
conditions to the formula when joining distinct boolean values, e.g:
`makeOr(makeAnd(FC1, Val1), makeAnd(FC2, Val2))`. This significantly
simplifies the implementation of `Environment::join`.

This patch removes the `DataflowAnalysisContext::getSolver` method.
The `DataflowAnalysisContext::flowConditionImplies` method should be
used instead.

Reviewed-by: ymandel, xazax.hun

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index 8df88301dff83..5cf681e4e489c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -21,6 +21,7 @@
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
 #include 
 #include 
 #include 
@@ -45,9 +46,6 @@ class DataflowAnalysisContext {
 assert(this->S != nullptr);
   }
 
-  /// Returns the SAT solver instance that is available in this context.
-  Solver &getSolver() const { return *S; }
-
   /// Takes ownership of `Loc` and returns a reference to it.
   ///
   /// Requirements:
@@ -151,7 +149,39 @@ class DataflowAnalysisContext {
   /// calls with the same argument will return the same result.
   BoolValue &getOrCreateNegationValue(BoolValue &Val);
 
+  /// Creates a fresh flow condition and returns a token that identifies it. 
The
+  /// token can be used to perform various operations on the flow condition 
such
+  /// as adding constraints to it, forking it, joining it with another flow
+  /// condition, or checking implications.
+  AtomicBoolValue &makeFlowConditionToken();
+
+  /// Adds `Constraint` to the flow condition identified by `Token`.
+  void addFlowConditionConstraint(AtomicBoolValue &Token,
+  BoolValue &Constraint);
+
+  /// Creates a new flow condition with the same constraints as the flow
+  /// condition identified by `Token` and returns its token.
+  AtomicBoolValue &forkFlowCondition(AtomicBoolValue &Token);
+
+  /// Creates a new flow condition that represents the disjunction of the flow
+  /// conditions identified by `FirstToken` and `SecondToken`, and returns its
+  /// token.
+  AtomicBoolValue &joinFlowConditions(AtomicBoolValue &FirstToken,
+  AtomicBoolValue &SecondToken);
+
+  /// Returns true if and only if the constraints of the flow condition
+  /// identified by `Token` imply that `Val` is true.
+  bool flowConditionImplies(AtomicBoolValue &Token, BoolValue &Val);
+
 private:
+  /// Adds all constraints of the flow condition identified by `Token` and all
+  /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used
+  /// to track tokens of flow conditions that were already visited by recursive
+  /// calls.
+  void addTransitiveFlowConditionConstraints(
+  AtomicBoolValue &Token, llvm::DenseSet &Constraints,
+  llvm::DenseSet &VisitedTokens) const;
+
   std::unique_ptr S;
 
   // Storage for the state of a program.
@@ -178,6 +208,27 @@ class DataflowAnalysisContext {
   llvm::DenseMap, DisjunctionValue *>
   DisjunctionVals;
   llvm::DenseMap NegationVals;
+
+  // Flow conditions are tracked symbolically: each unique flow condition is
+  // associated with a fresh symbolic variable (token), bound to the clause 
that
+  // defines the flow condition. Conceptually, each binding corresponds to an
+  // "iff" of the form `FC <=> (C1 ^ C2 ^ ...)` where `FC` is a flow condition
+  // token (an atomic boolean) and `Ci`s are the set of constraints in the flow
+  // flow condition clause. Internally, we do not record the formula directly 
as
+  // an "iff"

[PATCH] D124395: [clang][dataflow] Optimize flow condition representation

2022-05-01 Thread Stanislav Gatev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG955a05a2782e: [clang][dataflow] Optimize flow condition 
representation (authored by sgatev).

Changed prior to commit:
  https://reviews.llvm.org/D124395?vs=425221&id=426298#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124395

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
@@ -90,4 +90,54 @@
   EXPECT_NE(&NotX1, &NotY);
 }
 
+TEST_F(DataflowAnalysisContextTest, EmptyFlowCondition) {
+  auto &FC = Context.makeFlowConditionToken();
+  auto &C = Context.createAtomicBoolValue();
+  EXPECT_FALSE(Context.flowConditionImplies(FC, C));
+}
+
+TEST_F(DataflowAnalysisContextTest, AddFlowConditionConstraint) {
+  auto &FC = Context.makeFlowConditionToken();
+  auto &C = Context.createAtomicBoolValue();
+  Context.addFlowConditionConstraint(FC, C);
+  EXPECT_TRUE(Context.flowConditionImplies(FC, C));
+}
+
+TEST_F(DataflowAnalysisContextTest, ForkFlowCondition) {
+  auto &FC1 = Context.makeFlowConditionToken();
+  auto &C1 = Context.createAtomicBoolValue();
+  Context.addFlowConditionConstraint(FC1, C1);
+
+  // Forked flow condition inherits the constraints of its parent flow
+  // condition.
+  auto &FC2 = Context.forkFlowCondition(FC1);
+  EXPECT_TRUE(Context.flowConditionImplies(FC2, C1));
+
+  // Adding a new constraint to the forked flow condition does not affect its
+  // parent flow condition.
+  auto &C2 = Context.createAtomicBoolValue();
+  Context.addFlowConditionConstraint(FC2, C2);
+  EXPECT_TRUE(Context.flowConditionImplies(FC2, C2));
+  EXPECT_FALSE(Context.flowConditionImplies(FC1, C2));
+}
+
+TEST_F(DataflowAnalysisContextTest, JoinFlowConditions) {
+  auto &C1 = Context.createAtomicBoolValue();
+  auto &C2 = Context.createAtomicBoolValue();
+  auto &C3 = Context.createAtomicBoolValue();
+
+  auto &FC1 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC1, C1);
+  Context.addFlowConditionConstraint(FC1, C3);
+
+  auto &FC2 = Context.makeFlowConditionToken();
+  Context.addFlowConditionConstraint(FC2, C2);
+  Context.addFlowConditionConstraint(FC2, C3);
+
+  auto &FC3 = Context.joinFlowConditions(FC1, FC2);
+  EXPECT_FALSE(Context.flowConditionImplies(FC3, C1));
+  EXPECT_FALSE(Context.flowConditionImplies(FC3, C2));
+  EXPECT_TRUE(Context.flowConditionImplies(FC3, C3));
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -77,33 +77,14 @@
   Environment &MergedEnv,
   Environment::ValueModel &Model) {
   // Join distinct boolean values preserving information about the constraints
-  // in the respective path conditions. Note: this construction can, in
-  // principle, result in exponential growth in the size of boolean values.
-  // Potential optimizations may be worth considering. For example, represent
-  // the flow condition of each environment using a bool atom and store, in
-  // `DataflowAnalysisContext`, a mapping of bi-conditionals between flow
-  // condition atoms and flow condition constraints. Something like:
-  // \code
-  //   FC1 <=> C1 ^ C2
-  //   FC2 <=> C2 ^ C3 ^ C4
-  //   FC3 <=> (FC1 v FC2) ^ C5
-  // \code
-  // Then, we can track dependencies between flow conditions (e.g. above `FC3`
-  // depends on `FC1` and `FC2`) and modify `flowConditionImplies` to construct
-  // a formula that includes the bi-conditionals for all flow condition atoms in
-  // the transitive set, before invoking the solver.
+  // in the respective path conditions.
   //
   // FIXME: Does not work for backedges, since the two (or more) paths will not
   // have mutually exclusive conditions.
   if (auto *Expr1 = dyn_cast(Val1)) {
-for (BoolValue *Constraint : Env1.getFlowConditionConstraints()) {
-  Expr1 = &MergedEnv.makeAnd(*Expr1, *Constraint);
-}
 auto *Expr2 = cast(Val2);
-for (BoolValue *Constraint : Env2.getFlowConditionConstraints()) {
-  Expr2 = &MergedEnv.makeAnd(*Expr2, *Constraint);
-}
-return &MergedEnv.makeOr(*Expr1, *Expr2);
+return &Env1.makeOr(Env1.makeAnd(Env1.getFlowConditionToken(), *

[PATCH] D124729: [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Rink via Phabricator via cfe-commits
zhmu added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124729

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


[PATCH] D124729: [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/ananas.c:20
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o \
+// RUN: --target=x86_64-unknown-ananas -r 2>&1 \

Delete -no-canonical-prefixes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124729

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


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

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

Testing on VTK revealed this change:

  -  this->SliceMapper->SetBackground((this->Background &&
  -!(this->SliceFacesCamera && this->InternalResampleToScreenPixels &&
  -  !this->SeparateWindowLevelOperation)));
  +  this->SliceMapper->SetBackground(
  +  (this->Background &&
  +   (!this->SliceFacesCamera && this->InternalResampleToScreenPixels ||
  +this->SeparateWindowLevelOperation)));

Which is incorrect.  So more improvement is needed for the case of `!(x && y && 
!z)` or `!(x || y || !z)` is encountered.


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

https://reviews.llvm.org/D124650

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


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

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



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:586
+
+  auto Not = hasOperatorName("!");
+  auto Or = hasOperatorName("||");

njames93 wrote:
> njames93 wrote:
> > This whole implementation would be alot simpler(and likely faster) if you 
> > matched on the generic case then in the check callback work out what 
> > replacement you need.
> > ```lang=c++
> > Finder->addMatcher(
> > unaryOperator(
> > Not,
> > hasUnaryOperand(binaryOperator(
> > hasAnyOperatorName("&&", "||"),
> > hasEitherOperand(unaryOperator(Not).bind(Demorgan),
> > this);
> > ```
> Come to think of it, you wouldn't even need to work out which. Just remove 
> the outer `!`, Exchange `||` with `&&` and invert each side of the binary 
> operator.
These are good ideas, I'll take a look.  I wasn't aware of `hasEitherOperand`.  
I mean, it's in that giant AST matcher reference page, but somehow I overlooked 
it.  On Windows, we don't have TAB completion in clang-query either, so it 
becomes more difficult to interactively explore possibilities.


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

https://reviews.llvm.org/D124650

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


[PATCH] D124736: [CodeGen] Use ABI alignment for placement new

2022-05-01 Thread Daniel Bertalan via Phabricator via cfe-commits
BertalanD updated this revision to Diff 426301.
BertalanD added a comment.

Added a test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124736

Files:
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/test/CodeGenCXX/pr54845.cpp


Index: clang/test/CodeGenCXX/pr54845.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/pr54845.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple i686-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// https://github.com/llvm/llvm-project/issues/54845
+
+void *operator new(unsigned int, void *);
+
+void test(double *d) {
+  // This store used to have an alignment of 8, which was incorrect as
+  // the i386 psABI only guarantees a 4-byte alignment for doubles.
+
+  // CHECK: store double 0.00e+00, {{.*}}, align 4
+  new (d) double(0);
+}
Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -1573,7 +1573,7 @@
   llvm::Value *allocSize =
 EmitCXXNewAllocSize(*this, E, minElements, numElements,
 allocSizeWithoutCookie);
-  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+  CharUnits allocAlign;
 
   // Emit the allocation call.  If the allocator is a global placement
   // operator, just "inline" it directly.
@@ -1583,6 +1583,8 @@
 assert(E->getNumPlacementArgs() == 1);
 const Expr *arg = *E->placement_arguments().begin();
 
+allocAlign = getContext().getTypeAlignInChars(allocType);
+
 LValueBaseInfo BaseInfo;
 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
 
@@ -1605,6 +1607,8 @@
   allocator->getType()->castAs();
 unsigned ParamsToSkip = 0;
 
+allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+
 // The allocation size is the first argument.
 QualType sizeType = getContext().getSizeType();
 allocatorArgs.add(RValue::get(allocSize), sizeType);


Index: clang/test/CodeGenCXX/pr54845.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/pr54845.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple i686-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// https://github.com/llvm/llvm-project/issues/54845
+
+void *operator new(unsigned int, void *);
+
+void test(double *d) {
+  // This store used to have an alignment of 8, which was incorrect as
+  // the i386 psABI only guarantees a 4-byte alignment for doubles.
+
+  // CHECK: store double 0.00e+00, {{.*}}, align 4
+  new (d) double(0);
+}
Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -1573,7 +1573,7 @@
   llvm::Value *allocSize =
 EmitCXXNewAllocSize(*this, E, minElements, numElements,
 allocSizeWithoutCookie);
-  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+  CharUnits allocAlign;
 
   // Emit the allocation call.  If the allocator is a global placement
   // operator, just "inline" it directly.
@@ -1583,6 +1583,8 @@
 assert(E->getNumPlacementArgs() == 1);
 const Expr *arg = *E->placement_arguments().begin();
 
+allocAlign = getContext().getTypeAlignInChars(allocType);
+
 LValueBaseInfo BaseInfo;
 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
 
@@ -1605,6 +1607,8 @@
   allocator->getType()->castAs();
 unsigned ParamsToSkip = 0;
 
+allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+
 // The allocation size is the first argument.
 QualType sizeType = getContext().getSizeType();
 allocatorArgs.add(RValue::get(allocSize), sizeType);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124606: Use `-text` git attribute instead of `text eol=...'

2022-05-01 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur added a comment.

In D124606#3479793 , @ilya-biryukov 
wrote:

> LGTM

This and the commit (@MForster ) was too hasty. There should have been time for 
people discussing D124563  and D97625 
 to react, and should have been added as 
reviewers. I didn't even see @ilya-biryukov participating in the other 
discussions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124606

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


[PATCH] D124736: [CodeGen] Use ABI alignment for placement new

2022-05-01 Thread Daniel Bertalan via Phabricator via cfe-commits
BertalanD updated this revision to Diff 426303.
BertalanD added a comment.

Removed accidental execute permission from the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124736

Files:
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/test/CodeGenCXX/pr54845.cpp


Index: clang/test/CodeGenCXX/pr54845.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/pr54845.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple i686-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// https://github.com/llvm/llvm-project/issues/54845
+
+void *operator new(unsigned int, void *);
+
+void test(double *d) {
+  // This store used to have an alignment of 8, which was incorrect as
+  // the i386 psABI only guarantees a 4-byte alignment for doubles.
+
+  // CHECK: store double 0.00e+00, {{.*}}, align 4
+  new (d) double(0);
+}
Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -1573,7 +1573,7 @@
   llvm::Value *allocSize =
 EmitCXXNewAllocSize(*this, E, minElements, numElements,
 allocSizeWithoutCookie);
-  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+  CharUnits allocAlign;
 
   // Emit the allocation call.  If the allocator is a global placement
   // operator, just "inline" it directly.
@@ -1583,6 +1583,8 @@
 assert(E->getNumPlacementArgs() == 1);
 const Expr *arg = *E->placement_arguments().begin();
 
+allocAlign = getContext().getTypeAlignInChars(allocType);
+
 LValueBaseInfo BaseInfo;
 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
 
@@ -1605,6 +1607,8 @@
   allocator->getType()->castAs();
 unsigned ParamsToSkip = 0;
 
+allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+
 // The allocation size is the first argument.
 QualType sizeType = getContext().getSizeType();
 allocatorArgs.add(RValue::get(allocSize), sizeType);


Index: clang/test/CodeGenCXX/pr54845.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/pr54845.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple i686-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// https://github.com/llvm/llvm-project/issues/54845
+
+void *operator new(unsigned int, void *);
+
+void test(double *d) {
+  // This store used to have an alignment of 8, which was incorrect as
+  // the i386 psABI only guarantees a 4-byte alignment for doubles.
+
+  // CHECK: store double 0.00e+00, {{.*}}, align 4
+  new (d) double(0);
+}
Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -1573,7 +1573,7 @@
   llvm::Value *allocSize =
 EmitCXXNewAllocSize(*this, E, minElements, numElements,
 allocSizeWithoutCookie);
-  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+  CharUnits allocAlign;
 
   // Emit the allocation call.  If the allocator is a global placement
   // operator, just "inline" it directly.
@@ -1583,6 +1583,8 @@
 assert(E->getNumPlacementArgs() == 1);
 const Expr *arg = *E->placement_arguments().begin();
 
+allocAlign = getContext().getTypeAlignInChars(allocType);
+
 LValueBaseInfo BaseInfo;
 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
 
@@ -1605,6 +1607,8 @@
   allocator->getType()->castAs();
 unsigned ParamsToSkip = 0;
 
+allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
+
 // The allocation size is the first argument.
 QualType sizeType = getContext().getSizeType();
 allocatorArgs.add(RValue::get(allocSize), sizeType);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D117829: [Clang] Add integer add/mul reduction builtins

2022-05-01 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

> @fhahn Remind me - why did you want me to split these? If we're initially 
> just going for integer support, can't both be done at the same time in this 
> patch?

I think my original thinking was that `__builtin_reduce_mul` isn't defined at 
the moment https://clang.llvm.org/docs/LanguageExtensions.html#vector-builtins

So I think it would be good to either the update the docs  in the patch (or 
preferably be split off the straight forward `__builtin_reduce_add` change :))


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117829

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


[PATCH] D124741: [Clang] Add integer add reduction builtin

2022-05-01 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon created this revision.
RKSimon added reviewers: fhahn, scanon, aaron.ballman, craig.topper.
Herald added a subscriber: StephenFan.
Herald added a project: All.
RKSimon requested review of this revision.
Herald added a project: clang.

Similar to the existing bitwise reduction builtins, this lowers to a 
llvm.vector.reduce.add intrinsic call.

For other reductions, we've tried to share builtins for float/integer vectors, 
but the fadd reduction builtins also take a starting value argument. 
Technically I could support float by using default values, but we're probably 
better off with specific fadd reduction builtins for both arguments.

(Split off from D117829 )


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124741

Files:
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-reduction-math.c
  clang/test/Sema/builtins-reduction-math.c


Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -36,6 +36,23 @@
   // expected-error@-1 {{1st argument must be a vector type (was 'int')}}
 }
 
+void test_builtin_reduce_add(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_add(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of 
incompatible type 'int'}}
+
+  i = __builtin_reduce_add();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 
0}}
+
+  i = __builtin_reduce_add(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 
2}}
+
+  i = __builtin_reduce_add(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 
'int')}}
+
+  i = __builtin_reduce_add(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 
'float4' (vector of 4 'float' values))}}
+}
+
 void test_builtin_reduce_xor(int i, float4 v, int3 iv) {
   struct Foo s = __builtin_reduce_xor(iv);
   // expected-error@-1 {{initializing 'struct Foo' with an expression of 
incompatible type 'int'}}
Index: clang/test/CodeGen/builtins-reduction-math.c
===
--- clang/test/CodeGen/builtins-reduction-math.c
+++ clang/test/CodeGen/builtins-reduction-math.c
@@ -58,6 +58,28 @@
   unsigned long long r5 = __builtin_reduce_min(cvi1);
 }
 
+void test_builtin_reduce_add(si8 vi1, u4 vu1) {
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.add.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_add(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_add(vu1);
+
+  // CHECK:  [[CVI1:%.+]] = load <8 x i16>, <8 x i16>* %cvi1, align 16
+  // CHECK-NEXT: [[RDX1:%.+]] = call i16 @llvm.vector.reduce.add.v8i16(<8 x 
i16> [[CVI1]])
+  // CHECK-NEXT: sext i16 [[RDX1]] to i32
+  const si8 cvi1 = vi1;
+  int r4 = __builtin_reduce_add(cvi1);
+
+  // CHECK:  [[CVU1:%.+]] = load <4 x i32>, <4 x i32>* %cvu1, align 16
+  // CHECK-NEXT: [[RDX2:%.+]] = call i32 @llvm.vector.reduce.add.v4i32(<4 x 
i32> [[CVU1]])
+  // CHECK-NEXT: zext i32 [[RDX2]] to i64
+  const u4 cvu1 = vu1;
+  unsigned long long r5 = __builtin_reduce_add(cvu1);
+}
+
 void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
 
   // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -2331,6 +2331,8 @@
   }
 
   // These builtins support vectors of integers only.
+  // TODO: ADD should support floating-point types.
+  case Builtin::BI__builtin_reduce_add:
   case Builtin::BI__builtin_reduce_xor:
   case Builtin::BI__builtin_reduce_or:
   case Builtin::BI__builtin_reduce_and: {
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -3273,6 +3273,9 @@
 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
   }
 
+  case Builtin::BI__builtin_reduce_add:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def
+++ clang/include/clang/Basic/Builtins.def
@@ -663,6 +663,7 @@
 BUILTIN(__builtin_reduce_xor, "v.", "nct")

[PATCH] D124589: [clang-format] Fix a bug that misformats Access Specifier after *[]

2022-05-01 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 426307.
owenpan added a comment.

Instead of looking back, look ahead in `tryToParseLambdaIntroducer()`.


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

https://reviews.llvm.org/D124589

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
@@ -3336,6 +3336,14 @@
   verifyFormat("if (public == private)\n");
   verifyFormat("void foo(public, private)");
   verifyFormat("public::foo();");
+
+  verifyFormat("class A {\n"
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"
+   "private:\n"
+   "  int c;\n"
+   "};");
 }
 
 TEST_F(FormatTest, SeparatesLogicalBlocks) {
@@ -21487,6 +21495,7 @@
"  bar([]() {} // Did not respect 
SpacesBeforeTrailingComments\n"
"  );\n"
"}");
+  verifyFormat("auto k = *[](int *j) { return j; }(&i);");
 
   // Lambdas created through weird macros.
   verifyFormat("void f() {\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2048,6 +2048,11 @@
   nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
+  if (FormatTok->is(tok::r_square)) {
+const FormatToken *Next = Tokens->peekNextToken();
+if (Next && Next->is(tok::greater))
+  return false;
+  }
   parseSquare(/*LambdaIntroducer=*/true);
   return true;
 }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3336,6 +3336,14 @@
   verifyFormat("if (public == private)\n");
   verifyFormat("void foo(public, private)");
   verifyFormat("public::foo();");
+
+  verifyFormat("class A {\n"
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"
+   "private:\n"
+   "  int c;\n"
+   "};");
 }
 
 TEST_F(FormatTest, SeparatesLogicalBlocks) {
@@ -21487,6 +21495,7 @@
"  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
"  );\n"
"}");
+  verifyFormat("auto k = *[](int *j) { return j; }(&i);");
 
   // Lambdas created through weird macros.
   verifyFormat("void f() {\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2048,6 +2048,11 @@
   nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
+  if (FormatTok->is(tok::r_square)) {
+const FormatToken *Next = Tokens->peekNextToken();
+if (Next && Next->is(tok::greater))
+  return false;
+  }
   parseSquare(/*LambdaIntroducer=*/true);
   return true;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124741: [Clang] Add integer add reduction builtin

2022-05-01 Thread Florian Hahn via Phabricator via cfe-commits
fhahn accepted this revision.
fhahn added a comment.
This revision is now accepted and ready to land.

LGTM, thanks

> For other reductions, we've tried to share builtins for float/integer 
> vectors, but the fadd reduction builtins also take a starting value argument. 
> Technically I could support float by using default values, but we're probably 
> better off with specific fadd reduction builtins for both arguments.

I think them main issue for fadd reductions is that the `fadd` intrinsic can 
either do unordered or serialized, but not reduction-trees as specified for the 
builtins in Clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124741

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


[PATCH] D124589: [clang-format] Fix a bug that misformats Access Specifier after *[]

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

Now that we look ahead instead of looking back, it doesn't matter what comes 
before `*[]` or `[]`.




Comment at: clang/unittests/Format/FormatTest.cpp:3342
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"

curdeius wrote:
> How about `int const *`, `const int*`? Is `const` & co. a simple type 
> specifier?
It doesn't matter what comes before `*[]` now that we look ahead for a `>`.


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

https://reviews.llvm.org/D124589

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


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

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

I also noticed that some of the simplifications being performed resulted in 
`!(x || !y)` coming out of other parts of the simplifier, so it should be the 
case that running this check on your code should result in no further changes 
to your code if you run the check again.


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

https://reviews.llvm.org/D124650

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


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

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



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:598-599
+  auto UnlessNotLHS = unless(hasLHS(NotOp));
+  // match !(!a || b)
+  Finder->addMatcher(unaryOperator(Not, hasUnaryOperand(binaryOperator(
+Or, UnlessNotRHS, NotLHS, RHS)))

njames93 wrote:
> Maybe I'm overthinking this, but how come you don't need the match on the 
> ParenExpr?
> Is there some traversal mode?
How can you have a binaryOperator as the child of unaryOperator without parens? 
 The precedence doesn't allow it otherwise.


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

https://reviews.llvm.org/D124650

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


[PATCH] D123200: [compiler-rt][builtins] Add several helper functions for AVR

2022-05-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 marked an inline comment as done.
benshi001 added inline comments.



Comment at: compiler-rt/lib/builtins/CMakeLists.txt:671
 
+set(avr_SOURCES
+  avr/mulqi3.S

MaskRay wrote:
> Keep the `*_SOURCES` in alphabetical order. Move avr to the beginning. Ignore 
> some entries which are unordered.
I will fix all your concerns about "alphabetical order" when committing.


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

https://reviews.llvm.org/D123200

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


[PATCH] D124729: [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Brad Smith via Phabricator via cfe-commits
brad added inline comments.



Comment at: clang/test/Driver/ananas.c:20
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o \
+// RUN: --target=x86_64-unknown-ananas -r 2>&1 \

MaskRay wrote:
> Delete -no-canonical-prefixes
Why here and not with the other instances of this same test? I'm trying to 
understand what -no-canonical-prefixes does as I see this all over the place 
and it seems like it has something to do with expanding symlinks with relative 
paths.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124729

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


[PATCH] D123200: [compiler-rt][builtins] Add several helper functions for AVR

2022-05-01 Thread Ben Shi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
benshi001 marked an inline comment as done.
Closed by commit rGfb7a435492a5: [compiler-rt][builtins] Add several helper 
functions for AVR (authored by benshi001).

Changed prior to commit:
  https://reviews.llvm.org/D123200?vs=423805&id=426319#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123200

Files:
  compiler-rt/cmake/Modules/CompilerRTUtils.cmake
  compiler-rt/cmake/base-config-ix.cmake
  compiler-rt/cmake/builtin-config-ix.cmake
  compiler-rt/cmake/config-ix.cmake
  compiler-rt/lib/builtins/CMakeLists.txt
  compiler-rt/lib/builtins/avr/exit.S
  compiler-rt/lib/builtins/avr/mulhi3.S
  compiler-rt/lib/builtins/avr/mulqi3.S

Index: compiler-rt/lib/builtins/avr/mulqi3.S
===
--- /dev/null
+++ compiler-rt/lib/builtins/avr/mulqi3.S
@@ -0,0 +1,31 @@
+//=== mulhi3.S - int8 multiplication --===//
+//
+// 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
+//
+//===--===//
+//
+// The corresponding C code is something like:
+//
+// int __mulqi3(char A, char B) {
+//   return __mulhi3((int) A, (int) B);
+// }
+//
+//===--===//
+
+	.text
+	.align 2
+
+	.globl __mulqi3
+	.type  __mulqi3, @function
+
+__mulqi3:
+	movr25, r24
+	lslr25
+	sbcr25, r25 ; Promote A from char to int: `(int) A`.
+	movr23, r22
+	lslr23
+	sbcr23, r23 ; Promote B from char to int: `(int) B`.
+	rcall  __mulhi3 ; `__mulhi3((int) A, (int) B);`.
+	ret
Index: compiler-rt/lib/builtins/avr/mulhi3.S
===
--- /dev/null
+++ compiler-rt/lib/builtins/avr/mulhi3.S
@@ -0,0 +1,58 @@
+//=== mulhi3.S - int16 multiplication -===//
+//
+// 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
+//
+//===--===//
+//
+// The corresponding C code is something like:
+//
+// int __mulhi3(int A, int B) {
+//   int S = 0;
+//   while (A != 0) {
+// if (A & 1)
+//   S += B;
+// A = ((unsigned int) A) >> 1;
+// B <<= 1;
+//   }
+//   return S;
+// }
+//
+//===--===//
+
+	.text
+	.align 2
+
+	.globl __mulhi3
+	.type  __mulhi3, @function
+
+__mulhi3:
+	eorr28, r28
+	eorr20, r20
+	eorr21, r21 ; Initialize the result to 0: `S = 0;`.
+
+__mulhi3_loop:
+	cp r24, r28
+	cpcr25, r28 ; `while (A != 0) { ... }`
+	breq   __mulhi3_end ; End the loop if A is 0.
+
+	movr29, r24
+	andi   r29, 1   ; `if (A & 1) { ... }`
+	breq   __mulhi3_loop_a  ; Omit the accumulation (`S += B;`) if  A's LSB is 0.
+
+	addr20, r22
+	adcr21, r23 ; Do the accumulation: `S += B;`.
+
+__mulhi3_loop_a:
+	lsrr25
+	rorr24  ; `A = ((unsigned int) A) >> 1;`.
+	lslr22
+	rolr23  ; `B <<= 1;`
+
+	rjmp   __mulhi3_loop
+
+__mulhi3_end:
+	movr24, r20
+	movr25, r21
+	ret
Index: compiler-rt/lib/builtins/avr/exit.S
===
--- /dev/null
+++ compiler-rt/lib/builtins/avr/exit.S
@@ -0,0 +1,18 @@
+//=== exit.S - global terminator for AVR --===//
+//
+// 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
+//
+//===--===//
+
+	.text
+	.align 2
+
+	.globl _exit
+	.type  _exit, @function
+
+_exit:
+	cli ; Disable all interrupts.
+__stop_program:
+	rjmp __stop_program ; Fall into an infinite loop.
Index: compiler-rt/lib/builtins/CMakeLists.txt
===
--- compiler-rt/lib/builtins/CMakeLists.txt
+++ compiler-rt/lib/builtins/CMakeLists.txt
@@ -567,6 +567,13 @@
 set(armv8m.main_SOURCES ${arm_SOURCES})
 set(armv8.1m.main_SOURCES ${arm_SOURCES})
 
+# 8-bit AVR MCU
+set(avr_SOURCES
+  avr/mulqi3.S
+  avr/mulhi3.S
+  avr/exit.S
+)
+
 # hexagon arch
 set(hexagon_SOURCES
   hexagon/common_entry_exit_abi1.S
Index: compiler-rt/cmake/config-ix.cmake
===
--- compiler-rt/cmake/config-ix.cmake
+++ compiler-rt/cmak

[PATCH] D124157: [clang][preprocessor] Add more macros to target AVR

2022-05-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added a reviewer: MaskRay.
benshi001 added a comment.
Herald added a subscriber: StephenFan.

avr-gcc does define this __AVR_TINY_ macro for the tiny device family, we can 
check that by `avr-gcc -mmcu=avrtiny -E -dM -xc /dev/null -dM  | grep tiny -i`.


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

https://reviews.llvm.org/D124157

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


[PATCH] D124748: [clang-format] Fix whitespace counting stuff

2022-05-01 Thread sstwcw via Phabricator via cfe-commits
sstwcw created this revision.
sstwcw added reviewers: HazardyKnusperkeks, MyDeveloperDay, curdeius, owenpan.
Herald added a project: All.
sstwcw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The current way of counting whitespace would count backticks as
whitespace.  For Verilog stuff we need backticks to be handled
correctly.  For JavaScript the current way is to compare the entire
token text to see if it's a backtick.  However, when the backtick is the
first token following an escaped newline, the escaped newline will be
part of the tok::unknown token.  Verilog has macros and escaped newlines
unlike JavaScript.  So we can't regard an entire tok::unknown token as
whitespace.  Previously, the start of every token would be matched for
newlines.  Now, it is all whitespace instead of just newlines.

The column counting problem has already been fixed for JavaScript in
e71b4cbdd140f059667f84464bd0ac0ebc348387 by counting columns elsewhere.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124748

Files:
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/FormatTokenLexer.h

Index: clang/lib/Format/FormatTokenLexer.h
===
--- clang/lib/Format/FormatTokenLexer.h
+++ clang/lib/Format/FormatTokenLexer.h
@@ -92,6 +92,8 @@
 
   bool tryMergeConflictMarkers();
 
+  void resizeToken(size_t NewLen);
+
   FormatToken *getStashedToken();
 
   FormatToken *getNextToken();
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -836,6 +836,61 @@
   return FormatTok;
 }
 
+void FormatTokenLexer::resizeToken(size_t NewLen) {
+  resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
+  Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
+  FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
+  FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
+  FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
+  Encoding);
+  FormatTok->Tok.setLength(NewLen);
+}
+
+/// Count the length of leading whitespace in a token.
+static size_t countLeadingWhitespace(StringRef Text) {
+  // Basically counting the length matched by this regex.
+  // "^([\n\r\f\v \t]|(|\\?\\?/)[\n\r])+"
+  // Directly using the regex turned out to be slow. With the regex
+  // version formatting all files in this directory took about 1.25
+  // seconds. This version took about 0.5 seconds.
+  bool Done = false;
+  const char *Cur = Text.begin();
+  while (!Done && Cur < Text.end())
+switch (Cur[0]) {
+case '\n':
+case '\r':
+case '\f':
+case '\v':
+case ' ':
+case '\t':
+  ++Cur;
+  break;
+  // A '\' followed by a newline always escapes the newline, regardless
+  // of whether there is another '\' before it.
+case '\\':
+  // The source has a null byte at the end. It is not necessary to
+  // check Cur + 1 < Text.end().
+  if (Cur[1] == '\n' || Cur[1] == '\r')
+Cur += 2;
+  else
+Done = true;
+  break;
+  // Newlines can also be escaped by a '?' '?' '/' trigraph. By the way, the
+  // characters are quoted individually in this comment because if we write
+  // them together some compilers warn that we have a trigraph in the code.
+case '?':
+  if (Cur[1] == '?' && Cur[2] == '/' && (Cur[3] == '\n' || Cur[3] == '\r'))
+Cur += 4;
+  else
+Done = true;
+  break;
+default:
+  Done = true;
+  break;
+}
+  return Cur - Text.begin();
+}
+
 FormatToken *FormatTokenLexer::getNextToken() {
   if (StateStack.top() == LexerState::TOKEN_STASHED) {
 StateStack.pop();
@@ -850,34 +905,29 @@
   IsFirstToken = false;
 
   // Consume and record whitespace until we find a significant token.
+  // Some tok::unknown tokens are not just whitespace, e.g. whitespace
+  // followed by a symbol such as backtick. Those symbols may be
+  // significant in other languages.
   unsigned WhitespaceLength = TrailingWhitespace;
-  while (FormatTok->is(tok::unknown)) {
+  while (FormatTok->isNot(tok::eof)) {
+auto LeadingWhitespace = countLeadingWhitespace(FormatTok->TokenText);
+if (!LeadingWhitespace)
+  break;
+if (LeadingWhitespace < FormatTok->TokenText.size())
+  resizeToken(LeadingWhitespace);
 StringRef Text = FormatTok->TokenText;
-auto EscapesNewline = [&](int pos) {
-  // A '\r' here is just part of '\r\n'. Skip it.
-  if (pos >= 0 && Text[pos] == '\r')
---pos;
-  // See whether there is an odd number of '\' before this.
-  // FIXME: This is wrong. A '\' followed by a newline is always removed,
-  // regardless of whether there is another '\' before it.
-  // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
-  unsigned c

[PATCH] D124749: [clang-format] Handle Verilog preprocessor directives

2022-05-01 Thread sstwcw via Phabricator via cfe-commits
sstwcw created this revision.
sstwcw added reviewers: HazardyKnusperkeks, MyDeveloperDay, curdeius, owenpan.
Herald added a project: All.
sstwcw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124749

Files:
  clang/lib/Format/FormatToken.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/FormatTokenLexer.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTestVerilog.cpp

Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -43,6 +43,30 @@
   }
 };
 
+TEST_F(FormatTestVerilog, Delay) {
+  // Delay by the default unit.
+  verifyFormat("#0;");
+  verifyFormat("#1;");
+  verifyFormat("#10;");
+  verifyFormat("#1.5;");
+  // Explicit unit.
+  verifyFormat("#1fs;");
+  verifyFormat("#1.5fs;");
+  verifyFormat("#1ns;");
+  verifyFormat("#1.5ns;");
+  verifyFormat("#1us;");
+  verifyFormat("#1.5us;");
+  verifyFormat("#1ms;");
+  verifyFormat("#1.5ms;");
+  verifyFormat("#1s;");
+  verifyFormat("#1.5s;");
+  // The following expression should be on the same line.
+  verifyFormat("#1 x = x;");
+  EXPECT_EQ("#1 x = x;", format("#1\n"
+"x = x;",
+getLLVMStyle(FormatStyle::LK_Verilog)));
+}
+
 TEST_F(FormatTestVerilog, If) {
   verifyFormat("if (x)\n"
"  x = x;");
@@ -114,5 +138,61 @@
"  {x} = {x};");
 }
 
+TEST_F(FormatTestVerilog, Preprocessor) {
+  auto Style = getLLVMStyle(FormatStyle::LK_Verilog);
+  Style.ColumnLimit = 20;
+
+  // Macro definitions.
+  EXPECT_EQ("`define X  \\\n"
+"  if (x)   \\\n"
+"x = x;",
+format("`define X if(x)x=x;", Style));
+  EXPECT_EQ("`define X(x)   \\\n"
+"  if (x)   \\\n"
+"x = x;",
+format("`define X(x) if(x)x=x;", Style));
+  EXPECT_EQ("`define X  \\\n"
+"  x = x;   \\\n"
+"  x = x;",
+format("`define X x=x;x=x;", Style));
+  // Macro definitions with invocations inside.
+  EXPECT_EQ("`define LIST   \\\n"
+"  `ENTRY   \\\n"
+"  `ENTRY",
+format("`define LIST \\\n"
+   "`ENTRY \\\n"
+   "`ENTRY",
+   Style));
+  EXPECT_EQ("`define LIST   \\\n"
+"  `x = `x; \\\n"
+"  `x = `x;",
+format("`define LIST \\\n"
+   "`x = `x; \\\n"
+   "`x = `x;",
+   Style));
+  EXPECT_EQ("`define LIST   \\\n"
+"  `x = `x; \\\n"
+"  `x = `x;",
+format("`define LIST `x=`x;`x=`x;", Style));
+  // Macro invocations.
+  verifyFormat("`x = (`x1 + `x2 + x);");
+  // Lines starting with a normal macro invocation should be indented as a
+  // normal line.
+  EXPECT_EQ("if (x)\n"
+"  `x = `x;\n"
+"`timescale 1ns / 1ps",
+format("if (x)\n"
+   "`x = `x;\n"
+   "`timescale 1ns / 1ps",
+   Style));
+  EXPECT_EQ("if (x)\n"
+"`timescale 1ns / 1ps\n"
+"  `x = `x;",
+format("if (x)\n"
+   "`timescale 1ns / 1ps\n"
+   "`x = `x;",
+   Style));
+}
+
 } // namespace format
 } // end namespace clang
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1780,8 +1780,23 @@
 break;
 
   TokenCount = Line->Tokens.size();
-  if (TokenCount == 1 ||
-  (TokenCount == 2 && Line->Tokens.front().Tok->is(tok::comment))) {
+  // Determine whether the line might be a single macro expansion.
+  // In Verilog macro expansions begin with a backtick.
+  {
+const UnwrappedLineNode *Tok = &Line->Tokens.front(),
+*End = Tok + TokenCount;
+while (Tok != End && Tok->Tok->is(tok::comment))
+  ++Tok;
+if (Style.Language == FormatStyle::LK_Verilog) {
+  if (Tok != End && Tok->Tok->is(tok::hash))
+++Tok;
+  else
+break;
+}
+if (End - Tok != 1)
+  break;
+  }
+
 if (FormatTok->is(tok::colon) && !Line->MustBeDeclaration) {
   Line->Tokens.begin()->Tok->MustBreakBefore = true;
   parseLabel(!Style.IndentGotoLabels);
@@ -1805,7 +1820,6 @@
   PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
   addUnwrappedLine();
   return;
-}
   }
   break;

[PATCH] D124729: [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/ananas.c:20
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o \
+// RUN: --target=x86_64-unknown-ananas -r 2>&1 \

brad wrote:
> MaskRay wrote:
> > Delete -no-canonical-prefixes
> Why here and not with the other instances of this same test? I'm trying to 
> understand what -no-canonical-prefixes does as I see this all over the place 
> and it seems like it has something to do with expanding symlinks with 
> relative paths.
By default clang uses the dereferenced argv[0] to construct the -cc1 command 
line.

Many tests copy n paste `-no-canonical-prefixes` without a good reason.
`-no-canonical-prefixes` is only needed when writing `clang -cc1` and `%clang` 
has a content hash name (e.g. in Google's internal lit runner; I think Sony 
does something similar).

However, it is usually sufficient to omit `clang` and check just `-cc`. These 
tests can omit  `-no-canonical-prefixes` .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124729

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


[PATCH] D124749: [clang-format] Handle Verilog preprocessor directives

2022-05-01 Thread sstwcw via Phabricator via cfe-commits
sstwcw added a comment.

This revision depends on D124748 , but 
somehow it doesn't show up when I open the parent revision dialog.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124749

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


[PATCH] D124729: [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Brad Smith via Phabricator via cfe-commits
brad updated this revision to Diff 426327.
brad added a comment.

Updated with feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124729

Files:
  clang/lib/Driver/ToolChains/Ananas.cpp
  clang/test/Driver/ananas.c


Index: clang/test/Driver/ananas.c
===
--- clang/test/Driver/ananas.c
+++ clang/test/Driver/ananas.c
@@ -15,3 +15,10 @@
 // CHECK-SHARED: crtbeginS.o
 // CHECK-SHARED: crtendS.o
 // CHECK-SHARED: crtn.o
+
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang %s -### -o %t.o --target=x86_64-unknown-ananas -r 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE: "-r"
+// CHECK-RELOCATABLE-NOT: "-l
+// CHECK-RELOCATABLE-NOT: {{.*}}crt{{[^.]+}}.o
Index: clang/lib/Driver/ToolChains/Ananas.cpp
===
--- clang/lib/Driver/ToolChains/Ananas.cpp
+++ clang/lib/Driver/ToolChains/Ananas.cpp
@@ -85,7 +85,8 @@
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (!Args.hasArg(options::OPT_shared)) {
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
 }
@@ -111,12 +112,15 @@
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (ToolChain.ShouldLinkCXXStdlib(Args))
-ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
+if (ToolChain.ShouldLinkCXXStdlib(Args))
+  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
 CmdArgs.push_back("-lc");
+  }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   
CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
 else


Index: clang/test/Driver/ananas.c
===
--- clang/test/Driver/ananas.c
+++ clang/test/Driver/ananas.c
@@ -15,3 +15,10 @@
 // CHECK-SHARED: crtbeginS.o
 // CHECK-SHARED: crtendS.o
 // CHECK-SHARED: crtn.o
+
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang %s -### -o %t.o --target=x86_64-unknown-ananas -r 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE: "-r"
+// CHECK-RELOCATABLE-NOT: "-l
+// CHECK-RELOCATABLE-NOT: {{.*}}crt{{[^.]+}}.o
Index: clang/lib/Driver/ToolChains/Ananas.cpp
===
--- clang/lib/Driver/ToolChains/Ananas.cpp
+++ clang/lib/Driver/ToolChains/Ananas.cpp
@@ -85,7 +85,8 @@
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (!Args.hasArg(options::OPT_shared)) {
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
 }
@@ -111,12 +112,15 @@
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (ToolChain.ShouldLinkCXXStdlib(Args))
-ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
+if (ToolChain.ShouldLinkCXXStdlib(Args))
+  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
 CmdArgs.push_back("-lc");
+  }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
 else
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a132e52 - [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2022-05-02T00:28:14-04:00
New Revision: a132e527f25164268e08ebc63b043bbce8a043ed

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

LOG: [Driver][Ananas] -r: imply -nostdlib like GCC

Similar to D116843 for Gnu.cpp

Reviewed By: zhmu, MaskRay

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Ananas.cpp
clang/test/Driver/ananas.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Ananas.cpp 
b/clang/lib/Driver/ToolChains/Ananas.cpp
index be1476a7636c6..40f9e56b38e94 100644
--- a/clang/lib/Driver/ToolChains/Ananas.cpp
+++ b/clang/lib/Driver/ToolChains/Ananas.cpp
@@ -85,7 +85,8 @@ void ananas::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (!Args.hasArg(options::OPT_shared)) {
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
 }
@@ -111,12 +112,15 @@ void ananas::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (ToolChain.ShouldLinkCXXStdlib(Args))
-ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
+if (ToolChain.ShouldLinkCXXStdlib(Args))
+  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
 CmdArgs.push_back("-lc");
+  }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   
CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
 else

diff  --git a/clang/test/Driver/ananas.c b/clang/test/Driver/ananas.c
index 92c15104697bf..a6cabed9b190a 100644
--- a/clang/test/Driver/ananas.c
+++ b/clang/test/Driver/ananas.c
@@ -15,3 +15,10 @@
 // CHECK-SHARED: crtbeginS.o
 // CHECK-SHARED: crtendS.o
 // CHECK-SHARED: crtn.o
+
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang %s -### -o %t.o --target=x86_64-unknown-ananas -r 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE: "-r"
+// CHECK-RELOCATABLE-NOT: "-l
+// CHECK-RELOCATABLE-NOT: {{.*}}crt{{[^.]+}}.o



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


[PATCH] D124729: [Driver][Ananas] -r: imply -nostdlib like GCC

2022-05-01 Thread Brad Smith via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa132e527f251: [Driver][Ananas] -r: imply -nostdlib like GCC 
(authored by brad).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124729

Files:
  clang/lib/Driver/ToolChains/Ananas.cpp
  clang/test/Driver/ananas.c


Index: clang/test/Driver/ananas.c
===
--- clang/test/Driver/ananas.c
+++ clang/test/Driver/ananas.c
@@ -15,3 +15,10 @@
 // CHECK-SHARED: crtbeginS.o
 // CHECK-SHARED: crtendS.o
 // CHECK-SHARED: crtn.o
+
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang %s -### -o %t.o --target=x86_64-unknown-ananas -r 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE: "-r"
+// CHECK-RELOCATABLE-NOT: "-l
+// CHECK-RELOCATABLE-NOT: {{.*}}crt{{[^.]+}}.o
Index: clang/lib/Driver/ToolChains/Ananas.cpp
===
--- clang/lib/Driver/ToolChains/Ananas.cpp
+++ clang/lib/Driver/ToolChains/Ananas.cpp
@@ -85,7 +85,8 @@
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (!Args.hasArg(options::OPT_shared)) {
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
 }
@@ -111,12 +112,15 @@
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (ToolChain.ShouldLinkCXXStdlib(Args))
-ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
+if (ToolChain.ShouldLinkCXXStdlib(Args))
+  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
 CmdArgs.push_back("-lc");
+  }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   
CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
 else


Index: clang/test/Driver/ananas.c
===
--- clang/test/Driver/ananas.c
+++ clang/test/Driver/ananas.c
@@ -15,3 +15,10 @@
 // CHECK-SHARED: crtbeginS.o
 // CHECK-SHARED: crtendS.o
 // CHECK-SHARED: crtn.o
+
+// -r suppresses default -l and crt*.o like -nostdlib.
+// RUN: %clang %s -### -o %t.o --target=x86_64-unknown-ananas -r 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE: "-r"
+// CHECK-RELOCATABLE-NOT: "-l
+// CHECK-RELOCATABLE-NOT: {{.*}}crt{{[^.]+}}.o
Index: clang/lib/Driver/ToolChains/Ananas.cpp
===
--- clang/lib/Driver/ToolChains/Ananas.cpp
+++ clang/lib/Driver/ToolChains/Ananas.cpp
@@ -85,7 +85,8 @@
 assert(Output.isNothing() && "Invalid output.");
   }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (!Args.hasArg(options::OPT_shared)) {
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
 }
@@ -111,12 +112,15 @@
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
-  if (ToolChain.ShouldLinkCXXStdlib(Args))
-ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
+if (ToolChain.ShouldLinkCXXStdlib(Args))
+  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
 CmdArgs.push_back("-lc");
+  }
 
-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
+   options::OPT_r)) {
 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
 else
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 42fa5ba - [clang][preprocessor] Add more macros to target AVR

2022-05-01 Thread Ben Shi via cfe-commits

Author: Ben Shi
Date: 2022-05-02T04:37:57Z
New Revision: 42fa5bae7afcd58f769adfd46d15996eeb0381ad

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

LOG: [clang][preprocessor] Add more macros to target AVR

Reviewed By: MaskRay, aykevl

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

Added: 


Modified: 
clang/lib/Basic/Targets/AVR.cpp
clang/test/Preprocessor/avr-common.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/AVR.cpp b/clang/lib/Basic/Targets/AVR.cpp
index 14b3d0497c62c..7be33d4424f4d 100644
--- a/clang/lib/Basic/Targets/AVR.cpp
+++ b/clang/lib/Basic/Targets/AVR.cpp
@@ -384,6 +384,9 @@ void AVRTargetInfo::getTargetDefines(const LangOptions 
&Opts,
 auto It = llvm::find_if(
 AVRMcus, [&](const MCUInfo &Info) { return Info.Name == this->CPU; });
 
+if (It->IsTiny)
+  Builder.defineMacro("__AVR_TINY__", "1");
+
 if (It != std::end(AVRMcus)) {
   Builder.defineMacro(It->DefineName);
   if (It->NumFlashBanks >= 1)

diff  --git a/clang/test/Preprocessor/avr-common.c 
b/clang/test/Preprocessor/avr-common.c
index 8a03c1d91ab56..979dc52e67a10 100644
--- a/clang/test/Preprocessor/avr-common.c
+++ b/clang/test/Preprocessor/avr-common.c
@@ -1,6 +1,11 @@
-// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown /dev/null | FileCheck 
-match-full-lines %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny13 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny4 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,TINY %s
 
 // CHECK: #define AVR 1
 // CHECK: #define __AVR 1
+
+// TINY: #define __AVR_TINY__ 1
+// AVR-NOT: __AVR_TINY__
+
 // CHECK: #define __AVR__ 1
 // CHECK: #define __ELF__ 1



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


[PATCH] D124157: [clang][preprocessor] Add more macros to target AVR

2022-05-01 Thread Ben Shi via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG42fa5bae7afc: [clang][preprocessor] Add more macros to 
target AVR (authored by benshi001).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124157

Files:
  clang/lib/Basic/Targets/AVR.cpp
  clang/test/Preprocessor/avr-common.c


Index: clang/test/Preprocessor/avr-common.c
===
--- clang/test/Preprocessor/avr-common.c
+++ clang/test/Preprocessor/avr-common.c
@@ -1,6 +1,11 @@
-// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown /dev/null | FileCheck 
-match-full-lines %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny13 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny4 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,TINY %s
 
 // CHECK: #define AVR 1
 // CHECK: #define __AVR 1
+
+// TINY: #define __AVR_TINY__ 1
+// AVR-NOT: __AVR_TINY__
+
 // CHECK: #define __AVR__ 1
 // CHECK: #define __ELF__ 1
Index: clang/lib/Basic/Targets/AVR.cpp
===
--- clang/lib/Basic/Targets/AVR.cpp
+++ clang/lib/Basic/Targets/AVR.cpp
@@ -384,6 +384,9 @@
 auto It = llvm::find_if(
 AVRMcus, [&](const MCUInfo &Info) { return Info.Name == this->CPU; });
 
+if (It->IsTiny)
+  Builder.defineMacro("__AVR_TINY__", "1");
+
 if (It != std::end(AVRMcus)) {
   Builder.defineMacro(It->DefineName);
   if (It->NumFlashBanks >= 1)


Index: clang/test/Preprocessor/avr-common.c
===
--- clang/test/Preprocessor/avr-common.c
+++ clang/test/Preprocessor/avr-common.c
@@ -1,6 +1,11 @@
-// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown /dev/null | FileCheck -match-full-lines %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny13 /dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny4 /dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,TINY %s
 
 // CHECK: #define AVR 1
 // CHECK: #define __AVR 1
+
+// TINY: #define __AVR_TINY__ 1
+// AVR-NOT: __AVR_TINY__
+
 // CHECK: #define __AVR__ 1
 // CHECK: #define __ELF__ 1
Index: clang/lib/Basic/Targets/AVR.cpp
===
--- clang/lib/Basic/Targets/AVR.cpp
+++ clang/lib/Basic/Targets/AVR.cpp
@@ -384,6 +384,9 @@
 auto It = llvm::find_if(
 AVRMcus, [&](const MCUInfo &Info) { return Info.Name == this->CPU; });
 
+if (It->IsTiny)
+  Builder.defineMacro("__AVR_TINY__", "1");
+
 if (It != std::end(AVRMcus)) {
   Builder.defineMacro(It->DefineName);
   if (It->NumFlashBanks >= 1)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

2022-05-01 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:598-599
+  auto UnlessNotLHS = unless(hasLHS(NotOp));
+  // match !(!a || b)
+  Finder->addMatcher(unaryOperator(Not, hasUnaryOperand(binaryOperator(
+Or, UnlessNotRHS, NotLHS, RHS)))

LegalizeAdulthood wrote:
> njames93 wrote:
> > Maybe I'm overthinking this, but how come you don't need the match on the 
> > ParenExpr?
> > Is there some traversal mode?
> How can you have a binaryOperator as the child of unaryOperator without 
> parens?  The precedence doesn't allow it otherwise.
Its more the point that the AST has the ParenExpr
```lang=c++
!(a || !b);
```
```
`-UnaryOperator  'bool' prefix '!' cannot overflow
  `-ParenExpr  'bool'
`-BinaryOperator  'bool' '||'
  |-ImplicitCastExpr  'bool' 
  | `-DeclRefExpr  'bool' lvalue ParmVar 0x55a0e17465d0 'a' 'bool'
  `-UnaryOperator  'bool' prefix '!' cannot overflow
`-ImplicitCastExpr  'bool' 
  `-DeclRefExpr  'bool' lvalue ParmVar 0x55a0e1746648 'b' 'bool'
```


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

https://reviews.llvm.org/D124650

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


[PATCH] D124750: [MLIR] Add a utility to sort the operands of commutative ops

2022-05-01 Thread Srishti Srivastava via Phabricator via cfe-commits
srishti-pm created this revision.
Herald added subscribers: sdasgup3, wenzhicui, wrengr, Chia-hungDuan, dcaballe, 
cota, teijeong, rdzhabarov, tatianashp, msifontes, jurahul, Kayjukh, grosul1, 
Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, antiagainst, shauheen, 
rriddle, mehdi_amini, mgorny.
Herald added a project: All.
srishti-pm requested review of this revision.
Herald added subscribers: cfe-commits, stephenneuendorffer, nicolasvasilache.
Herald added projects: clang, MLIR.

Add a utility to sort the operands of commutative operations. This
utility is intended to be used inside a pass or an individual pattern to
simplify the matching of commutative operations. Note that this utility
can also be used inside PDL patterns in conjunction with the
`pdl.apply_native_rewrite` op. The sorting is done in ascending order of
"keys" associated with the operands. Each "key" represents a
breadth-first traversal of the backward slice of the operand. The
ascending order of "keys" is defined in a way that allows the (1)
operands defined by non-constant-like ops to come first, followed by (2)
block arguments, which are finally followed by the (3) operands defined
by constant-like ops. In addition to this, within the categories (1) and
(3), the order of operands is alphabetical w.r.t. the dialect name and
op name.

Illustration of the utility:
Let foo.op be a commutative op.

If the utility is called on foo.op and the DAG associated with foo.op is
as follows-

e = foo.div f, g
c = foo.constant
b = foo.add e, d
a = foo.add c, d
s = foo.op a, b,

then,

the utility will rewrite foo.op to the following-

s = foo.op b, a.

Signed-off-by: Srishti Srivastava 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124750

Files:
  clang/docs/tools/clang-formatted-files.txt
  mlir/include/mlir/Transforms/CommutativityUtils.h
  mlir/lib/Transforms/Utils/CMakeLists.txt
  mlir/lib/Transforms/Utils/CommutativityUtils.cpp
  mlir/test/Transforms/test-commutativity-utils.mlir
  mlir/test/lib/Dialect/Test/TestOps.td
  mlir/test/lib/Transforms/CMakeLists.txt
  mlir/test/lib/Transforms/TestCommutativityUtils.cpp
  mlir/tools/mlir-opt/mlir-opt.cpp

Index: mlir/tools/mlir-opt/mlir-opt.cpp
===
--- mlir/tools/mlir-opt/mlir-opt.cpp
+++ mlir/tools/mlir-opt/mlir-opt.cpp
@@ -56,6 +56,7 @@
 void registerVectorizerTestPass();
 
 namespace test {
+void registerCommutativityUtils();
 void registerConvertCallOpPass();
 void registerInliner();
 void registerMemRefBoundCheck();
@@ -146,6 +147,7 @@
   registerVectorizerTestPass();
   registerTosaTestQuantUtilAPIPass();
 
+  mlir::test::registerCommutativityUtils();
   mlir::test::registerConvertCallOpPass();
   mlir::test::registerInliner();
   mlir::test::registerMemRefBoundCheck();
Index: mlir/test/lib/Transforms/TestCommutativityUtils.cpp
===
--- /dev/null
+++ mlir/test/lib/Transforms/TestCommutativityUtils.cpp
@@ -0,0 +1,67 @@
+//===- TestCommutativityUtils.cpp - Pass to test the commutativity utility-===//
+//
+// 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
+//
+//===--===//
+//
+// This pass tests the functionality of the commutativity utility.
+//
+//===--===//
+
+#include "mlir/Transforms/CommutativityUtils.h"
+
+#include "TestDialect.h"
+#include "mlir/Pass/Pass.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+using namespace mlir;
+using namespace test;
+
+namespace {
+
+struct SmallPattern : public OpRewritePattern {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(TestCommutativeOp testCommOp,
+PatternRewriter &rewriter) const override {
+sortCommutativeOperands(testCommOp.getOperation(), rewriter);
+return success();
+  }
+};
+
+struct LargePattern : public OpRewritePattern {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(TestLargeCommutativeOp testLargeCommOp,
+PatternRewriter &rewriter) const override {
+sortCommutativeOperands(testLargeCommOp.getOperation(), rewriter);
+return success();
+  }
+};
+
+struct CommutativityUtils
+: public PassWrapper> {
+  MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CommutativityUtils)
+
+  StringRef getArgument() const final { return "test-commutativity-utils"; }
+  StringRef getDescription() const final {
+return "Test the functionality of the commutativity utility";
+  }
+
+  void runOnOperation() override {
+auto func = getOperation();
+auto *context = &getContext();
+
+RewritePatternSet patterns(context);
+patterns.add(context);
+
+(void)applyPa

[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-01 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

Wouldn't it be better if the user is not required to specify the triple in this 
shorthand version? We can infer the triple from the GPUArch. We have this 
support in our downstream branch.

```
clang  --target=x86_64-unknown-linux-gnu -fopenmp --offload-arch=gfx906 
helloworld.c -o helloworld
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D124750: [MLIR] Add a utility to sort the operands of commutative ops

2022-05-01 Thread Srishti Srivastava via Phabricator via cfe-commits
srishti-pm updated this revision to Diff 426335.
srishti-pm added a comment.

Improving the commit summary


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124750

Files:
  clang/docs/tools/clang-formatted-files.txt
  mlir/include/mlir/Transforms/CommutativityUtils.h
  mlir/lib/Transforms/Utils/CMakeLists.txt
  mlir/lib/Transforms/Utils/CommutativityUtils.cpp
  mlir/test/Transforms/test-commutativity-utils.mlir
  mlir/test/lib/Dialect/Test/TestOps.td
  mlir/test/lib/Transforms/CMakeLists.txt
  mlir/test/lib/Transforms/TestCommutativityUtils.cpp
  mlir/tools/mlir-opt/mlir-opt.cpp

Index: mlir/tools/mlir-opt/mlir-opt.cpp
===
--- mlir/tools/mlir-opt/mlir-opt.cpp
+++ mlir/tools/mlir-opt/mlir-opt.cpp
@@ -56,6 +56,7 @@
 void registerVectorizerTestPass();
 
 namespace test {
+void registerCommutativityUtils();
 void registerConvertCallOpPass();
 void registerInliner();
 void registerMemRefBoundCheck();
@@ -146,6 +147,7 @@
   registerVectorizerTestPass();
   registerTosaTestQuantUtilAPIPass();
 
+  mlir::test::registerCommutativityUtils();
   mlir::test::registerConvertCallOpPass();
   mlir::test::registerInliner();
   mlir::test::registerMemRefBoundCheck();
Index: mlir/test/lib/Transforms/TestCommutativityUtils.cpp
===
--- /dev/null
+++ mlir/test/lib/Transforms/TestCommutativityUtils.cpp
@@ -0,0 +1,67 @@
+//===- TestCommutativityUtils.cpp - Pass to test the commutativity utility-===//
+//
+// 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
+//
+//===--===//
+//
+// This pass tests the functionality of the commutativity utility.
+//
+//===--===//
+
+#include "mlir/Transforms/CommutativityUtils.h"
+
+#include "TestDialect.h"
+#include "mlir/Pass/Pass.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+using namespace mlir;
+using namespace test;
+
+namespace {
+
+struct SmallPattern : public OpRewritePattern {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(TestCommutativeOp testCommOp,
+PatternRewriter &rewriter) const override {
+sortCommutativeOperands(testCommOp.getOperation(), rewriter);
+return success();
+  }
+};
+
+struct LargePattern : public OpRewritePattern {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(TestLargeCommutativeOp testLargeCommOp,
+PatternRewriter &rewriter) const override {
+sortCommutativeOperands(testLargeCommOp.getOperation(), rewriter);
+return success();
+  }
+};
+
+struct CommutativityUtils
+: public PassWrapper> {
+  MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CommutativityUtils)
+
+  StringRef getArgument() const final { return "test-commutativity-utils"; }
+  StringRef getDescription() const final {
+return "Test the functionality of the commutativity utility";
+  }
+
+  void runOnOperation() override {
+auto func = getOperation();
+auto *context = &getContext();
+
+RewritePatternSet patterns(context);
+patterns.add(context);
+
+(void)applyPatternsAndFoldGreedily(func, std::move(patterns));
+  }
+};
+} // namespace
+
+namespace mlir {
+namespace test {
+void registerCommutativityUtils() { PassRegistration(); }
+} // namespace test
+} // namespace mlir
Index: mlir/test/lib/Transforms/CMakeLists.txt
===
--- mlir/test/lib/Transforms/CMakeLists.txt
+++ mlir/test/lib/Transforms/CMakeLists.txt
@@ -1,5 +1,6 @@
 # Exclude tests from libMLIR.so
 add_mlir_library(MLIRTestTransforms
+  TestCommutativityUtils.cpp
   TestConstantFold.cpp
   TestControlFlowSink.cpp
   TestInlining.cpp
Index: mlir/test/lib/Dialect/Test/TestOps.td
===
--- mlir/test/lib/Dialect/Test/TestOps.td
+++ mlir/test/lib/Dialect/Test/TestOps.td
@@ -1101,11 +1101,21 @@
   let hasFolder = 1;
 }
 
+def TestAddIOp : TEST_Op<"addi"> {
+  let arguments = (ins I32:$op1, I32:$op2);
+  let results = (outs I32);
+}
+
 def TestCommutativeOp : TEST_Op<"op_commutative", [Commutative]> {
   let arguments = (ins I32:$op1, I32:$op2, I32:$op3, I32:$op4);
   let results = (outs I32);
 }
 
+def TestLargeCommutativeOp : TEST_Op<"op_large_commutative", [Commutative]> {
+  let arguments = (ins I32:$op1, I32:$op2, I32:$op3, I32:$op4, I32:$op5, I32:$op6, I32:$op7);
+  let results = (outs I32);
+}
+
 def TestCommutative2Op : TEST_Op<"op_commutative2", [Commutative]> {
   let arguments = (ins I32:$op1, I32:$op2);
   let results = (outs I32);
Index: mlir/t

[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-01 Thread Nathan Ridge via Phabricator via cfe-commits
nridge requested changes to this revision.
nridge added a comment.
This revision now requires changes to proceed.

Apologies for the slow response here. This generally looks good to me, but I 
have a couple of suggestions regarding the formatting of the hints and handling 
type aliases.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:448
+auto Type = Param->getType();
+return Type->isLValueReferenceType() &&
+   !Type.getNonReferenceType().isConstQualified()

We should make sure we handle the case where a parameter is a typedef to a 
reference type, e.g.:

```
using IntRef = int&;
void foo(IntRef);
int main() {
  int arg;
  foo(arg);  // should show `&: ` hint
}
```

Let's add the testcase for this, and if necessary adjust the code to handle it 
(it's not immediately obvious to me whether it already handles it as written).



Comment at: clang-tools-extra/clangd/InlayHints.cpp:454
+
+  bool shouldNameHint(const Expr *Arg, StringRef ParamName) {
 if (ParamName.empty())

nit: `shouldHintName` would make more sense to me as a revised method name



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:217
+  )cpp",
+   ExpectedHint{"param: &", "param"});
+}

I prefer for the hint to continue to end with a space, to create visual 
separation between the hint and the actual code.

Especially in a case like this where a hint ends in ` &`, it may be difficult 
to visually distinguish this from the `&` occurring in the actual code.

To that end, I think the hint would make more sense as `param&: ` or `¶m: `.



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:382
+  )cpp",
+   ExpectedHint{"&", "param"});
+}

Similarly, and for consistency with other parameter hints, `&: ` would make 
sense to me here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

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


[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-01 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D124688#3483895 , @sammccall wrote:

> Trying this on a few files, this seems like it increases preamble sizes up to 
> 1% or so

Are preamble sizes a good proxy for preamble build times as well? I suspect 
that may be the metric that's more noticeable for users.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

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


[PATCH] D124748: [clang-format] Fix whitespace counting stuff

2022-05-01 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:839
 
+void FormatTokenLexer::resizeToken(size_t NewLen) {
+  resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(

Can you add some documentation?



Comment at: clang/lib/Format/FormatTokenLexer.cpp:868
+  break;
+  // A '\' followed by a newline always escapes the newline, regardless
+  // of whether there is another '\' before it.

I'd put (and search while reading) the comment after the case.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:871-872
+case '\\':
+  // The source has a null byte at the end. It is not necessary to
+  // check Cur + 1 < Text.end().
+  if (Cur[1] == '\n' || Cur[1] == '\r')

Please verify your assumption with an assert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124748

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


[PATCH] D124751: Support -E option for HLSL.

2022-05-01 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: beanz, steven_wu, JonChesterfield, sscalpone, 
pow2clk, rnk, bogner, MaskRay, dexonsmith.
Herald added subscribers: Anastasia, StephenFan.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

-E option will set entry function for hlsl.
The format is -E entry_name.

To avoid conflict with existing option with name 'E', add an extra prefix '--'.

A new field HLSLEntry is added to TargetOption.
To share code with HLSLShaderAttr, entry function will be add HLSLShaderAttr 
attribute too.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124751

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TargetOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaHLSL/entry.hlsl
  clang/test/SemaHLSL/prohibit_pointer.hlsl

Index: clang/test/SemaHLSL/prohibit_pointer.hlsl
===
--- clang/test/SemaHLSL/prohibit_pointer.hlsl
+++ clang/test/SemaHLSL/prohibit_pointer.hlsl
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -o - -fsyntax-only %s -verify
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library -x hlsl -o - -fsyntax-only %s -verify
 
 // expected-error@+1 {{pointers are unsupported in HLSL}}
 typedef int (*fn_int)(int);
Index: clang/test/SemaHLSL/entry.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/entry.hlsl
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-compute -x hlsl -Efoo -DWITH_NUM_THREADS -ast-dump -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-compute -x hlsl -Efoo  -o - %s  -verify
+
+
+// Make sure add HLSLShaderAttr along with HLSLNumThreadsAttr.
+// CHECK:HLSLNumThreadsAttr 0x{{.*}}  1 1 1
+// CHECK:HLSLShaderAttr 0x{{.*}}  Compute
+
+#ifdef WITH_NUM_THREADS
+[numthreads(1,1,1)]
+#endif
+// expected-error@+1 {{missing numthreads attribute for Compute shader entry}}
+void foo() {
+
+}
\ No newline at end of file
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -9863,6 +9863,55 @@
 }
   }
 
+  if (getLangOpts().HLSL) {
+auto &TargetInfo = getASTContext().getTargetInfo();
+if (!NewFD->isInvalidDecl() &&
+// Skip operator overload which not identifier.
+Name.isIdentifier() &&
+NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
+// Make sure it is in translation-unit scope.
+S->getDepth() == 0) {
+  CheckHLSLEntryPoint(NewFD);
+  if (!NewFD->isInvalidDecl()) {
+auto TripeShaderType = TargetInfo.getTriple().getEnvironment();
+AttributeCommonInfo AL(NewFD->getBeginLoc());
+HLSLShaderAttr::ShaderType ShaderType =
+HLSLShaderAttr::ShaderType::Callable;
+switch (TripeShaderType) {
+default:
+  break;
+case llvm::Triple::EnvironmentType::Compute:
+  ShaderType = HLSLShaderAttr::ShaderType::Compute;
+  break;
+case llvm::Triple::EnvironmentType::Vertex:
+  ShaderType = HLSLShaderAttr::ShaderType::Vertex;
+  break;
+case llvm::Triple::EnvironmentType::Hull:
+  ShaderType = HLSLShaderAttr::ShaderType::Hull;
+  break;
+case llvm::Triple::EnvironmentType::Domain:
+  ShaderType = HLSLShaderAttr::ShaderType::Domain;
+  break;
+case llvm::Triple::EnvironmentType::Geometry:
+  ShaderType = HLSLShaderAttr::ShaderType::Geometry;
+  break;
+case llvm::Triple::EnvironmentType::Pixel:
+  ShaderType = HLSLShaderAttr::ShaderType::Pixel;
+  break;
+case llvm::Triple::EnvironmentType::Mesh:
+  ShaderType = HLSLShaderAttr::ShaderType::Mesh;
+  break;
+case llvm::Triple::EnvironmentType::Amplification:
+  ShaderType = HLSLShaderAttr::ShaderType::Amplification;
+  break;
+}
+// To share code with HLSLShaderAttr, add HLSLShaderAttr to entry function.
+if (HLSLShaderAttr *Attr = mergeHLSLShaderAttr(NewFD, AL, ShaderType))
+  NewFD->addAttr(Attr);
+  }
+}
+  }
+
   if (!getLangOpts().CPlusPlus) {
 // Perform semantic checking on the function declaration.
 if (!NewFD->isInvalidDecl() && NewFD->isMain())
@@ -11683,6 +11732,21 @@
   }
 }
 
+void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
+  auto &TargetInfo = getASTContext().getTargetInfo();
+  switch (TargetInfo.getTriple().getEnvironment()) {
+  default:
+// FIXME: check all shader profiles.
+break;
+  case llvm::Triple::EnvironmentType::Compute:
+if (!FD->hasAttr()

[PATCH] D104439: [analyzer][NFC] Demonstrate a move from the analyzer-configs `.def` file to a TableGen file

2022-05-01 Thread Min-Yih Hsu via Phabricator via cfe-commits
myhsu added a comment.

Just curious: Have you considered using llvm::opt or even llvm::cl 
infrastructure? What are the pros & cons?




Comment at: clang/utils/TableGen/ClangSAConfigsEmitter.cpp:24
+
+using SortedRecords = llvm::StringMap;
+





Comment at: clang/utils/TableGen/ClangSAConfigsEmitter.cpp:32
+  OS.write_escaped(R->getValueAsString("HelpText")) << "\",";
+  StringRef DefaultVal = R->getValueAsString("DefaultVal");
+

I'm not an expert in clang-analyzer, but can `DefaultVal` be optional in an 
analyzer config? It you want it to be optional -- which, I think, also makes 
the TableGen file more concise -- you can use 
`Record::getValueasOptionalString` instead.



Comment at: clang/utils/TableGen/ClangSAConfigsEmitter.cpp:57
+
+  OS << "// This file is automatically generated. Do not edit this file by "
+"hand.\n";

Please use `llvm::emitSourceFileHeader` (in llvm/TableGen/TableGenBackend.h)



Comment at: clang/utils/TableGen/ClangSAConfigsEmitter.cpp:76
+OS << "BOOLEAN_OPTION(bool,";
+printOptionFields(R, OS, /*IsDefaultValString*/false);
+OS << ")\n";

IIRC usually we will also write /*IsDefaultValString=*/



Comment at: clang/utils/TableGen/ClangSAConfigsEmitter.cpp:140
+}
+OS << ")\n";
+  }

if `R->isValueUnset("Values")` returns true, the resulting code will have a 
trailing comma just right before the right brace:
```
ENUM_OPTION(Foo, Foo, "bar", "...",)
```
which I don't think is valid for C/C++ macro.
Please use `llvm::ListSeparator`(in StringExtras.h) to print commas instead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104439

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


[PATCH] D124749: [clang-format] Handle Verilog preprocessor directives

2022-05-01 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:1105
+  static const llvm::Regex VerilogToken(
+  "^(\'|``?|((\r?\n|\r)|[^[:space:]])*)");
+

Consider a raw string, for a better reading.



Comment at: clang/lib/Format/FormatTokenLexer.cpp:1129
 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
-  Lex->LexFromRawLexer(Tok.Tok);
+  if (!(Style.isVerilog() && readRawTokenVerilogSpecific(Tok.Tok)))
+Lex->LexFromRawLexer(Tok.Tok);

Otherwise I don't see why you change that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124749

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


[PATCH] D124687: [Tooling/DependencyScanning & Preprocessor] Refactor dependency scanning to record and use pre-lexed preprocessor directive tokens, instead of minimized sources

2022-05-01 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

I finished an initial pass through the code and it looks good for the most 
parts. I left a couple of suggestions in-line.

Did you test this change on some larger body of code? That would make me more 
confident, since this is a non-trivial change.

Might be good to get other reviewers to chime in.




Comment at: clang/include/clang/Lex/PreprocessorOptions.h:214
+  FileEntryRef)>
+  DependencyDirectivesForFile;
 

To be honest, I'm not a fan of using `PreprocessorOptions` to carry state 
between compiler invocations.

Could we implement a different mechanism for this in a prep patch an put 
`DependencyDirectivesForFile` there? `FailedModules` also seem as a state 
rather than options.



Comment at: clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp:1
-//===- DependencyDirectivesSourceMinimizer.cpp -  
-===//
-//

Can you split out the minimizer -> directives scanner rename into a separate 
patch? That would help with reviewing.



Comment at: 
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp:204
 
-  // Pass the skip mappings which should speed up excluded conditional 
block
-  // skipping in the preprocessor.
-  ScanInstance.getPreprocessorOpts()
-  .ExcludedConditionalDirectiveSkipMappings = &PPSkipMappings;
+  llvm::IntrusiveRefCntPtr localDepFS =
+  DepFS;

Nit: I think Clang still uses `PascalCase` for variable names.



Comment at: clang/test/ClangScanDeps/macro-expansions.cpp:1
+// RUN: rm -rf %t
+// RUN: split-file %s %t

Could you provide a short description of what's the intention of this test? 
Probably not obvious to the uninitiated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124687

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