r371182 - Reland [LifetimeAnalysis] Support more STL idioms (template forward declaration and DependentNameType)

2019-09-06 Thread Matthias Gehre via cfe-commits
Author: mgehre
Date: Fri Sep  6 01:56:30 2019
New Revision: 371182

URL: http://llvm.org/viewvc/llvm-project?rev=371182&view=rev
Log:
Reland [LifetimeAnalysis] Support more STL idioms (template forward declaration 
and DependentNameType)

Reland after https://reviews.llvm.org/D66806 fixed the false-positive 
diagnostics.

Summary:
This fixes inference of gsl::Pointer on std::set::iterator with libstdc++ (the 
typedef for iterator
on the template is a DependentNameType - we can only put the gsl::Pointer 
attribute
on the underlaying record after instantiation)

inference of gsl::Pointer on std::vector::iterator with libc++ (the class was 
forward-declared,
we added the gsl::Pointer on the canonical decl (the forward decl), and later 
when the
template was instantiated, there was no attribute on the definition so it was 
not instantiated).

and a duplicate gsl::Pointer on some class with libstdc++ (we first added an 
attribute to
a incomplete instantiation, and then another was copied from the template 
definition
when the instantiation was completed).

We now add the attributes to all redeclarations to fix thos issues and make 
their usage easier.

Reviewers: gribozavr

Subscribers: Szelethus, xazax.hun, cfe-commits

Tags: #clang

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

Added:
cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp
Modified:
cfe/trunk/lib/Sema/SemaAttr.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/SemaCXX/attr-gsl-owner-pointer-std.cpp
cfe/trunk/test/SemaCXX/attr-gsl-owner-pointer.cpp
cfe/trunk/unittests/Sema/CMakeLists.txt

Modified: cfe/trunk/lib/Sema/SemaAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=371182&r1=371181&r2=371182&view=diff
==
--- cfe/trunk/lib/Sema/SemaAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri Sep  6 01:56:30 2019
@@ -88,13 +88,11 @@ void Sema::AddMsStructLayoutForRecord(Re
 template 
 static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
  CXXRecordDecl *Record) {
-  CXXRecordDecl *Canonical = Record->getCanonicalDecl();
-  if (Canonical->hasAttr() || Canonical->hasAttr())
+  if (Record->hasAttr() || Record->hasAttr())
 return;
 
-  Canonical->addAttr(::new (Context) Attribute(SourceRange{}, Context,
-   /*DerefType*/ nullptr,
-   /*Spelling=*/0));
+  for (Decl *Redecl : Record->redecls())
+Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
 }
 
 void Sema::inferGslPointerAttribute(NamedDecl *ND,
@@ -189,8 +187,7 @@ void Sema::inferGslOwnerPointerAttribute
 
   // Handle classes that directly appear in std namespace.
   if (Record->isInStdNamespace()) {
-CXXRecordDecl *Canonical = Record->getCanonicalDecl();
-if (Canonical->hasAttr() || Canonical->hasAttr())
+if (Record->hasAttr() || Record->hasAttr())
   return;
 
 if (StdOwners.count(Record->getName()))

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=371182&r1=371181&r2=371182&view=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Fri Sep  6 01:56:30 2019
@@ -4592,9 +4592,11 @@ static void handleLifetimeCategoryAttr(S
   }
   return;
 }
-D->addAttr(::new (S.Context)
-   OwnerAttr(AL.getRange(), S.Context, DerefTypeLoc,
- AL.getAttributeSpellingListIndex()));
+for (Decl *Redecl : D->redecls()) {
+  Redecl->addAttr(::new (S.Context)
+  OwnerAttr(AL.getRange(), S.Context, DerefTypeLoc,
+AL.getAttributeSpellingListIndex()));
+}
   } else {
 if (checkAttrMutualExclusion(S, D, AL))
   return;
@@ -4609,9 +4611,11 @@ static void handleLifetimeCategoryAttr(S
   }
   return;
 }
-D->addAttr(::new (S.Context)
-   PointerAttr(AL.getRange(), S.Context, DerefTypeLoc,
-   AL.getAttributeSpellingListIndex()));
+for (Decl *Redecl : D->redecls()) {
+  Redecl->addAttr(::new (S.Context)
+  PointerAttr(AL.getRange(), S.Context, DerefTypeLoc,
+  AL.getAttributeSpellingListIndex()));
+}
   }
 }
 

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=371182&r1=371181&r2=371182&view=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/Se

[PATCH] D67172: [clangd] Use pre-populated mappings for standard symbols

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D67172#1657590 , @ilya-biryukov 
wrote:

> Also considered moving the std symbol mapping into a separate 
> (private-to-implementation) class, e.g. we don't use suffix mappings and 
> symbol mappings outside system includes.
>  But decided to wait until suffix mapping are going away completely.


It took me a while to understand this patch. I'd suggest doing it in this patch 
as well (it should not require large effort to do it, I think?)
The `CanonicalInclude` is becoming complex now, and leading to some wire design 
(we introduce a new field pointing to another instance).

And I'm not sure whether it is possible to remove the suffix mapping completely 
-- for STL symbols it is possible, but for other symbols like GNU C headers, I 
didn't find out an automatic way to build a lookup table.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67172



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


[PATCH] D67172: [clangd] Use pre-populated mappings for standard symbols

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Ok, agreed. Adding this indirection layer is probably making things a bit too 
complex. I'll update the patch to clearly separate the std symbol mapping and 
canonical includes.

In D67172#1660435 , @hokein wrote:

> And I'm not sure whether it is possible to remove the suffix mapping 
> completely -- for STL symbols it is possible, but for other symbols like GNU 
> C headers, I didn't find out an automatic way to build a lookup table.


It's because we don't have anything similar to cppreference.com for them? Maybe 
we could try scrapping man pages ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67172



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


[clang-tools-extra] r371194 - [clangd] Use override keyword to override the base class method, NFC

2019-09-06 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Fri Sep  6 03:24:39 2019
New Revision: 371194

URL: http://llvm.org/viewvc/llvm-project?rev=371194&view=rev
Log:
[clangd] Use override keyword to override the base class method, NFC

Modified:
clang-tools-extra/trunk/clangd/ParsedAST.cpp

Modified: clang-tools-extra/trunk/clangd/ParsedAST.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ParsedAST.cpp?rev=371194&r1=371193&r2=371194&view=diff
==
--- clang-tools-extra/trunk/clangd/ParsedAST.cpp (original)
+++ clang-tools-extra/trunk/clangd/ParsedAST.cpp Fri Sep  6 03:24:39 2019
@@ -110,9 +110,8 @@ public:
  std::vector 
&MainFileMacroLocs)
   : SM(SM), MainFileMacroLocs(MainFileMacroLocs) {}
 
-  virtual void MacroExpands(const Token &MacroNameTok,
-const MacroDefinition &MD, SourceRange Range,
-const MacroArgs *Args) {
+  void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
+SourceRange Range, const MacroArgs *Args) override {
 SourceLocation L = MacroNameTok.getLocation();
 if (!L.isMacroID() && isInsideMainFile(L, SM))
   MainFileMacroLocs.push_back(L);


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


[PATCH] D67024: [analyzer] NFC: Replace intrusive list of bug reports with a vector of pointers.

2019-09-06 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added a comment.

Still LGTM, just some nitpicks to replace iterator usage with index-based 
accesses (which I believe is simpler).




Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:569
SmallVectorImpl &bugReports) {
-return &*eqClass.begin();
+return eqClass.getReports().begin()->get();
   }

`getReports()[0]` ?



Comment at: clang/lib/StaticAnalyzer/Core/BugReporter.cpp:2803
   assert(I != E);
-  const BugType& BT = I->getBugType();
+  const BugType& BT = (*I)->getBugType();
 

```
assert(!EQ.getReports().empty());
const BugType& BT = EQ.getReports()[0]->getBugType();
```

?



Comment at: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:3139
+  const auto *R =
+  dyn_cast(EI->getReports().begin()->get());
   if (!R)

`getReports()[0]` ?


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

https://reviews.llvm.org/D67024



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


[PATCH] D67172: [clangd] Use pre-populated mappings for standard symbols

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 219061.
ilya-biryukov added a comment.

- Move system symbol mapping to a different class.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67172

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/index/CanonicalIncludes.cpp
  clang-tools-extra/clangd/index/CanonicalIncludes.h
  clang-tools-extra/clangd/index/IndexAction.cpp
  clang-tools-extra/clangd/unittests/CanonicalIncludesTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp

Index: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
===
--- clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -973,7 +973,7 @@
   CanonicalIncludes Includes;
   auto Language = LangOptions();
   Language.CPlusPlus = true;
-  addSystemHeadersMapping(&Includes, Language);
+  Includes.addSystemHeadersMapping(Language);
   CollectorOpts.Includes = &Includes;
   runSymbolCollector("namespace std { class string {}; }", /*Main=*/"");
   EXPECT_THAT(Symbols,
Index: clang-tools-extra/clangd/unittests/CanonicalIncludesTests.cpp
===
--- clang-tools-extra/clangd/unittests/CanonicalIncludesTests.cpp
+++ clang-tools-extra/clangd/unittests/CanonicalIncludesTests.cpp
@@ -7,17 +7,22 @@
 //===--===//
 
 #include "index/CanonicalIncludes.h"
+#include "clang/Basic/LangOptions.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace clangd {
 namespace {
 
+using llvm::ValueIs;
+using ::testing::Eq;
+
 TEST(CanonicalIncludesTest, CStandardLibrary) {
   CanonicalIncludes CI;
   auto Language = LangOptions();
   Language.C11 = true;
-  addSystemHeadersMapping(&CI, Language);
+  CI.addSystemHeadersMapping(Language);
   // Usual standard library symbols are mapped correctly.
   EXPECT_EQ("", CI.mapHeader("path/stdio.h", "printf"));
 }
@@ -26,7 +31,7 @@
   CanonicalIncludes CI;
   auto Language = LangOptions();
   Language.CPlusPlus = true;
-  addSystemHeadersMapping(&CI, Language);
+  CI.addSystemHeadersMapping(Language);
 
   // Usual standard library symbols are mapped correctly.
   EXPECT_EQ("", CI.mapHeader("path/vector.h", "std::vector"));
@@ -53,20 +58,24 @@
 
 TEST(CanonicalIncludesTest, SymbolMapping) {
   // As used for standard library.
-  CanonicalIncludes CI;
-  CI.addSymbolMapping("some::symbol", "");
+  StdIncludes SI;
+  SI.addSymbolMapping("some::symbol", "");
 
-  EXPECT_EQ("", CI.mapHeader("foo/bar", "some::symbol"));
-  EXPECT_EQ("foo/bar", CI.mapHeader("foo/bar", "other::symbol"));
+  EXPECT_THAT(SI.mapHeader("foo/bar", "some::symbol"),
+  ValueIs(StringRef("")));
+  EXPECT_THAT(SI.mapHeader("foo/bar", "other::symbol"), Eq(llvm::None));
 }
 
 TEST(CanonicalIncludesTest, Precedence) {
   CanonicalIncludes CI;
   CI.addMapping("some/path", "");
-  CI.addSymbolMapping("some::symbol", "");
+
+  LangOptions Language;
+  Language.CPlusPlus = true;
+  CI.addSystemHeadersMapping(Language);
 
   // Symbol mapping beats path mapping.
-  EXPECT_EQ("", CI.mapHeader("some/path", "some::symbol"));
+  EXPECT_EQ("", CI.mapHeader("some/path", "std::vector"));
 }
 
 } // namespace
Index: clang-tools-extra/clangd/index/IndexAction.cpp
===
--- clang-tools-extra/clangd/index/IndexAction.cpp
+++ clang-tools-extra/clangd/index/IndexAction.cpp
@@ -140,7 +140,7 @@
   std::unique_ptr
   CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
 CI.getPreprocessor().addCommentHandler(PragmaHandler.get());
-addSystemHeadersMapping(Includes.get(), CI.getLangOpts());
+Includes->addSystemHeadersMapping(CI.getLangOpts());
 if (IncludeGraphCallback != nullptr)
   CI.getPreprocessor().addPPCallbacks(
   std::make_unique(CI.getSourceManager(), IG));
Index: clang-tools-extra/clangd/index/CanonicalIncludes.h
===
--- clang-tools-extra/clangd/index/CanonicalIncludes.h
+++ clang-tools-extra/clangd/index/CanonicalIncludes.h
@@ -29,6 +29,8 @@
 namespace clang {
 namespace clangd {
 
+class StdIncludes;
+
 /// Maps a definition location onto an #include file, based on a set of filename
 /// rules.
 /// Only const methods (i.e. mapHeader) in this class are thread safe.
@@ -36,35 +38,30 @@
 public:
   CanonicalIncludes() = default;
 
-  /// Adds a string-to-string mapping from \p Path to \p CanonicalPath.
-  void addMapping(llvm::StringRef Path, llvm::StringRef CanonicalPath);
-
-  /// Maps files with last path components matching \p Suffix to \p
-  /// CanonicalPath.
-  void addPathSuffixMapping(llvm::S

[PATCH] D67172: [clangd] Use pre-populated mappings for standard symbols

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Not sure whether the new code is a win overall, it's still a bit messy
Let me know what you think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67172



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


[PATCH] D66791: [lldb][ELF] Read symbols from .gnu_debugdata sect.

2019-09-06 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk updated this revision to Diff 219038.
kwk added a comment.

- Fix spelling error


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66791

Files:
  lldb/CMakeLists.txt
  lldb/cmake/modules/LLDBConfig.cmake
  lldb/include/lldb/Host/Config.h.cmake
  lldb/include/lldb/Host/LZMA.h
  lldb/lit/Breakpoint/Inputs/minidebuginfo-lib.c
  lldb/lit/Breakpoint/Inputs/minidebuginfo-lib.h
  lldb/lit/Breakpoint/Inputs/minidebuginfo-main.c
  lldb/lit/Breakpoint/Inputs/minidebuginfo.keep_symbols
  lldb/lit/Breakpoint/minidebuginfo-corrupt-xz.yaml
  lldb/lit/Breakpoint/minidebuginfo-find-symbols.yaml
  lldb/lit/Breakpoint/minidebuginfo-no-lzma.yaml
  lldb/lit/Breakpoint/minidebuginfo-set-and-hit-breakpoint.test
  lldb/lit/CMakeLists.txt
  lldb/lit/lit.cfg.py
  lldb/lit/lit.site.cfg.py.in
  lldb/source/Host/CMakeLists.txt
  lldb/source/Host/common/LZMA.cpp
  lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
  lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h

Index: lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h
===
--- lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h
+++ lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h
@@ -208,6 +208,10 @@
   /// Collection of symbols from the dynamic table.
   DynamicSymbolColl m_dynamic_symbols;
 
+  /// Object file parsed from .gnu_debugdata section (\sa
+  /// GetGnuDebugDataObjectFile())
+  std::shared_ptr m_gnu_debug_data_object_file;
+
   /// List of file specifications corresponding to the modules (shared
   /// libraries) on which this object file depends.
   mutable std::unique_ptr m_filespec_up;
@@ -383,6 +387,14 @@
   lldb_private::UUID &uuid);
 
   bool AnySegmentHasPhysicalAddress();
+  
+  /// Takes the .gnu_debugdata and returns the decompressed object file that is
+  /// stored within that section.
+  ///
+  /// \returns either the decompressed object file stored within the
+  /// .gnu_debugdata section or \c nullptr if an error occured or if there's no
+  /// section with that name.
+  std::shared_ptr GetGnuDebugDataObjectFile();
 };
 
 #endif // liblldb_ObjectFileELF_h_
Index: lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
===
--- lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
+++ lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
@@ -18,6 +18,7 @@
 #include "lldb/Core/PluginManager.h"
 #include "lldb/Core/Section.h"
 #include "lldb/Host/FileSystem.h"
+#include "lldb/Host/LZMA.h"
 #include "lldb/Symbol/DWARFCallFrameInfo.h"
 #include "lldb/Symbol/SymbolContext.h"
 #include "lldb/Target/SectionLoadList.h"
@@ -1842,6 +1843,72 @@
   // unified section list.
   if (GetType() != eTypeDebugInfo)
 unified_section_list = *m_sections_up;
+  
+  // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
+  // embedded in there and replace the one in the original object file (if any).
+  // If there's none in the orignal object file, we add it to it.
+  SectionList *module_section_list = GetModule()->GetSectionList();
+  if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
+if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
+  if (SectionSP symtab_section_sp =
+  gdd_objfile_section_list->FindSectionByType(
+  eSectionTypeELFSymbolTable, true)) {
+SectionSP module_section_sp = module_section_list->FindSectionByType(
+eSectionTypeELFSymbolTable, true);
+if (module_section_sp)
+  module_section_list->ReplaceSection(module_section_sp->GetID(),
+  symtab_section_sp);
+else
+  module_section_list->AddSection(symtab_section_sp);
+  }
+}
+  }  
+}
+
+std::shared_ptr ObjectFileELF::GetGnuDebugDataObjectFile() {
+  if (m_gnu_debug_data_object_file != nullptr)
+return m_gnu_debug_data_object_file;
+
+  SectionSP section =
+  GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));
+  if (!section)
+return nullptr;
+
+  if (!lldb_private::lzma::isAvailable()) {
+GetModule()->ReportWarning(
+"No LZMA support found for reading .gnu_debugdata section");
+return nullptr;
+  }
+
+  // Uncompress the data
+  DataExtractor data;
+  section->GetSectionData(data);
+  llvm::ArrayRef compressedData(data.GetDataStart(), data.GetByteSize());
+  llvm::SmallVector uncompressedData;
+  auto err = lldb_private::lzma::uncompress(compressedData, uncompressedData);
+  if (err) {
+GetModule()->ReportWarning(
+"An error occurred while decompression the section %s: %s",
+section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());
+return nullptr;
+  }
+
+  // Construct ObjectFileELF object from decompressed buffer
+  DataBufferSP gdd_data_buf(
+  new DataBufferHeap(uncompressedData.data(), uncompr

[PATCH] D67172: [clangd] Use pre-populated mappings for standard symbols

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/index/CanonicalIncludes.cpp:780
+  // Prefer a mapping from the system symbols.
+  if (SystemSymbols) {
+if (auto Result = SystemSymbols->mapHeader(Header, QualifiedName))

what's the interesting case where `SystemSymbols` is null?
I think it should be fine to always use the standard symbol mapping here? just 
use `getStandardSymbolMapping()->mapHeader()`, this would help to simplify the 
CanonicalInclude interface (no `addSystemHeadersMapping` and `SystemSymbols` 
members  are needed).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67172



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


[PATCH] D67172: [clangd] Use pre-populated mappings for standard symbols

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D67172#1660469 , @ilya-biryukov 
wrote:

> Ok, agreed. Adding this indirection layer is probably making things a bit too 
> complex. I'll update the patch to clearly separate the std symbol mapping and 
> canonical includes.
>
> In D67172#1660435 , @hokein wrote:
>
> > And I'm not sure whether it is possible to remove the suffix mapping 
> > completely -- for STL symbols it is possible, but for other symbols like 
> > GNU C headers, I didn't find out an automatic way to build a lookup table.
>
>
> It's because we don't have anything similar to cppreference.com for them? 
> Maybe we could try scrapping man pages ?


yes, cppreferences only provides symbols from C++/C standard libraries. Parsing 
man page is possible, but it requires some work (we have to write another tool 
to parse it).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67172



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


[PATCH] D67140: [analyzer][NFC] Fix inconsistent references to checkers as "checks"

2019-09-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D67140#1659978 , @Szelethus wrote:

> In D67140#1659907 , @NoQ wrote:
>
> > In D67140#1659872 , @aaron.ballman 
> > wrote:
> >
> > > If we're okay with the inconsistency but still feel like giving ourselves 
> > > more work, adding proper punctuation to Static Analyzer diagnostics would 
> > > at least make them grammatically correct. :-D
> >
> >
> > I'd love us some punctuation! Unfortunately the last time a person who 
> > actually speaks English committed actively to the Static Analyzer was, 
> > like, a couple of years ago at least (:
>
>
> I guess there's a joke waiting to be made about a couple Hungarians and 
> Russians discussing how to write proper English :^)


LOL!

> With that said, we could ask @whisperity to chip in more, he has an 
> ever-growing academic background, and a keen eye for grammatical errors.

I am also happy to help out with this task, though it would have to be on my 
own time as a best-faith effort.

In D67140#1659982 , @gribozavr wrote:

> We should take a page from desktop software here. If the messages were in a 
> separate file, there would be a lot of people capable of mass-editing them. 
> When messages are hardcoded in the tool code, navigating and editing them 
> requires more skill, and definitely a lot more jumping around.


Agreed -- this is why Clang puts its diagnostics into .td files (it's not 
perfect because people still sometimes use positional args when %select{} would 
be easier to localize, but it's a great start). I think the difficulty the 
static analyzer and clang-tidy would have doing this is in figuring out how to 
organize the diagnostics without breaking checker layering.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67140



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


[PATCH] D64671: [clang-tidy] New check: misc-init-local-variables

2019-09-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Aside from the missing documentation bit, I think this LG.




Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp:29
+  Options.getLocalOrGlobal("IncludeStyle", "llvm"))),
+  MathHeader(Options.get("MathHeader", "math.h")) {}
+

You need to document this option.


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

https://reviews.llvm.org/D64671



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


[PATCH] D64644: [Sema] Fixes an assertion failure while instantiation a template with an incomplete typo corrected type

2019-09-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


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

https://reviews.llvm.org/D64644



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


[PATCH] D67264: [clangd] Collect location of macro definition in the ParsedAST

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.
hokein retitled this revision from "[clangd] Collect location of macro 
definition in the ParsedAST

allows semantic hightlighting macro definition" to "[clangd] Collect location 
of macro definition in the ParsedAST".
hokein edited the summary of this revision.
hokein updated this revision to Diff 219067.
hokein added a comment.
hokein added a reviewer: ilya-biryukov.

update


allows semantic hightlighting macro definition


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D67264

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -390,20 +390,22 @@
   // Tokens that share a source range but have conflicting Kinds are not
   // highlighted.
   R"cpp(
-  #define DEF_MULTIPLE(X) namespace X { class X { int X; }; }
-  #define DEF_CLASS(T) class T {};
+  // Preamble ends here.
+  namespace {
+  #define $Macro[[DEF_MULTIPLE]](X) namespace X { class X { int X; }; }
+  #define $Macro[[DEF_CLASS]](T) class T {};
   $Macro[[DEF_MULTIPLE]](XYZ);
   $Macro[[DEF_MULTIPLE]](XYZW);
   $Macro[[DEF_CLASS]]($Class[[A]])
-  #define MACRO_CONCAT(X, V, T) T foo##X = V
-  #define DEF_VAR(X, V) int X = V
-  #define DEF_VAR_T(T, X, V) T X = V
-  #define DEF_VAR_REV(V, X) DEF_VAR(X, V)
-  #define CPY(X) X
-  #define DEF_VAR_TYPE(X, Y) X Y
-  #define SOME_NAME variable
-  #define SOME_NAME_SET variable2 = 123
-  #define INC_VAR(X) X += 2
+  #define $Macro[[MACRO_CONCAT]](X, V, T) T foo##X = V
+  #define $Macro[[DEF_VAR]](X, V) int X = V
+  #define $Macro[[DEF_VAR_T]](T, X, V) T X = V
+  #define $Macro[[DEF_VAR_REV]](V, X) DEF_VAR(X, V)
+  #define $Macro[[CPY]](X) X
+  #define $Macro[[DEF_VAR_TYPE]](X, Y) X Y
+  #define $Macro[[SOME_NAME]] variable
+  #define $Macro[[SOME_NAME_SET]] variable2 = 123
+  #define $Macro[[INC_VAR]](X) X += 2
   $Primitive[[void]] $Function[[foo]]() {
 $Macro[[DEF_VAR]]($LocalVariable[[X]],  123);
 $Macro[[DEF_VAR_REV]](908, $LocalVariable[[XY]]);
@@ -422,15 +424,18 @@
   $Macro[[DEF_VAR]]($Variable[[XYZ]], 567);
   $Macro[[DEF_VAR_REV]](756, $Variable[[AB]]);
 
-  #define CALL_FN(F) F();
-  #define DEF_FN(F) void F ()
+  #define $Macro[[CALL_FN]](F) F();
+  #define $Macro[[DEF_FN]](F) void F ()
   $Macro[[DEF_FN]]($Function[[g]]) {
 $Macro[[CALL_FN]]($Function[[foo]]);
   }
+  } // namespace
 )cpp",
   R"cpp(
-  #define fail(expr) expr
-  #define assert(COND) if (!(COND)) { fail("assertion failed" #COND); }
+  // Preamble ends here.
+  namespace {
+  #define $Macro[[fail]](expr) expr
+  #define $Macro[[assert]](COND) if (!(COND)) { fail("assertion failed" #COND); }
   $Primitive[[int]] $Variable[[x]];
   $Primitive[[int]] $Variable[[y]];
   $Primitive[[int]] $Function[[f]]();
@@ -438,8 +443,9 @@
 $Macro[[assert]]($Variable[[x]] != $Variable[[y]]);
 $Macro[[assert]]($Variable[[x]] != $Function[[f]]());
   }
+  } // namespace
 )cpp",
-R"cpp(
+  R"cpp(
   struct $Class[[S]] {
 $Primitive[[float]] $Field[[Value]];
 $Class[[S]] *$Field[[Next]];
Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -229,32 +229,36 @@
 
 TEST(ParsedASTTest, CollectsMainFileMacroExpansions) {
   Annotations TestCase(R"cpp(
-#define MACRO_ARGS(X, Y) X Y
+  // Preamble ends here.
+  namespace {
+#define ^MACRO_ARGS(X, Y) X Y
 ^ID(int A);
 // Macro arguments included.
 ^MACRO_ARGS(^MACRO_ARGS(^MACRO_EXP(int), A), ^ID(= 2));
 
 // Macro names inside other macros not included.
-#define FOO BAR
-#define BAR 1
+#define ^MACRO_ARGS2(X, Y) X Y
+#define ^FOO BAR
+#define ^BAR 1
 int A = ^FOO;
 
 // Macros from token concatenations not included.
-#define CONCAT(X) X##A()
-#define PREPEND(X) MACRO##X()
-#define MACROA() 123
+#define ^CONCAT(X) X##A()
+#define ^PREPEND(X) MACRO##X()
+#define ^MACROA() 123
 int B = ^CONCAT(MACRO);
 int D = ^PREPEND(A)
 
 // Macros included not from preamble not included.
 #include "foo.inc"
 
-#define assert(COND) if (!(COND)) { printf("%s", #CO

[PATCH] D67264: [clangd] Collect location of macro definition in the ParsedAST

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 219067.
hokein added a comment.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67264

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -390,20 +390,22 @@
   // Tokens that share a source range but have conflicting Kinds are not
   // highlighted.
   R"cpp(
-  #define DEF_MULTIPLE(X) namespace X { class X { int X; }; }
-  #define DEF_CLASS(T) class T {};
+  // Preamble ends here.
+  namespace {
+  #define $Macro[[DEF_MULTIPLE]](X) namespace X { class X { int X; }; }
+  #define $Macro[[DEF_CLASS]](T) class T {};
   $Macro[[DEF_MULTIPLE]](XYZ);
   $Macro[[DEF_MULTIPLE]](XYZW);
   $Macro[[DEF_CLASS]]($Class[[A]])
-  #define MACRO_CONCAT(X, V, T) T foo##X = V
-  #define DEF_VAR(X, V) int X = V
-  #define DEF_VAR_T(T, X, V) T X = V
-  #define DEF_VAR_REV(V, X) DEF_VAR(X, V)
-  #define CPY(X) X
-  #define DEF_VAR_TYPE(X, Y) X Y
-  #define SOME_NAME variable
-  #define SOME_NAME_SET variable2 = 123
-  #define INC_VAR(X) X += 2
+  #define $Macro[[MACRO_CONCAT]](X, V, T) T foo##X = V
+  #define $Macro[[DEF_VAR]](X, V) int X = V
+  #define $Macro[[DEF_VAR_T]](T, X, V) T X = V
+  #define $Macro[[DEF_VAR_REV]](V, X) DEF_VAR(X, V)
+  #define $Macro[[CPY]](X) X
+  #define $Macro[[DEF_VAR_TYPE]](X, Y) X Y
+  #define $Macro[[SOME_NAME]] variable
+  #define $Macro[[SOME_NAME_SET]] variable2 = 123
+  #define $Macro[[INC_VAR]](X) X += 2
   $Primitive[[void]] $Function[[foo]]() {
 $Macro[[DEF_VAR]]($LocalVariable[[X]],  123);
 $Macro[[DEF_VAR_REV]](908, $LocalVariable[[XY]]);
@@ -422,15 +424,18 @@
   $Macro[[DEF_VAR]]($Variable[[XYZ]], 567);
   $Macro[[DEF_VAR_REV]](756, $Variable[[AB]]);
 
-  #define CALL_FN(F) F();
-  #define DEF_FN(F) void F ()
+  #define $Macro[[CALL_FN]](F) F();
+  #define $Macro[[DEF_FN]](F) void F ()
   $Macro[[DEF_FN]]($Function[[g]]) {
 $Macro[[CALL_FN]]($Function[[foo]]);
   }
+  } // namespace
 )cpp",
   R"cpp(
-  #define fail(expr) expr
-  #define assert(COND) if (!(COND)) { fail("assertion failed" #COND); }
+  // Preamble ends here.
+  namespace {
+  #define $Macro[[fail]](expr) expr
+  #define $Macro[[assert]](COND) if (!(COND)) { fail("assertion failed" #COND); }
   $Primitive[[int]] $Variable[[x]];
   $Primitive[[int]] $Variable[[y]];
   $Primitive[[int]] $Function[[f]]();
@@ -438,8 +443,9 @@
 $Macro[[assert]]($Variable[[x]] != $Variable[[y]]);
 $Macro[[assert]]($Variable[[x]] != $Function[[f]]());
   }
+  } // namespace
 )cpp",
-R"cpp(
+  R"cpp(
   struct $Class[[S]] {
 $Primitive[[float]] $Field[[Value]];
 $Class[[S]] *$Field[[Next]];
Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -229,32 +229,36 @@
 
 TEST(ParsedASTTest, CollectsMainFileMacroExpansions) {
   Annotations TestCase(R"cpp(
-#define MACRO_ARGS(X, Y) X Y
+  // Preamble ends here.
+  namespace {
+#define ^MACRO_ARGS(X, Y) X Y
 ^ID(int A);
 // Macro arguments included.
 ^MACRO_ARGS(^MACRO_ARGS(^MACRO_EXP(int), A), ^ID(= 2));
 
 // Macro names inside other macros not included.
-#define FOO BAR
-#define BAR 1
+#define ^MACRO_ARGS2(X, Y) X Y
+#define ^FOO BAR
+#define ^BAR 1
 int A = ^FOO;
 
 // Macros from token concatenations not included.
-#define CONCAT(X) X##A()
-#define PREPEND(X) MACRO##X()
-#define MACROA() 123
+#define ^CONCAT(X) X##A()
+#define ^PREPEND(X) MACRO##X()
+#define ^MACROA() 123
 int B = ^CONCAT(MACRO);
 int D = ^PREPEND(A)
 
 // Macros included not from preamble not included.
 #include "foo.inc"
 
-#define assert(COND) if (!(COND)) { printf("%s", #COND); exit(0); }
+#define ^assert(COND) if (!(COND)) { printf("%s", #COND); exit(0); }
 
 void test() {
   // Includes macro expansions in arguments that are expressions
   ^assert(0 <= ^BAR);
 }
+  } // namespace
   )cpp");
   auto TU = TestTU::withCode(TestCase.code());
   TU.HeaderCode = R"cpp(
Index: clang-tools-extra/clangd/ParsedAST.h
===
--- clang-

[PATCH] D67264: [clangd] Collect location of macro definition in the ParsedAST

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:104
 // *definitions* in the preamble region of the main file).
 class CollectMainFileMacroExpansions : public PPCallbacks {
   const SourceManager &SM;

The name doesn't fit into what it does anymore, maybe rename to 
`CollectMainFileMacroLocations`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67264



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


[PATCH] D65761: Add Windows Control Flow Guard checks (/guard:cf).

2019-09-06 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.
Herald added a subscriber: ychen.

This is very exciting! I didn't look closely at the actual instrumentation 
code, as rnk knows that better and had some good comments.




Comment at: clang/include/clang/Driver/Options.td:500
 def b : JoinedOrSeparate<["-"], "b">, Flags<[Unsupported]>;
+def cfguard_no_checks : Flag<["-"], "cfguard-no-checks">, Flags<[CC1Option]>,
+  HelpText<"Emit Windows Control Flow Guard tables only (no checks).">;

rnk wrote:
> @hans, WDYT about the -cc1 interface? I think this is fine.
The -cc1 interface looks good to me, but since these are cc1 options only, I 
think they should be in CC1Options.td, not Options.td (I realize this is a 
pre-existing issue with -cfguard).



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:493
+  }
   if (CodeGenOpts.ControlFlowGuard) {
+// Function ID tables and checks for Control Flow Guard (cfguard=2).

Maybe check for this first, and then the ControlFlowGuardNoChecks one in an 
else-if, to make this one take precedence?



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5971
+
+if (Instrument && !NoChecks)
+  //Emit CFG instrumentation and the table of address-taken functions.

It seems unfortunate that the Instrument and NoChecks variables allow four 
different states. whereas I think the logic should really only allow for three: 
1) do nothing, 2) tables only, 3) tables and checks. Maybe we could have an 
enum instead?



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5972
+if (Instrument && !NoChecks)
+  //Emit CFG instrumentation and the table of address-taken functions.
   CmdArgs.push_back("-cfguard");

rnk wrote:
> Comment formatting needs to be fixed, you can use clang-format for this.
Also I'd suggest braces since even though there's just one statement, there are 
multiple lines here and in the else block.



Comment at: clang/lib/Driver/ToolChains/MSVC.cpp:420
+  // Flags that can simply be passed through.
+  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_guard);
 

Thanks for remembering /fallback. Please add a /guard:cf option to the first 
test in clang/test/Driver/cl-fallback.c



Comment at: llvm/docs/LangRef.rst:441
+This calling convention is used for the Control Flow Guard check function,
+   which can be inserted before indirect calls to check that the call 
target 
+   is a valid function address. The check function has no return value, but

Indentation looks a little off here.

"function, which can be inserted before indirect calls" -- maybe instead 
"function, calls to which can be inserted ..."



Comment at: llvm/docs/LangRef.rst:447
+
+- On X86_32 the target address is passed in ECX.
+- On ARM the target address is passed in R0.

I don't think X86_32 is common nomenclature.. maybe just X86 is enough.



Comment at: llvm/docs/LangRef.rst:456
+(architecture-specific) register. All other function arguments are 
+   passed as usual.
+

Indentation off here too.



Comment at: llvm/docs/LangRef.rst:458
+
+- On X86-64 the target address is passed in RAX.
 "``cc ``" - Numbered convention

Maybe explicitly call out in the text that this calling convention is only used 
on x86_64, and is used instead of cfguard_checkcc (iiuc)?



Comment at: llvm/include/llvm/IR/CallingConv.h:79
+/// Special calling convention on Windows for calling the Control
+/// Guard Check ICall funtion. The function take exactly one argument
+/// (address of the target function) passed in the first argument register,

nit: s/take/takes/



Comment at: llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp:381
 
+  // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2)
   if (mdconst::extract_or_null(

ultra nit: period at the end, here and for other comments



Comment at: llvm/lib/Target/X86/X86FixupCFGuard.cpp:13
+/// for such cases and replaces the pair of instructions with a single
+/// call/invoke. For example:
+///

Naive question: Why do we generate code as in the examples in the first place, 
and can't some general optimization pass do this folding? From the examples it 
looks like straight-forward constant propagation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65761



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


[PATCH] D65917: [clang-tidy] Added check for the Google style guide's category method naming rule.

2019-09-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/google/RequireCategoryMethodPrefixesCheck.cpp:57
+  }
+  std::string method_name = method_declaration->getNameAsString();
+  auto owning_objc_class_interface = method_declaration->getClassInterface();

dgatwood wrote:
> aaron.ballman wrote:
> > dgatwood wrote:
> > > aaron.ballman wrote:
> > > > dgatwood wrote:
> > > > > aaron.ballman wrote:
> > > > > > This should use `getName()` to get a `StringRef` to avoid the copy.
> > > > > That's actually what I originally tried, but that method won't work 
> > > > > here, unless I'm missing something.  The getName() method crashes 
> > > > > with a message saying that "Name is not a simple identifier".
> > > > You can call `getIdentifier()` instead, and if you get a non-null 
> > > > object back, you can call `getName()` on that. If it is null, there's 
> > > > nothing to check.
> > > I just tried it, and getIdentifier() returns NULL consistently for every 
> > > category method, so I changed it back to getNameAsString(), which works.
> > The comment to use `getIdentifier()` was marked as done but the changes 
> > were not applied; was that a mistake? I'm pushing back on 
> > `getNameAsString()` because the function is commented as having its use 
> > discouraged, so we should not be adding new uses of it.
> I marked that as done because I tried it and it didn't work.  The 
> getIdentifier() method returned NULL for every category method.
> 
> BTW, this isn't my first attempt at writing this code in a way that doesn't 
> require that method.  I literally fought with getting the name of category 
> methods for a day or more when I first started writing this, because I kept 
> getting NULLs or crashes.  At one point, I think I even tried looking for the 
> owning class and querying its interface.  Nothing worked until I discovered 
> getNameAsString().
> 
> I'm assuming that this is simply a bug somewhere in the LLVM core that nobody 
> has noticed or bothered to fix, because it really should not be difficult to 
> get the name of a method.  :-/
> I'm assuming that this is simply a bug somewhere in the LLVM core that nobody 
> has noticed or bothered to fix, because it really should not be difficult to 
> get the name of a method. :-/

I am not certain if it's a bug or not, but we shouldn't be using essentially 
deprecated APIs to work around bugs elsewhere. I'd really like to know what's 
going on here. I am looking through the logic of DeclarationName::print() 
(which is what getNameAsString() eventually calls into) and it doesn't look 
like it makes any special accommodations for ObjC method declarations, but it 
does for ObjC selectors. I'm not an ObjC expert, but I think that's what the 
name of an ObjC method is, isn't it? If so, I think you would do (assuming the 
methods can only be named using selectors):
```
MethodDeclaration->getDeclName().getObjCSelector().getAsString()
```



Comment at: 
clang-tools-extra/clang-tidy/google/RequireCategoryMethodPrefixesCheck.cpp:30
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "WhitelistedPrefixes", WhitelistedPrefixes);
+}

dgatwood wrote:
> aaron.ballman wrote:
> > dgatwood wrote:
> > > aaron.ballman wrote:
> > > > `ExpectedPrefixes` here as well.
> > > > 
> > > > Should there be a default list of these?
> > > Done.  And no, there should be no default, unless somehow Xcode's project 
> > > prefix makes it down as far as LLVM, in which case //maybe// that could 
> > > be the default.
> > > 
> > > The idea is that you can whitelist your own Xcode project's prefix, along 
> > > with the prefixes of your own in-house libraries, so that each individual 
> > > team/workgroup can add categories on their own classes, but will get 
> > > warned when they try to add unprefixed category methods on classes that 
> > > they don't own (e.g. classes in system frameworks, third-party 
> > > frameworks, etc.).
> > Still wondering whether we should have a default list of expected prefixes 
> > or not.
> This is weird.  I don't know why this comment system didn't submit my comment 
> before.
> 
> No, there should be no default, unless somehow Xcode's project prefix makes 
> it down as far as LLVM, in which case maybe that could be the default.
> 
> The idea is that you can whitelist your own Xcode project's prefix, along 
> with the prefixes of your own in-house libraries, so that each individual 
> team/workgroup can add categories on their own classes, but will get warned 
> when they try to add unprefixed category methods on classes that they don't 
> own (e.g. classes in system frameworks, third-party frameworks, etc.).
Ah, thank you for the explanation!



Comment at: 
clang-tools-extra/clang-tidy/google/RequireCategoryMethodPrefixesCheck.cpp:56
+  // the error "Name is not a simple identifier".
+  StringRef method_name = method_declaration->getNameAsStrin

[PATCH] D67185: [RISCV] Add support for -ffixed-xX flags

2019-09-06 Thread Simon Cook via Phabricator via cfe-commits
simoncook updated this revision to Diff 219068.
simoncook edited the summary of this revision.
simoncook added a comment.

Update based on initial feedback/going down the providing error route.

Unlike AArch64, which provides an error if a function tries to call a function 
with arguments and any of the argument passing registers are used, I've gone 
down a more detailed route. I've added tests for any place where any ABI 
register will be modified, and produce an error indicating what part of the ABI 
requires this register.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67185

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/test/Driver/riscv-fixed-x-register.c
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVISelLowering.h
  llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVRegisterInfo.h
  llvm/lib/Target/RISCV/RISCVSubtarget.cpp
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/reserved-reg-errors.ll
  llvm/test/CodeGen/RISCV/reserved-regs.ll

Index: llvm/test/CodeGen/RISCV/reserved-regs.ll
===
--- /dev/null
+++ llvm/test/CodeGen/RISCV/reserved-regs.ll
@@ -0,0 +1,130 @@
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x3 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X3
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x3 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X3
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x4 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X4
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x4 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X4
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x5 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X5
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x5 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X5
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x6 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X6
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x6 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X6
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x7 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X7
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x7 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X7
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x8 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X8
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x8 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X8
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x9 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X9
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x9 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X9
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x10 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X10
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x10 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X10
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x11 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X11
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x11 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X11
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x12 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X12
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x12 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X12
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x13 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X13
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x13 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X13
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x14 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X14
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x14 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X14
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x15 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X15
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x15 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X15
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x16 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X16
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x16 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X16
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x17 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X17
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x17 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X17
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x18 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X18
+; RUN: llc -mtriple=riscv64 -mattr=+reserve-x18 -verify-machineinstrs < %s | FileCheck %s -check-prefix=X18
+; RUN: llc -mtriple=riscv32 -mattr=+reserve-x19 -verify-machineinstrs < %s | FileCheck %s -check-pr

[PATCH] D67265: [clang-tidy] Magic number checker shouldn't warn on user defined string literals

2019-09-06 Thread Tibor Brunner via Phabricator via cfe-commits
bruntib created this revision.
bruntib added reviewers: alexfh, Szelethus, 0x8000-, aaron.ballman.
Herald added subscribers: cfe-commits, xazax.hun, whisperity.
Herald added a project: clang.

The following code snippet results a false positive report in the magic number 
checker:

std::string s = "Hello World"s;

The expression "Hello World"s has a StringLiteral in its AST, since this is a 
function call on std::string operator "" s(const char* std::size_t) and the 
second parameter is passed the length of the string literal.

This patch fixes https://bugs.llvm.org/show_bug.cgi?id=40633


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D67265

Files:
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp


Index: clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp
===
--- clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp
+++ clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s readability-magic-numbers %t \
+// RUN: %check_clang_tidy -std=c++14 %s readability-magic-numbers %t \
 // RUN: -config='{CheckOptions: \
 // RUN:  [{key: readability-magic-numbers.IgnoredIntegerValues, value: 
"0;1;2;10;100;"}, \
 // RUN:   {key: readability-magic-numbers.IgnoredFloatingPointValues, value: 
"3.14;2.71828;9.81;1.0;101.0;0x1.2p3"}, \
@@ -197,3 +197,18 @@
 
   return Total;
 }
+
+namespace std {
+  class string {};
+  using size_t = decltype(sizeof(int));
+  string operator "" s(const char *, std::size_t);
+  int operator "" s(unsigned long long);
+}
+
+void UserDefinedLiteral() {
+  using std::operator ""s;
+  "Hello World"s;
+  const int i = 3600s;
+  int j = 3600s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; 
consider replacing it with a named constant [readability-magic-numbers]
+}
Index: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
@@ -112,10 +112,21 @@
   return llvm::any_of(
   Result.Context->getParents(ExprResult),
   [&Result](const DynTypedNode &Parent) {
-return isUsedToInitializeAConstant(Result, Parent) ||
-   // Ignore this instance, because this match reports the location
-   // where the template is defined, not where it is instantiated.
-   Parent.get();
+if (isUsedToInitializeAConstant(Result, Parent))
+  return true;
+
+// Ignore this instance, because this match reports the location
+// where the template is defined, not where it is instantiated.
+if (Parent.get())
+  return true;
+
+// Don't warn on string user defined literals:
+// std::string s = "Hello World"s;
+if (const UserDefinedLiteral *UDL = Parent.get())
+  if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)
+return true;
+
+return false;
   });
 }
 


Index: clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp
===
--- clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp
+++ clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s readability-magic-numbers %t \
+// RUN: %check_clang_tidy -std=c++14 %s readability-magic-numbers %t \
 // RUN: -config='{CheckOptions: \
 // RUN:  [{key: readability-magic-numbers.IgnoredIntegerValues, value: "0;1;2;10;100;"}, \
 // RUN:   {key: readability-magic-numbers.IgnoredFloatingPointValues, value: "3.14;2.71828;9.81;1.0;101.0;0x1.2p3"}, \
@@ -197,3 +197,18 @@
 
   return Total;
 }
+
+namespace std {
+  class string {};
+  using size_t = decltype(sizeof(int));
+  string operator "" s(const char *, std::size_t);
+  int operator "" s(unsigned long long);
+}
+
+void UserDefinedLiteral() {
+  using std::operator ""s;
+  "Hello World"s;
+  const int i = 3600s;
+  int j = 3600s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+}
Index: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
@@ -112,10 +112,21 @@
   return llvm::any_of(
   Result.Context->getParents(ExprResult),
   [&Result](const DynTypedNode &Parent) {
-return isUsedToInitializeAConstant(Result, Parent) ||
-   // Ignore this instance, because this match reports the location
-   // where the template is def

[PATCH] D67265: [clang-tidy] Magic number checker shouldn't warn on user defined string literals

2019-09-06 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/readability-magic-numbers.cpp:1
-// RUN: %check_clang_tidy %s readability-magic-numbers %t \
+// RUN: %check_clang_tidy -std=c++14 %s readability-magic-numbers %t \
 // RUN: -config='{CheckOptions: \

IIRC `%check_clang_tidy` is actually run for every standard, so this decreases 
test coverage;
just add a c++14-specific test.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D67265



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


[PATCH] D67265: [clang-tidy] Magic number checker shouldn't warn on user defined string literals

2019-09-06 Thread Florin Iucha via Phabricator via cfe-commits
0x8000- accepted this revision.
0x8000- added a comment.
This revision is now accepted and ready to land.

Looks good to me. Thank you for the fix.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D67265



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


[PATCH] D66951: [ASTImporter] Add comprehensive tests for ODR violation handling strategies

2019-09-06 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: clang/unittests/AST/ASTImporterODRStrategiesTest.cpp:36
+  static constexpr auto *Definition = "void X(int a) {}";
+  static constexpr auto *ConflictingDefinition = "void X(double a) {}";
+  BindableMatcher getPattern() {

Probably for (non-member?) functions there is no possibility for conflicting 
definition (for same prototype)? This can be the case if the function body is 
different but this is not checked now. For functions no name conflict happens 
because of overload, at least if C++ is used. I think the tests here with 
functions are not needed or only for C language. (Do all these pass?)



Comment at: clang/unittests/AST/ASTImporterODRStrategiesTest.cpp:128
+};
+
+struct ClassTemplateSpec {

Is this better?
```
struct VariableTemplate {
  using DeclTy = VarTemplateDecl;
  static constexpr auto *Prototype = "template  extern T X;";
  static constexpr auto *ConflictingPrototype =
  "template  extern float X;";
  static constexpr auto *Definition =
  R"(
  template  T X;
  template <> int X;
  )";
  static constexpr auto *ConflictingDefinition =
  R"(
  template  T X;
  template <> float X;
  )";
  static constexpr auto *ConflictingProtoDef =
  R"(
  template  float X;
  template <> float X;
  )";
  // There is no matcher for varTemplateDecl so use a work-around.
  BindableMatcher getPattern() {
return namedDecl(hasName("X"), unless(isImplicit()),
 has(templateTypeParmDecl()));
  }
};
```



Comment at: clang/unittests/AST/ASTImporterODRStrategiesTest.cpp:151
+};
+
+template 

`FunctionTemplate` and `FunctionTemplateSpec` are missing?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66951



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


[PATCH] D67265: [clang-tidy] Magic number checker shouldn't warn on user defined string literals

2019-09-06 Thread Tibor Brunner via Phabricator via cfe-commits
bruntib updated this revision to Diff 219088.
bruntib edited the summary of this revision.
bruntib added a comment.

Thank you for the suggestion. I didn't know about this behavior of 
`%check_clang_tidy`.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D67265

Files:
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp


Index: 
clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
@@ -0,0 +1,16 @@
+// RUN: %check_clang_tidy -std=c++14-or-later %s readability-magic-numbers %t 
--
+
+namespace std {
+  class string {};
+  using size_t = decltype(sizeof(int));
+  string operator "" s(const char *, std::size_t);
+  int operator "" s(unsigned long long);
+}
+
+void UserDefinedLiteral() {
+  using std::operator ""s;
+  "Hello World"s;
+  const int i = 3600s;
+  int j = 3600s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; 
consider replacing it with a named constant [readability-magic-numbers]
+}
Index: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
@@ -112,10 +112,21 @@
   return llvm::any_of(
   Result.Context->getParents(ExprResult),
   [&Result](const DynTypedNode &Parent) {
-return isUsedToInitializeAConstant(Result, Parent) ||
-   // Ignore this instance, because this match reports the location
-   // where the template is defined, not where it is instantiated.
-   Parent.get();
+if (isUsedToInitializeAConstant(Result, Parent))
+  return true;
+
+// Ignore this instance, because this match reports the location
+// where the template is defined, not where it is instantiated.
+if (Parent.get())
+  return true;
+
+// Don't warn on string user defined literals:
+// std::string s = "Hello World"s;
+if (const UserDefinedLiteral *UDL = Parent.get())
+  if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)
+return true;
+
+return false;
   });
 }
 


Index: clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
@@ -0,0 +1,16 @@
+// RUN: %check_clang_tidy -std=c++14-or-later %s readability-magic-numbers %t --
+
+namespace std {
+  class string {};
+  using size_t = decltype(sizeof(int));
+  string operator "" s(const char *, std::size_t);
+  int operator "" s(unsigned long long);
+}
+
+void UserDefinedLiteral() {
+  using std::operator ""s;
+  "Hello World"s;
+  const int i = 3600s;
+  int j = 3600s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+}
Index: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
@@ -112,10 +112,21 @@
   return llvm::any_of(
   Result.Context->getParents(ExprResult),
   [&Result](const DynTypedNode &Parent) {
-return isUsedToInitializeAConstant(Result, Parent) ||
-   // Ignore this instance, because this match reports the location
-   // where the template is defined, not where it is instantiated.
-   Parent.get();
+if (isUsedToInitializeAConstant(Result, Parent))
+  return true;
+
+// Ignore this instance, because this match reports the location
+// where the template is defined, not where it is instantiated.
+if (Parent.get())
+  return true;
+
+// Don't warn on string user defined literals:
+// std::string s = "Hello World"s;
+if (const UserDefinedLiteral *UDL = Parent.get())
+  if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)
+return true;
+
+return false;
   });
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D65182: [analyzer] Add fix-it hint support.

2019-09-06 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:491
+   ArrayRef Ranges = None,
+   ArrayRef Fixits = None);
 

NoQ wrote:
> gribozavr wrote:
> > I'm not sure if this is the right model for fixits. Fixits are usually 
> > associated with a message that explains what the fixit does. Only in the 
> > unusual case where Clang or ClangTidy is very confident that the fixit is 
> > correct, it is attached to the warning. Most commonly, fixits are attached 
> > to notes.
> > 
> > Also, for IDE support, it would be really nice if we could provide short 
> > descriptions of edits themselves (e.g., "replace 'virtual' with 'override") 
> > that can be displayed to the user instead of the diff when possible -- 
> > right now we don't and tools using ClangTidy have to use a subpar UI 
> > because of that. For example, when we show UI for fixing a warning, 
> > displaying the complete diff is too much; a concise description would be a 
> > lot better.
> > Fixits are usually associated with a message that explains what the fixit 
> > does. Only in the unusual case where Clang or ClangTidy is very confident 
> > that the fixit is correct, it is attached to the warning.
> 
> Wait, you guys already have fixits attached to notes? Then, yeah, i need to 
> support this.
> 
> > Also, for IDE support, it would be really nice if we could provide short 
> > descriptions of edits themselves (e.g., "replace 'virtual' with 'override") 
> > that can be displayed to the user instead of the diff when possible -- 
> > right now we don't and tools using ClangTidy have to use a subpar UI 
> > because of that.
> 
> Mmm, interesting. I've seen this IDE of ours autogenerate such messages as 
> "replace '`$code_in_removed_range`' with '`$inserted_code`'" (while also 
> combining multiple parts of the fixit into a single replacement under the 
> hood) and it looked quite bearable most of the time and i silently assumed 
> that everybody does the same thing.
> 
> I agree that a high-level description of a fixit is nice to have. But given 
> that you're attaching fixits to notes, isn't the text of the note text itself 
> sufficient? E.g.:
> - warning: variable may be used uninitialized here
> - note: initialize 'x' here to suppress the warning
>   - fixit: add ' = 0' after 'x'
> Wait, you guys already have fixits attached to notes? Then, yeah, i need to 
> support this.

Yes, fixits are attached to notes in Clang and ClangTidy.

> Mmm, interesting. I've seen this IDE of ours autogenerate such messages as 
> "replace '$code_in_removed_range' with '$inserted_code'" (while also 
> combining multiple parts of the fixit into a single replacement under the 
> hood) and it looked quite bearable most of the time and i silently assumed 
> that everybody does the same thing.

We are doing the same thing, however, it only works well when the edit text is 
meaningful. For example, a hypothetical "replace const with constexpr" edit 
looks readable. However, "insert '(*' and insert ')'" does not read well, 
"dereference the pointer" would be better.

> I agree that a high-level description of a fixit is nice to have. But given 
> that you're attaching fixits to notes, isn't the text of the note text itself 
> sufficient? E.g.:

Often yes, however not always. Also, fixits can be attached to warnings 
themselves. For example:

warning: #includes are not sorted according to the style guide
attached fixit: , 


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

https://reviews.llvm.org/D65182



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


[PATCH] D67122: [UBSan][clang][compiler-rt] Applying non-zero offset to nullptr is undefined behaviour

2019-09-06 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri marked 5 inline comments as done.
lebedev.ri added inline comments.
Herald added a subscriber: ychen.



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:4703-4720
+// 2) The sign of the difference between the computed address and the base
+// pointer matches the sign of the total offset.
+llvm::Value *ValidGEP;
+auto *NoOffsetOverflow = Builder.CreateNot(OffsetOverflows);
+if (SignedIndices) {
+  auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
+  auto *PosOrZeroOffset = Builder.CreateICmpSGE(TotalOffset, Zero);

vsk wrote:
> lebedev.ri wrote:
> > lebedev.ri wrote:
> > > This makes me ick every time i look at it.
> > > I wonder if this can be sanely rewritten via `.with.overflow` intrinsic..
> > Hm, 
> > ```
> > Name: add unsigned
> >   %computed = add i8 %base, %offset
> >   %PosOrZeroValid = icmp uge i8 %computed, %base
> > =>
> >   %agg = uadd_overflow i8 %base, %offset
> >   %computed = extractvalue i8 %agg, 0
> >   %ov = extractvalue i1 %agg, 1
> >   %PosOrZeroValid = xor i1 %ov, -1
> > 
> > Name: sub unsigned
> >   %computed = add i8 %base, %offset
> >   %PosOrZeroValid = icmp ule i8 %computed, %base
> > =>
> >   %negated_offset = sub i8 0, %offset
> >   %agg = usub_overflow i8 %base, %negated_offset
> >   %computed = extractvalue i8 %agg, 0
> >   %ov = extractvalue i1 %agg, 1
> >   %PosOrZeroValid = xor i1 %ov, -1
> > 
> > Name: add signed
> >   %computed = add i8 %base, %offset
> >   %PosOrZeroValid = icmp uge i8 %computed, %base
> >   %PosOrZeroOffset = icmp sge i8 %offset, 0
> >   %NegValid = icmp ult i8 %computed, %base
> >   %OKay = select i1 %PosOrZeroOffset, i1 %PosOrZeroValid, i1 %NegValid
> > =>
> >   %uadd.agg = uadd_overflow i8 %base, %offset
> >   %uadd.ov = extractvalue i1 %uadd.agg, 1
> >   %negated_offset = sub i8 0, %offset
> >   %usub.agg = usub_overflow i8 %base, %negated_offset
> >   %usub.ov = extractvalue i1 %usub.agg, 1
> >   %computed = add i8 %base, %offset
> >   %PosOrZeroOffset = icmp sge i8 %offset, 0
> >   %NotOKay = select i1 %PosOrZeroOffset, i1 %uadd.ov, i1 %usub.ov
> >   %OKay = xor i1 %NotOKay, -1
> > ```
> > 
> > That's not great, but i wonder what is more friendly to middle-end.
> > https://godbolt.org/z/ORSU_L
> I suggest splitting out changes to the existing pointer wraparound check in a 
> follow-up patch. This may well be an improvement, but there are enough moving 
> parts to this patch as-is.
I'll just precommit them, they are NFC.



Comment at: clang/test/CodeGen/catch-nullptr-and-nonzero-offset-blacklist.c:1
+// RUN: %clang_cc1 -fsanitize=pointer-overflow 
-fsanitize-recover=pointer-overflow -emit-llvm %s -o - -triple x86_64-linux-gnu 
| FileCheck %s -implicit-check-not="call void @__ubsan_handle_pointer_overflow" 
--check-prefixes=CHECK,CHECK-NULL-IS-INVALID-PTR
+// RUN: %clang_cc1 -fno-delete-null-pointer-checks -fsanitize=pointer-overflow 
-fsanitize-recover=pointer-overflow -emit-llvm %s -o - -triple x86_64-linux-gnu 
| FileCheck %s -implicit-check-not="call void @__ubsan_handle_pointer_overflow" 
--check-prefixes=CHECK,CHECK-NULL-IS-VALID-PTR

vsk wrote:
> lebedev.ri wrote:
> > vsk wrote:
> > > Should the test filename be "ignore-nullptr-and-nonzero-..."?
> > `-blacklist.c` is the filename i have i used for all similar testfiles in 
> > all previous sanitizers.
> > "black list" means here "list of cases where no sanitization will be 
> > emitted".
> This is minor. I only raised the nit as I felt that this test was about 
> ignoring "foo", not about catching "foo", and that "blacklist" already means 
> something else in the context of sanitizers. Happy to defer to your 
> preference here.
Nitpicking is good, less chance to omit something that wasn't intentional and 
is thus bad :)



Comment at: clang/test/CodeGen/ubsan-pointer-overflow.m:48
 void pointer_array_unsigned_indices(int **arr, unsigned k) {
   // CHECK: icmp uge
   // CHECK-NOT: select

vsk wrote:
> lebedev.ri wrote:
> > vsk wrote:
> > > I'm curious about what happens here with the new null-status-change 
> > > check. If array indices are unsigned, there is no need for a separate 
> > > null-status-change check: if the result of the GEP is indeed null, that 
> > > will be detected by the pointer wraparound check. We just need to check 
> > > that the base pointer itself isn't null.
> > > 
> > > That generalizes to addition of unsigned offsets to base pointers, I 
> > > think. So e.g. I wouldn't expect the 'preinc' function to contain a 
> > > null-status-change check either.
> > Ugh, i still hate those codegen-time optimizations :)
> > Not only do they result in a maze that is 'hard' to comprehend and argue 
> > about,
> > the middle-end isn't "forced" to know these folds so the other code stays 
> > unoptimized,
> > worse yet, unlike miscompile that will be detected, if the logic error is 
> > made here,
> > it will likely "only" result in 

[PATCH] D67058: [clang][CodeGen] Add alias for cpu_dispatch function with IFunc & Fix resolver linkage type

2019-09-06 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:3002
 false);
 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
 MangledName + ".resolver", ResolverType, GlobalDecl{},

zsrkmyn wrote:
> erichkeane wrote:
> > This Resolver should have the same linkage as below.
> Actually, I wanted to set linkage here at the first time, but failed. When 
> compiling code with cpu_specific but no cpu_dispatch, we cannot set it as 
> LinkOnceODR or WeakODR. E.g.:
> 
> ```
> $ cat specific_only.c
> __declspec(cpu_specific(pentium_iii))
> int foo(void) { return 0; }
> int usage() { return foo(); }
> 
> $ clang -fdeclspec specific_only.c
>  
> Global is external, but doesn't have external or weak linkage!
> 
> i32 ()* ()* @foo.resolver 
> 
> fatal error: error in backend: Broken module found, compilation aborted!   
> ```
> 
> This is found by lit test test/CodeGen/attr-cpuspecific.c, in which 
> 'SingleVersion()' doesn't have a cpu_dispatch declaration.
The crash message is complaining it isn't external/weak.  However, WeakODR 
should count, right?  Can you look into it a bit more to see what it thinks is 
broken?



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:3005
 /*ForVTable=*/false);
+auto Linkage = (FD->isCPUDispatchMultiVersion() || 
FD->isCPUSpecificMultiVersion())
+? llvm::Function::LinkOnceODRLinkage

zsrkmyn wrote:
> erichkeane wrote:
> > I think this can always just be LinkOnceODR.
> Changing this also changes linkage for attribute(target()), should I also 
> change test cases for them? (including test/CodeGen{,CXX}/attr-*.ll)
Yep!  Also, I think WeakODR is the right one.


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

https://reviews.llvm.org/D67058



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


[PATCH] D66951: [ASTImporter] Add comprehensive tests for ODR violation handling strategies

2019-09-06 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 6 inline comments as done.
martong added inline comments.



Comment at: clang/unittests/AST/ASTImporterODRStrategiesTest.cpp:36
+  static constexpr auto *Definition = "void X(int a) {}";
+  static constexpr auto *ConflictingDefinition = "void X(double a) {}";
+  BindableMatcher getPattern() {

balazske wrote:
> Probably for (non-member?) functions there is no possibility for conflicting 
> definition (for same prototype)? This can be the case if the function body is 
> different but this is not checked now. For functions no name conflict happens 
> because of overload, at least if C++ is used. I think the tests here with 
> functions are not needed or only for C language. (Do all these pass?)
We do check these only with lang C. That is handled with the `getLang()` 
function, each test use that language which is provided by the `getLang()` 
function.

`ConflictingDefinition` is needed, because we test cases like this (in 
`ImportConflictingDefAfterProto`):
```
void X(int); // TU1
void X(double a) {}; // TU2
```
This is handled differently by the distinct strategies. I.e. the conflicting 
definition is not imported when the strategy is `Conservative`. When it is 
`Liberal` then it is imported.



Comment at: clang/unittests/AST/ASTImporterODRStrategiesTest.cpp:128
+};
+
+struct ClassTemplateSpec {

balazske wrote:
> Is this better?
> ```
> struct VariableTemplate {
>   using DeclTy = VarTemplateDecl;
>   static constexpr auto *Prototype = "template  extern T X;";
>   static constexpr auto *ConflictingPrototype =
>   "template  extern float X;";
>   static constexpr auto *Definition =
>   R"(
>   template  T X;
>   template <> int X;
>   )";
>   static constexpr auto *ConflictingDefinition =
>   R"(
>   template  T X;
>   template <> float X;
>   )";
>   static constexpr auto *ConflictingProtoDef =
>   R"(
>   template  float X;
>   template <> float X;
>   )";
>   // There is no matcher for varTemplateDecl so use a work-around.
>   BindableMatcher getPattern() {
> return namedDecl(hasName("X"), unless(isImplicit()),
>  has(templateTypeParmDecl()));
>   }
> };
> ```
I did not want to get this from our fork, becuase `template <> int X;` 
seems to be a specialization of a variable template, and that confuses me.

Also, structural equivalency is completely wrong with variable templates, so 
they are here only for the sake of completeness, the tests which use them are 
all disabled.



Comment at: clang/unittests/AST/ASTImporterODRStrategiesTest.cpp:151
+};
+
+template 

balazske wrote:
> `FunctionTemplate` and `FunctionTemplateSpec` are missing?
Yes, because `FunctionTemplates` overload with each other. So they are imported 
always "liberally".

There is no point to liberally import conflicting 
`FunctionTemplateSpecializations`.
The only thing we can do in that case is to omit the conflicting declaration.
And this is true in case of `ClassTemplateSpecialization`s too.

Perhaps we should remove `struct ClassTemplateSpec` as well from here (?).
Because they are never going to be handled "liberally".

@shafik , what do you think about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66951



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


[PATCH] D66516: [clangd] Added highlighting to types dependant on templates.

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 219090.
ilya-biryukov added a comment.

- Replace UnderlyingTypeVisitor with a function
- Remove PrintTo()
- Also highlight references to typedefs
- reformat


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66516

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

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -231,7 +231,9 @@
 )cpp",
   R"cpp(
   namespace $Namespace[[a]] {
-struct $Class[[A]] {};
+struct $Class[[A]] {
+  $Primitive[[void]] $Method[[foo]]($Class[[A]]*);
+};
 typedef $Primitive[[char]] $Primitive[[C]];
   }
   typedef $Namespace[[a]]::$Class[[A]] $Class[[B]];
@@ -244,6 +246,12 @@
   $Enum[[CD]] $Function[[f]]($Class[[BB]]);
   typedef $Namespace[[a]]::$Primitive[[C]] $Primitive[[PC]];
   typedef $Primitive[[float]] $Primitive[[F]];
+  using $Primitive[[Member]] =
+$Primitive[[void]] (B::*)($Namespace[[a]]::$Class[[A]]*);
+  $Primitive[[void]] $Function[[foo]]($Primitive[[int]], $Class[[B]]);
+  typedef decltype($Function[[foo]]) $Primitive[[fooo]];
+  typedef $Class[[B]] (*$Class[[func]])();
+  typedef $Primitive[[int]] (*$Primitive[[func]])();
 )cpp",
   R"cpp(
   template
@@ -439,7 +447,7 @@
 $Macro[[assert]]($Variable[[x]] != $Function[[f]]());
   }
 )cpp",
-R"cpp(
+  R"cpp(
   struct $Class[[S]] {
 $Primitive[[float]] $Field[[Value]];
 $Class[[S]] *$Field[[Next]];
@@ -453,6 +461,20 @@
 // Highlights references to BindingDecls.
 $Variable[[B1]]++;
   }
+)cpp",
+  R"cpp(
+  template
+  class $Class[[A]] {
+using $TemplateParameter[[D]] = $TemplateParameter[[T]];
+using $TemplateParameter[[DD]] = $TemplateParameter[[T]] *;
+using $TemplateParameter[[DDD]] = $TemplateParameter[[T]] &;
+using $TemplateParameter[[B]] = $TemplateParameter[[T]]*[3];
+using $TemplateParameter[[BB]] = $TemplateParameter[[T]]&&;
+using $TemplateParameter[[Member]] =
+  $TemplateParameter[[BB]] (T::*)($Primitive[[int]]);
+using $TemplateParameter[[MemberT]] =
+  $TemplateParameter[[T]]*& (T::*)($Class[[A]]);
+  };
 )cpp"};
   for (const auto &TestCase : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -15,12 +15,33 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
+#include "clang/AST/TypeLoc.h"
 #include 
 
 namespace clang {
 namespace clangd {
 namespace {
 
+/// Return a type that should be used for highlighting a typedef to type \p T.
+/// Can be null, e.g. for dependent expression in decltype().
+const Type *getTypeForHighlighting(const Type *T) {
+  assert(T != nullptr);
+  while (true) {
+// Remove all syntax sugar, this handles 'auto', 'decltype', typedefs, etc.
+T = T->getUnqualifiedDesugaredType();
+QualType Pointee = T->getPointeeType();
+if (!Pointee.isNull())
+  T = Pointee.getTypePtr();
+else if (T->isArrayType())
+  T = T->getArrayElementTypeNoTypeQual();
+else if (auto *F = T->getAs())
+  T = F->getReturnType().getTypePtrOrNull();
+else // We reached the leaf type, return it to the user.
+  return T;
+  }
+}
+
 // Collects all semantic tokens in an ASTContext.
 class HighlightingTokenCollector
 : public RecursiveASTVisitor {
@@ -124,17 +145,17 @@
 
   bool VisitTypedefNameDecl(TypedefNameDecl *TD) {
 if (const auto *TSI = TD->getTypeSourceInfo())
-  addType(TD->getLocation(), TSI->getTypeLoc().getTypePtr());
+  addType(TD->getLocation(),
+  getTypeForHighlighting(TSI->getTypeLoc().getType().getTypePtr()));
 return true;
   }
 
-  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc &TL) {
-// TemplateTypeParmTypeLoc does not have a TagDecl in its type ptr.
-addToken(TL.getBeginLoc(), TL.getDecl());
+  bool VisitTypedefTypeLoc(TypedefTypeLoc TL) {
+addType(TL.getBeginLoc(), getTypeForHighlighting(TL.getTypePtr()));
 return true;
   }
 
-  bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc &TL) {
+  bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
 if (const TemplateDecl *TD =
 TL.getTypePtr()->getTemplateName().getAsTemplateDecl()

[PATCH] D65182: [analyzer] Add fix-it hint support.

2019-09-06 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:343
+  /// to produce a good fix-it hint for most path-sensitive warnings.
+  void addFixItHint(const FixItHint &F) {
+Fixits.push_back(F);

Are these fix-its notionally attached to the primary diagnostic itself?


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

https://reviews.llvm.org/D65182



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


[PATCH] D66516: [clangd] Added highlighting to types dependant on templates.

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov planned changes to this revision.
ilya-biryukov added a comment.

Now that I think about it more, maybe the simplest option is to not recurse 
into composite types at all
E.g. a typedef to a template parameter will be highlighted as a template 
parameter. A typedef to a pointer can be highligthed with a separate kind 
(other typedefs...)
I'll do these changes, this should simplify both our model and the 
implementation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66516



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


[PATCH] D67135: [clang-tidy] performance-inefficient-vector-operation: Support proto repeated field

2019-09-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

your patch doesn't have a full context, please upload the patch with full 
context (`=U9`) or use Arcanist 
.

> I'd think the check instead should be parametrized, so this patch should 
> become just extending the config.

The AST for protobuf is quite different compared with normal vector, so I don't 
think there will be an easy and simple way to do it in a config way.




Comment at: 
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp:86
 utils::options::serializeStringList(VectorLikeClasses));
+  Options.store(Opts, "EnableProto", static_cast(EnableProto));
 }

nit: remove `static_cast`?



Comment at: 
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp:227
+std::string MutableFieldName =
+("mutable_" + ProtoAddFieldCall->getMethodDecl()->getName().substr(4))
+.str();

nit: getName().drop_front(sizeof("add_")).



Comment at: 
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp:233
+  if (Matches.empty()) {
+// There is no method with name "mutable_xxx".
+return;

for repeated fields, there should be `add_foo`, `mutable_foo` methods in the 
proto generated code 
(https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#repeatednumeric).

So I think we can remove this check here.



Comment at: 
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp:249
+match.getNodeAs("maybe_reallocation");
+// Skip cases where "mutable_xxx" or "add_xxx" is called before the
+// loop.

the heuristic is limited, and will fail the cases like below:

```
MyProto proto;
set_proto_xxx_size(&proto);
for (int i = 0; i < n; ++i) {
   proto.add_xxx(i);
}
```

In the vector case, we do a more strict check, maybe we do the same way as well 
(but it will make the check fail to spot some cases)...


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

https://reviews.llvm.org/D67135



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


[PATCH] D67265: [clang-tidy] Magic number checker shouldn't warn on user defined string literals

2019-09-06 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp:125
+// std::string s = "Hello World"s;
+if (const UserDefinedLiteral *UDL = Parent.get())
+  if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)

You could use const auto *, because type is spelled in same statement.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D67265



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


r371205 - libclang depends on ClangDriverOptions since r352803

2019-09-06 Thread Nico Weber via cfe-commits
Author: nico
Date: Fri Sep  6 06:57:12 2019
New Revision: 371205

URL: http://llvm.org/viewvc/llvm-project?rev=371205&view=rev
Log:
libclang depends on ClangDriverOptions since r352803

Without this, the build would sometimes fail with

In file included from clang/tools/libclang/CIndexer.cpp:17:
In file included from clang/include/clang/Driver/Driver.h:15:
clang/include/clang/Driver/Options.h:44:10: fatal error:
'clang/Driver/Options.inc' file not found
#include "clang/Driver/Options.inc"
 ^

if Options.inc wasn't generated before libclang was built
by coincidence.

(In the GN build, this works because lib/Driver there declares
the dep on tablegen as a public_dep since the generated file
is part of Driver's public interface, and then things work out
automatically without every client of Driver having to be careful.)

Modified:
cfe/trunk/tools/libclang/CMakeLists.txt

Modified: cfe/trunk/tools/libclang/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CMakeLists.txt?rev=371205&r1=371204&r2=371205&view=diff
==
--- cfe/trunk/tools/libclang/CMakeLists.txt (original)
+++ cfe/trunk/tools/libclang/CMakeLists.txt Fri Sep  6 06:57:12 2019
@@ -97,7 +97,10 @@ endif()
 add_clang_library(libclang ${ENABLE_SHARED} ${ENABLE_STATIC} 
INSTALL_WITH_TOOLCHAIN
   OUTPUT_NAME ${output_name}
   ${SOURCES}
-  DEPENDS clang-resource-headers
+
+  DEPENDS
+  ClangDriverOptions
+  clang-resource-headers
 
   LINK_LIBS
   ${LIBS}


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


[PATCH] D64736: [clang-tidy] New bugprone-infinite-loop check for detecting obvious infinite loops

2019-09-06 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added a comment.

Thanks for following up!




Comment at: clang-tidy/bugprone/InfiniteLoopCheck.cpp:53
+
+/// \brief Return whether `Var` has a pointer of reference in `S`.
+static bool hasPtrOrReferenceInStmt(const Stmt *S, const VarDecl *Var) {

Please delete "\brief" (everywhere in the patch) -- it is the default for the 
first sentence.

Also s/pointer of reference/pointer or reference/



Comment at: docs/clang-tidy/checks/bugprone-infinite-loop.rst:18
+- It is a local variable.
+- It has no reference or pointer aliases
+- It is not a structure or class member.

Please add a period at the end.



Comment at: test/clang-tidy/bugprone-infinite-loop.cpp:152
+  int *p = &i;
+}
+

I'd prefer you to add these tests back and add a short comment that this code 
triggers false negatives that are difficult to solve without CFG-based analysis.


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

https://reviews.llvm.org/D64736



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


[PATCH] D64672: [X86] Prevent passing vectors of __int128 as in llvm IR

2019-09-06 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

@craig.topper Wasn't this committed at rL371169 
 ?


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

https://reviews.llvm.org/D64672



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


[PATCH] D67265: [clang-tidy] Magic number checker shouldn't warn on user defined string literals

2019-09-06 Thread Tibor Brunner via Phabricator via cfe-commits
bruntib updated this revision to Diff 219097.
bruntib added a comment.

Usually I'm not a big fan of `auto`, but in this case it makes sense not to 
duplicate the type name in the same expression. I'll use this rule of thumb in 
the future, thanks :)


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D67265

Files:
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp


Index: 
clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
@@ -0,0 +1,16 @@
+// RUN: %check_clang_tidy -std=c++14-or-later %s readability-magic-numbers %t 
--
+
+namespace std {
+  class string {};
+  using size_t = decltype(sizeof(int));
+  string operator ""s(const char *, std::size_t);
+  int operator "" s(unsigned long long);
+}
+
+void UserDefinedLiteral() {
+  using std::operator ""s;
+  "Hello World"s;
+  const int i = 3600s;
+  int j = 3600s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; 
consider replacing it with a named constant [readability-magic-numbers]
+}
Index: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
@@ -112,10 +112,21 @@
   return llvm::any_of(
   Result.Context->getParents(ExprResult),
   [&Result](const DynTypedNode &Parent) {
-return isUsedToInitializeAConstant(Result, Parent) ||
-   // Ignore this instance, because this match reports the location
-   // where the template is defined, not where it is instantiated.
-   Parent.get();
+if (isUsedToInitializeAConstant(Result, Parent))
+  return true;
+
+// Ignore this instance, because this match reports the location
+// where the template is defined, not where it is instantiated.
+if (Parent.get())
+  return true;
+
+// Don't warn on string user defined literals:
+// std::string s = "Hello World"s;
+if (const auto *UDL = Parent.get())
+  if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)
+return true;
+
+return false;
   });
 }
 


Index: clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/readability-magic-numbers-userliteral.cpp
@@ -0,0 +1,16 @@
+// RUN: %check_clang_tidy -std=c++14-or-later %s readability-magic-numbers %t --
+
+namespace std {
+  class string {};
+  using size_t = decltype(sizeof(int));
+  string operator ""s(const char *, std::size_t);
+  int operator "" s(unsigned long long);
+}
+
+void UserDefinedLiteral() {
+  using std::operator ""s;
+  "Hello World"s;
+  const int i = 3600s;
+  int j = 3600s;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+}
Index: clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
@@ -112,10 +112,21 @@
   return llvm::any_of(
   Result.Context->getParents(ExprResult),
   [&Result](const DynTypedNode &Parent) {
-return isUsedToInitializeAConstant(Result, Parent) ||
-   // Ignore this instance, because this match reports the location
-   // where the template is defined, not where it is instantiated.
-   Parent.get();
+if (isUsedToInitializeAConstant(Result, Parent))
+  return true;
+
+// Ignore this instance, because this match reports the location
+// where the template is defined, not where it is instantiated.
+if (Parent.get())
+  return true;
+
+// Don't warn on string user defined literals:
+// std::string s = "Hello World"s;
+if (const auto *UDL = Parent.get())
+  if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)
+return true;
+
+return false;
   });
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D67274: [clangd] Improve output of semantic highlighting tests in case of failures

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: hokein.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Instead of matching lists of highlightings, we annotate input code with
resulting highlightings and diff it against the expected annotated input.

In case of failures, this produces much nicer output in form of text-based
diffs.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D67274

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

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -10,9 +10,14 @@
 #include "ClangdServer.h"
 #include "Protocol.h"
 #include "SemanticHighlighting.h"
+#include "SourceCode.h"
 #include "TestFS.h"
 #include "TestTU.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
 #include "gmock/gmock.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -59,6 +64,36 @@
   return ExpectedTokens;
 }
 
+/// Annotates the input code with provided semantic highlightings. Results look
+/// something like:
+///   class $Class[[X]] {
+/// $Primitive[[int]] $Field[[a]] = 0;
+///   };
+std::string annotate(llvm::StringRef Input,
+ llvm::ArrayRef Tokens) {
+  assert(std::is_sorted(
+  Tokens.begin(), Tokens.end(),
+  [](const HighlightingToken &L, const HighlightingToken &R) {
+return L.R.start < R.R.start;
+  }));
+
+  std::string Result;
+  unsigned NextChar = 0;
+  for (auto &T : Tokens) {
+unsigned StartOffset = llvm::cantFail(positionToOffset(Input, T.R.start));
+unsigned EndOffset = llvm::cantFail(positionToOffset(Input, T.R.end));
+assert(StartOffset <= EndOffset);
+assert(NextChar <= StartOffset);
+
+Result += Input.substr(NextChar, StartOffset - NextChar);
+Result += llvm::formatv("${0}[[{1}]]", T.Kind,
+Input.substr(StartOffset, EndOffset - StartOffset));
+NextChar = EndOffset;
+  }
+  Result += Input.substr(NextChar);
+  return Result;
+}
+
 void checkHighlightings(llvm::StringRef Code,
 std::vector>
@@ -68,8 +103,8 @@
   for (auto File : AdditionalFiles)
 TU.AdditionalFiles.insert({File.first, File.second});
   auto AST = TU.build();
-  std::vector ActualTokens = getSemanticHighlightings(AST);
-  EXPECT_THAT(ActualTokens, getExpectedTokens(Test)) << Code;
+
+  EXPECT_EQ(Code, annotate(Test.code(), getSemanticHighlightings(AST)));
 }
 
 // Any annotations in OldCode and NewCode are converted into their corresponding
Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -18,6 +18,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_SEMANTICHIGHLIGHTING_H
 
 #include "Protocol.h"
+#include "llvm/Support/raw_ostream.h"
 
 namespace clang {
 namespace clangd {
@@ -42,6 +43,7 @@
 
   NumKinds,
 };
+llvm::raw_ostream& operator<<(llvm::raw_ostream &OS, HighlightingKind K);
 
 // Contains all information needed for the highlighting a token.
 struct HighlightingToken {
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -351,6 +351,43 @@
 }
 } // namespace
 
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, HighlightingKind K) {
+  switch (K) {
+  case HighlightingKind::Variable:
+return OS << "Variable";
+  case HighlightingKind::LocalVariable:
+return OS << "LocalVariable";
+  case HighlightingKind::Parameter:
+return OS << "Parameter";
+  case HighlightingKind::Function:
+return OS << "Function";
+  case HighlightingKind::Method:
+return OS << "Method";
+  case HighlightingKind::StaticMethod:
+return OS << "StaticMethod";
+  case HighlightingKind::Field:
+return OS << "Field";
+  case HighlightingKind::StaticField:
+return OS << "StaticField";
+  case HighlightingKind::Class:
+return OS << "Class";
+  case HighlightingKind::Enum:
+return OS << "Enum";
+  case HighlightingKind::EnumConstant:
+return OS << "EnumConstant";
+  case HighlightingKind::Namespace:
+return OS << "Namespace";
+  case HighlightingKind::TemplateParameter:
+return OS << "TemplateParameter";
+  case HighlightingKind::Primitive:
+return OS << "Primitive";
+  case HighlightingKind::Macro:
+return OS << "Macro";
+  case HighlightingKind::NumKinds:
+llvm_unreachable("NumKinds is not a valid Highlighting

r371206 - [NFC][CodeGen][UBSan] EmitCheckedInBoundsGEP(): add some comments to pointer-overflow check

2019-09-06 Thread Roman Lebedev via cfe-commits
Author: lebedevri
Date: Fri Sep  6 07:18:49 2019
New Revision: 371206

URL: http://llvm.org/viewvc/llvm-project?rev=371206&view=rev
Log:
[NFC][CodeGen][UBSan] EmitCheckedInBoundsGEP(): add some comments to 
pointer-overflow check

It's rather eye-twiching, some comments may help here..

This was originally part of https://reviews.llvm.org/D67122

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

Modified: cfe/trunk/lib/CodeGen/CGExprScalar.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprScalar.cpp?rev=371206&r1=371205&r2=371206&view=diff
==
--- cfe/trunk/lib/CodeGen/CGExprScalar.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprScalar.cpp Fri Sep  6 07:18:49 2019
@@ -4643,19 +4643,29 @@ Value *CodeGenFunction::EmitCheckedInBou
   llvm::Value *ValidGEP;
   auto *NoOffsetOverflow = Builder.CreateNot(OffsetOverflows);
   if (SignedIndices) {
+// GEP is computed as `unsigned base + signed offset`, therefore:
+// * If offset was positive, then the computed pointer can not be
+//   [unsigned] less than the base pointer, unless it overflowed.
+// * If offset was negative, then the computed pointer can not be
+//   [unsigned] greater than the bas pointere, unless it overflowed.
 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
 auto *PosOrZeroOffset = Builder.CreateICmpSGE(TotalOffset, Zero);
 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
-ValidGEP = Builder.CreateAnd(
-Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid),
-NoOffsetOverflow);
-  } else if (!SignedIndices && !IsSubtraction) {
-auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
-ValidGEP = Builder.CreateAnd(PosOrZeroValid, NoOffsetOverflow);
+ValidGEP = Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
+  } else if (!IsSubtraction) {
+// GEP is computed as `unsigned base + unsigned offset`,  therefore the
+// computed pointer can not be [unsigned] less than base pointer,
+// unless there was an overflow.
+// Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
+ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
   } else {
-auto *NegOrZeroValid = Builder.CreateICmpULE(ComputedGEP, IntPtr);
-ValidGEP = Builder.CreateAnd(NegOrZeroValid, NoOffsetOverflow);
+// GEP is computed as `unsigned base - unsigned offset`, therefore the
+// computed pointer can not be [unsigned] greater than base pointer,
+// unless there was an overflow.
+// Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
+ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
   }
+  ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
 
   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.


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


r371207 - [NFC][CodeGen][UBSan] EmitCheckedInBoundsGEP(): refactor EmitGEPOffsetInBytes() helper

2019-09-06 Thread Roman Lebedev via cfe-commits
Author: lebedevri
Date: Fri Sep  6 07:18:57 2019
New Revision: 371207

URL: http://llvm.org/viewvc/llvm-project?rev=371207&view=rev
Log:
[NFC][CodeGen][UBSan] EmitCheckedInBoundsGEP(): refactor EmitGEPOffsetInBytes() 
helper

It shouldn't really be inlined into the EmitCheckedInBoundsGEP().
Refactoring it beforehand will make follow-up changes more obvious.

This was originally part of https://reviews.llvm.org/D67122

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

Modified: cfe/trunk/lib/CodeGen/CGExprScalar.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprScalar.cpp?rev=371207&r1=371206&r2=371207&view=diff
==
--- cfe/trunk/lib/CodeGen/CGExprScalar.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprScalar.cpp Fri Sep  6 07:18:57 2019
@@ -4533,31 +4533,24 @@ LValue CodeGenFunction::EmitCompoundAssi
   llvm_unreachable("Unhandled compound assignment operator");
 }
 
-Value *CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr,
-   ArrayRef IdxList,
-   bool SignedIndices,
-   bool IsSubtraction,
-   SourceLocation Loc,
-   const Twine &Name) {
-  Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
-
-  // If the pointer overflow sanitizer isn't enabled, do nothing.
-  if (!SanOpts.has(SanitizerKind::PointerOverflow))
-return GEPVal;
-
-  // If the GEP has already been reduced to a constant, leave it be.
-  if (isa(GEPVal))
-return GEPVal;
-
-  // Only check for overflows in the default address space.
-  if (GEPVal->getType()->getPointerAddressSpace())
-return GEPVal;
+struct GEPOffsetAndOverflow {
+  // The total (signed) byte offset for the GEP.
+  llvm::Value *TotalOffset;
+  // The offset overflow flag - true if the total offset overflows.
+  llvm::Value *OffsetOverflows;
+};
 
+/// Evaluate given GEPVal, which must be an inbounds GEP,
+/// and compute the total offset it applies from it's base pointer BasePtr.
+/// Returns offset in bytes and a boolean flag whether an overflow happened
+/// during evaluation.
+static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
+ llvm::LLVMContext &VMContext,
+ CodeGenModule &CGM,
+ CGBuilderTy Builder) {
   auto *GEP = cast(GEPVal);
   assert(GEP->isInBounds() && "Expected inbounds GEP");
 
-  SanitizerScope SanScope(this);
-  auto &VMContext = getLLVMContext();
   const auto &DL = CGM.getDataLayout();
   auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
 
@@ -4627,21 +4620,54 @@ Value *CodeGenFunction::EmitCheckedInBou
   TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
   }
 
+  return {TotalOffset, OffsetOverflows};
+}
+
+Value *
+CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef IdxList,
+bool SignedIndices, bool IsSubtraction,
+SourceLocation Loc, const Twine &Name) 
{
+  Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
+
+  // If the pointer overflow sanitizer isn't enabled, do nothing.
+  if (!SanOpts.has(SanitizerKind::PointerOverflow))
+return GEPVal;
+
+  // If the GEP has already been reduced to a constant, leave it be.
+  if (isa(GEPVal))
+return GEPVal;
+
+  // Only check for overflows in the default address space.
+  if (GEPVal->getType()->getPointerAddressSpace())
+return GEPVal;
+
+  SanitizerScope SanScope(this);
+
+  GEPOffsetAndOverflow EvaluatedGEP =
+  EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
+
+  auto *GEP = cast(GEPVal);
+
+  const auto &DL = CGM.getDataLayout();
+  auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
+
+  auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
+
   // Common case: if the total offset is zero, don't emit a check.
-  if (TotalOffset == Zero)
+  if (EvaluatedGEP.TotalOffset == Zero)
 return GEPVal;
 
   // Now that we've computed the total offset, add it to the base pointer (with
   // wrapping semantics).
   auto *IntPtr = Builder.CreatePtrToInt(GEP->getPointerOperand(), IntPtrTy);
-  auto *ComputedGEP = Builder.CreateAdd(IntPtr, TotalOffset);
+  auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
 
   // The GEP is valid if:
   // 1) The total offset doesn't overflow, and
   // 2) The sign of the difference between the computed address and the base
   // pointer matches the sign of the total offset.
   llvm::Value *ValidGEP;
-  auto *NoOffsetOverflow = Builder.CreateNot(OffsetOverflows);
+  auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
   if (SignedIndices) {
 // GEP is c

r371208 - [NFC][CodeGen][UBSan] EmitCheckedInBoundsGEP(): pass a vector to EmitCheck()

2019-09-06 Thread Roman Lebedev via cfe-commits
Author: lebedevri
Date: Fri Sep  6 07:19:04 2019
New Revision: 371208

URL: http://llvm.org/viewvc/llvm-project?rev=371208&view=rev
Log:
[NFC][CodeGen][UBSan] EmitCheckedInBoundsGEP(): pass a vector to EmitCheck()

Will be easier to add a new 'check' in a follow-up.

This was originally part of https://reviews.llvm.org/D67122

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

Modified: cfe/trunk/lib/CodeGen/CGExprScalar.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprScalar.cpp?rev=371208&r1=371207&r2=371208&view=diff
==
--- cfe/trunk/lib/CodeGen/CGExprScalar.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprScalar.cpp Fri Sep  6 07:19:04 2019
@@ -4662,6 +4662,8 @@ CodeGenFunction::EmitCheckedInBoundsGEP(
   auto *IntPtr = Builder.CreatePtrToInt(GEP->getPointerOperand(), IntPtrTy);
   auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
 
+  llvm::SmallVector, 1> Checks;
+
   // The GEP is valid if:
   // 1) The total offset doesn't overflow, and
   // 2) The sign of the difference between the computed address and the base
@@ -4693,12 +4695,14 @@ CodeGenFunction::EmitCheckedInBoundsGEP(
 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
   }
   ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
+  Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
+
+  assert(!Checks.empty() && "Should have produced some checks.");
 
   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
   llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
-  EmitCheck(std::make_pair(ValidGEP, SanitizerKind::PointerOverflow),
-SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
+  EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, 
DynamicArgs);
 
   return GEPVal;
 }


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


[PATCH] D66516: [clangd] Added highlighting to types dependant on templates.

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 219100.
ilya-biryukov added a comment.

- Only highlight typedefs to non-composite types, simplifies everything


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66516

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


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -266,7 +266,9 @@
 )cpp",
   R"cpp(
   namespace $Namespace[[a]] {
-struct $Class[[A]] {};
+struct $Class[[A]] {
+  $Primitive[[void]] $Method[[foo]]($Class[[A]]*);
+};
 typedef $Primitive[[char]] $Primitive[[C]];
   }
   typedef $Namespace[[a]]::$Class[[A]] $Class[[B]];
@@ -474,7 +476,7 @@
 $Macro[[assert]]($Variable[[x]] != $Function[[f]]());
   }
 )cpp",
-R"cpp(
+  R"cpp(
   struct $Class[[S]] {
 $Primitive[[float]] $Field[[Value]];
 $Class[[S]] *$Field[[Next]];
@@ -488,6 +490,21 @@
 // Highlights references to BindingDecls.
 $Variable[[B1]]++;
   }
+)cpp",
+  R"cpp(
+  template
+  class $Class[[A]] {
+using $TemplateParameter[[TemplateParam1]] = $TemplateParameter[[T]];
+typedef $TemplateParameter[[T]] $TemplateParameter[[TemplateParam2]];
+using $Primitive[[IntType]] = $Primitive[[int]];
+
+// These typedefs are not yet highlighted, their types are complicated.
+using Pointer = $TemplateParameter[[T]] *;
+using LVReference = $TemplateParameter[[T]] &;
+using RVReference = $TemplateParameter[[T]]&&;
+using Array = $TemplateParameter[[T]]*[3];
+using MemberPointer = $Primitive[[int]] (A::*)($Primitive[[int]]);
+  };
 )cpp"};
   for (const auto &TestCase : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -15,6 +15,8 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
+#include "clang/AST/TypeLoc.h"
 #include 
 
 namespace clang {
@@ -124,17 +126,16 @@
 
   bool VisitTypedefNameDecl(TypedefNameDecl *TD) {
 if (const auto *TSI = TD->getTypeSourceInfo())
-  addType(TD->getLocation(), TSI->getTypeLoc().getTypePtr());
+  addType(TD->getLocation(), TSI->getTypeLoc().getType().getTypePtr());
 return true;
   }
 
-  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc &TL) {
-// TemplateTypeParmTypeLoc does not have a TagDecl in its type ptr.
-addToken(TL.getBeginLoc(), TL.getDecl());
+  bool VisitTypedefTypeLoc(TypedefTypeLoc TL) {
+addType(TL.getBeginLoc(), TL.getTypePtr());
 return true;
   }
 
-  bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc &TL) {
+  bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
 if (const TemplateDecl *TD =
 TL.getTypePtr()->getTemplateName().getAsTemplateDecl())
   addToken(TL.getBeginLoc(), TD);
@@ -187,6 +188,9 @@
 if (TP->isBuiltinType())
   // Builtins must be special cased as they do not have a TagDecl.
   addToken(Loc, HighlightingKind::Primitive);
+if (const TemplateTypeParmType *TD = dyn_cast(TP))
+  // TemplateTypeParmType also do not have a TagDecl.
+  addToken(Loc, TD->getDecl());
 if (const TagDecl *TD = TP->getAsTagDecl())
   addToken(Loc, TD);
   }


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -266,7 +266,9 @@
 )cpp",
   R"cpp(
   namespace $Namespace[[a]] {
-struct $Class[[A]] {};
+struct $Class[[A]] {
+  $Primitive[[void]] $Method[[foo]]($Class[[A]]*);
+};
 typedef $Primitive[[char]] $Primitive[[C]];
   }
   typedef $Namespace[[a]]::$Class[[A]] $Class[[B]];
@@ -474,7 +476,7 @@
 $Macro[[assert]]($Variable[[x]] != $Function[[f]]());
   }
 )cpp",
-R"cpp(
+  R"cpp(
   struct $Class[[S]] {
 $Primitive[[float]] $Field[[Value]];
 $Class[[S]] *$Field[[Next]];
@@ -488,6 +490,21 @@
 // Highlights references to BindingDecls.
 $Variable[[B1]]++;
   }
+)cpp",
+  R"cpp(
+  template
+  class $Class[[A]] {
+using $TemplateParameter[[TemplateParam1]] =

[PATCH] D66516: [clangd] Highlight typedefs to template parameters as template parameters

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I'll send a separate change to fallback to a new highlighting type if the 
underlying type of a typedef is complicated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66516



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


[PATCH] D66951: [ASTImporter] Add comprehensive tests for ODR violation handling strategies

2019-09-06 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

OK
Probably the `ClassTemplateSpec` can not be handled in liberal way because the 
AST data structure for template specializations do not allow multiple instances 
with same argument values?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66951



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


[PATCH] D67277: [clangd] Replace HighlightingKind::NumKinds with LastKind. NFC

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: hokein.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

The latter simplifies the client code by avoiding the need to handle it
as a separate case statement.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D67277

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h


Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -41,7 +41,7 @@
   Primitive,
   Macro,
 
-  NumKinds,
+  LastKind = Macro
 };
 llvm::raw_ostream& operator<<(llvm::raw_ostream &OS, HighlightingKind K);
 
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -387,9 +387,8 @@
 return OS << "Primitive";
   case HighlightingKind::Macro:
 return OS << "Macro";
-  case HighlightingKind::NumKinds:
-llvm_unreachable("NumKinds is not a valid HighlightingKind");
   }
+  llvm_unreachable("invalid HighlightingKind");
 }
 
 std::vector
@@ -515,8 +514,6 @@
 return "storage.type.primitive.cpp";
   case HighlightingKind::Macro:
 return "entity.name.function.preprocessor.cpp";
-  case HighlightingKind::NumKinds:
-llvm_unreachable("must not pass NumKinds to the function");
   }
   llvm_unreachable("unhandled HighlightingKind");
 }
Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -87,7 +87,7 @@
 std::vector> buildHighlightScopeLookupTable() {
   std::vector> LookupTable;
   // HighlightingKind is using as the index.
-  for (int KindValue = 0; KindValue < (int)HighlightingKind::NumKinds;
+  for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
++KindValue)
 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
   return LookupTable;


Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -41,7 +41,7 @@
   Primitive,
   Macro,
 
-  NumKinds,
+  LastKind = Macro
 };
 llvm::raw_ostream& operator<<(llvm::raw_ostream &OS, HighlightingKind K);
 
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -387,9 +387,8 @@
 return OS << "Primitive";
   case HighlightingKind::Macro:
 return OS << "Macro";
-  case HighlightingKind::NumKinds:
-llvm_unreachable("NumKinds is not a valid HighlightingKind");
   }
+  llvm_unreachable("invalid HighlightingKind");
 }
 
 std::vector
@@ -515,8 +514,6 @@
 return "storage.type.primitive.cpp";
   case HighlightingKind::Macro:
 return "entity.name.function.preprocessor.cpp";
-  case HighlightingKind::NumKinds:
-llvm_unreachable("must not pass NumKinds to the function");
   }
   llvm_unreachable("unhandled HighlightingKind");
 }
Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -87,7 +87,7 @@
 std::vector> buildHighlightScopeLookupTable() {
   std::vector> LookupTable;
   // HighlightingKind is using as the index.
-  for (int KindValue = 0; KindValue < (int)HighlightingKind::NumKinds;
+  for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
++KindValue)
 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
   return LookupTable;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D67122: [UBSan][clang][compiler-rt] Applying non-zero offset to nullptr is undefined behaviour

2019-09-06 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 219103.
lebedev.ri marked 4 inline comments as done.
lebedev.ri added a comment.

Rebased over precommitted NFC changes, much nicer diff! :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67122

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UndefinedBehaviorSanitizer.rst
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/catch-nullptr-and-nonzero-offset-blacklist.c
  clang/test/CodeGen/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.c
  clang/test/CodeGen/catch-nullptr-and-nonzero-offset-when-nullptr-is-defined.c
  clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
  clang/test/CodeGen/catch-pointer-overflow-volatile.c
  clang/test/CodeGen/catch-pointer-overflow.c
  clang/test/CodeGen/ubsan-pointer-overflow.m
  clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
  compiler-rt/lib/ubsan/ubsan_checks.inc
  compiler-rt/lib/ubsan/ubsan_handlers.cpp
  compiler-rt/test/ubsan/TestCases/Pointer/index-overflow.cpp
  
compiler-rt/test/ubsan/TestCases/Pointer/nullptr-and-nonzero-offset-constants.cpp
  
compiler-rt/test/ubsan/TestCases/Pointer/nullptr-and-nonzero-offset-summary.cpp
  
compiler-rt/test/ubsan/TestCases/Pointer/nullptr-and-nonzero-offset-variable.cpp
  compiler-rt/test/ubsan/TestCases/Pointer/unsigned-index-expression.cpp
  compiler-rt/test/ubsan_minimal/TestCases/nullptr-and-nonzero-offset.c
  llvm/docs/ReleaseNotes.rst

Index: llvm/docs/ReleaseNotes.rst
===
--- llvm/docs/ReleaseNotes.rst
+++ llvm/docs/ReleaseNotes.rst
@@ -50,6 +50,20 @@
 
Makes programs 10x faster by doing Special New Thing.
 
+* As per :ref:`LLVM Language Reference Manual `,
+  ``getelementptr inbounds`` can not change the null status of a pointer,
+  meaning it can not produce non-null pointer given null base pointer, and
+  likewise given non-null base pointer it can not produce null pointer; if it
+  does, the result is a :ref:`poison value `.
+  Since `r369789 `_
+  (`D66608 `_ ``[InstCombine] icmp eq/ne (gep
+  inbounds P, Idx..), null -> icmp eq/ne P, null``) LLVM uses that for
+  transformations. If the original source violates these requirements this
+  may result in code being miscompiled. If you are using Clang front-end,
+  Undefined Behaviour Sanitizer ``-fsanitize=pointer-overflow`` check
+  will now catch such cases.
+
+
 Changes to the LLVM IR
 --
 
Index: compiler-rt/test/ubsan_minimal/TestCases/nullptr-and-nonzero-offset.c
===
--- /dev/null
+++ compiler-rt/test/ubsan_minimal/TestCases/nullptr-and-nonzero-offset.c
@@ -0,0 +1,23 @@
+// RUN: %clang -fsanitize=pointer-overflow %s -o %t && %run %t 2>&1 | FileCheck %s --implicit-check-not="pointer-overflow"
+
+#include 
+
+int main(int argc, char *argv[]) {
+  char *base, *result;
+
+  // CHECK-NOT: pointer-overflow
+
+  base = (char *)0;
+  result = base + 1;
+  // CHECK: pointer-overflow
+
+  // CHECK-NOT: pointer-overflow
+
+  base = (char *)1;
+  result = base - 1;
+  // CHECK: pointer-overflow
+
+  // CHECK-NOT: pointer-overflow
+
+  return 0;
+}
Index: compiler-rt/test/ubsan/TestCases/Pointer/unsigned-index-expression.cpp
===
--- compiler-rt/test/ubsan/TestCases/Pointer/unsigned-index-expression.cpp
+++ compiler-rt/test/ubsan/TestCases/Pointer/unsigned-index-expression.cpp
@@ -1,5 +1,5 @@
 // RUN: %clangxx -std=c++11 -fsanitize=pointer-overflow %s -o %t
-// RUN: %run %t 2>&1 | FileCheck %s
+// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not="error:"
 
 int main(int argc, char *argv[]) {
   char c;
@@ -12,7 +12,7 @@
   // CHECK: unsigned-index-expression.cpp:[[@LINE+1]]:16: runtime error: subtraction of unsigned offset from 0x{{.*}} overflowed to 0x{{.*}}
   char *q1 = p - neg_1;
 
-  // CHECK: unsigned-index-expression.cpp:[[@LINE+2]]:16: runtime error: pointer index expression with base 0x{{0*}} overflowed to 0x{{.*}}
+  // CHECK: unsigned-index-expression.cpp:[[@LINE+2]]:16: runtime error: applying non-zero offset {{.*}} to null pointer
   char *n = nullptr;
   char *q2 = n - 1ULL;
 
Index: compiler-rt/test/ubsan/TestCases/Pointer/nullptr-and-nonzero-offset-variable.cpp
===
--- /dev/null
+++ compiler-rt/test/ubsan/TestCases/Pointer/nullptr-and-nonzero-offset-variable.cpp
@@ -0,0 +1,52 @@
+// RUN: %clang -x c   -fsanitize=pointer-overflow -O0 %s -o %t && %run %t 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefix=CHECK-OK
+// RUN: %clang -x c   -fsanitize=pointer-overflow -O1 %s -o %t && %run %t 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefix=CHECK-OK
+// RUN: %clang -x c   -fsanitize=pointer-overflow -O2 %s -o %t && %run %t

Re: r371182 - Reland [LifetimeAnalysis] Support more STL idioms (template forward declaration and DependentNameType)

2019-09-06 Thread Yvan Roux via cfe-commits
Hi Matthias,

this commit broke AArch64 bots, logs are available here:

http://lab.llvm.org:8011/builders/clang-cmake-aarch64-quick/builds/19917/steps/ninja%20check%201/logs/stdio

Thanks,
Yvan

On Fri, 6 Sep 2019 at 10:54, Matthias Gehre via cfe-commits
 wrote:
>
> Author: mgehre
> Date: Fri Sep  6 01:56:30 2019
> New Revision: 371182
>
> URL: http://llvm.org/viewvc/llvm-project?rev=371182&view=rev
> Log:
> Reland [LifetimeAnalysis] Support more STL idioms (template forward 
> declaration and DependentNameType)
>
> Reland after https://reviews.llvm.org/D66806 fixed the false-positive 
> diagnostics.
>
> Summary:
> This fixes inference of gsl::Pointer on std::set::iterator with libstdc++ 
> (the typedef for iterator
> on the template is a DependentNameType - we can only put the gsl::Pointer 
> attribute
> on the underlaying record after instantiation)
>
> inference of gsl::Pointer on std::vector::iterator with libc++ (the class was 
> forward-declared,
> we added the gsl::Pointer on the canonical decl (the forward decl), and later 
> when the
> template was instantiated, there was no attribute on the definition so it was 
> not instantiated).
>
> and a duplicate gsl::Pointer on some class with libstdc++ (we first added an 
> attribute to
> a incomplete instantiation, and then another was copied from the template 
> definition
> when the instantiation was completed).
>
> We now add the attributes to all redeclarations to fix thos issues and make 
> their usage easier.
>
> Reviewers: gribozavr
>
> Subscribers: Szelethus, xazax.hun, cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D66179
>
> Added:
> cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp
> Modified:
> cfe/trunk/lib/Sema/SemaAttr.cpp
> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> cfe/trunk/lib/Sema/SemaInit.cpp
> cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
> cfe/trunk/test/SemaCXX/attr-gsl-owner-pointer-std.cpp
> cfe/trunk/test/SemaCXX/attr-gsl-owner-pointer.cpp
> cfe/trunk/unittests/Sema/CMakeLists.txt
>
> Modified: cfe/trunk/lib/Sema/SemaAttr.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=371182&r1=371181&r2=371182&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaAttr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri Sep  6 01:56:30 2019
> @@ -88,13 +88,11 @@ void Sema::AddMsStructLayoutForRecord(Re
>  template 
>  static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
>   CXXRecordDecl *Record) {
> -  CXXRecordDecl *Canonical = Record->getCanonicalDecl();
> -  if (Canonical->hasAttr() || Canonical->hasAttr())
> +  if (Record->hasAttr() || Record->hasAttr())
>  return;
>
> -  Canonical->addAttr(::new (Context) Attribute(SourceRange{}, Context,
> -   /*DerefType*/ nullptr,
> -   /*Spelling=*/0));
> +  for (Decl *Redecl : Record->redecls())
> +Redecl->addAttr(Attribute::CreateImplicit(Context, 
> /*DerefType=*/nullptr));
>  }
>
>  void Sema::inferGslPointerAttribute(NamedDecl *ND,
> @@ -189,8 +187,7 @@ void Sema::inferGslOwnerPointerAttribute
>
>// Handle classes that directly appear in std namespace.
>if (Record->isInStdNamespace()) {
> -CXXRecordDecl *Canonical = Record->getCanonicalDecl();
> -if (Canonical->hasAttr() || Canonical->hasAttr())
> +if (Record->hasAttr() || Record->hasAttr())
>return;
>
>  if (StdOwners.count(Record->getName()))
>
> Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=371182&r1=371181&r2=371182&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Fri Sep  6 01:56:30 2019
> @@ -4592,9 +4592,11 @@ static void handleLifetimeCategoryAttr(S
>}
>return;
>  }
> -D->addAttr(::new (S.Context)
> -   OwnerAttr(AL.getRange(), S.Context, DerefTypeLoc,
> - AL.getAttributeSpellingListIndex()));
> +for (Decl *Redecl : D->redecls()) {
> +  Redecl->addAttr(::new (S.Context)
> +  OwnerAttr(AL.getRange(), S.Context, DerefTypeLoc,
> +AL.getAttributeSpellingListIndex()));
> +}
>} else {
>  if (checkAttrMutualExclusion(S, D, AL))
>return;
> @@ -4609,9 +4611,11 @@ static void handleLifetimeCategoryAttr(S
>}
>return;
>  }
> -D->addAttr(::new (S.Context)
> -   PointerAttr(AL.getRange(), S.Context, DerefTypeLoc,
> -   AL.getAttributeSpellingListIndex()));
> +for (Decl *Redecl : D->redecls()) {
> +  Redecl->addAttr(::new (S.Context)

[PATCH] D67216: [cfi] Add flag to always generate call frame information

2019-09-06 Thread David Candler via Phabricator via cfe-commits
dcandler added a comment.
Herald added a subscriber: ychen.

I was actually torn myself on whether to put the flag in the g group or not, so 
I'm happy to rename it. As far as I could find, no compiler has an existing 
option to control this: instead armcc always includes a debug_frame section by 
default to follow Arm's Dwarf specification. Having it as an option seems more 
flexible than forcing a different behavior.




Comment at: clang/lib/Frontend/CompilerInvocation.cpp:956
  OPT_fno_unique_section_names, true);
+  Opts.AlwaysNeedCFI =
+  Args.hasFlag(OPT_falways_need_cfi, OPT_fno_always_need_cfi, false);

ostannard wrote:
> Is this option actually being read anywhere?
Not any more, since I moved the option directly into AsmPrinter. I'll make sure 
this (and the other line) doesn't get included in the next diff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67216



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


[PATCH] D67058: [clang][CodeGen] Add alias for cpu_dispatch function with IFunc & Fix resolver linkage type

2019-09-06 Thread Sr.Zhang via Phabricator via cfe-commits
zsrkmyn marked an inline comment as done.
zsrkmyn added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:3002
 false);
 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
 MangledName + ".resolver", ResolverType, GlobalDecl{},

erichkeane wrote:
> zsrkmyn wrote:
> > erichkeane wrote:
> > > This Resolver should have the same linkage as below.
> > Actually, I wanted to set linkage here at the first time, but failed. When 
> > compiling code with cpu_specific but no cpu_dispatch, we cannot set it as 
> > LinkOnceODR or WeakODR. E.g.:
> > 
> > ```
> > $ cat specific_only.c
> > __declspec(cpu_specific(pentium_iii))
> > int foo(void) { return 0; }
> > int usage() { return foo(); }
> > 
> > $ clang -fdeclspec specific_only.c  
> >
> > Global is external, but doesn't have external or weak linkage!  
> >   
> > i32 ()* ()* @foo.resolver   
> >   
> > fatal error: error in backend: Broken module found, compilation aborted!   
> > ```
> > 
> > This is found by lit test test/CodeGen/attr-cpuspecific.c, in which 
> > 'SingleVersion()' doesn't have a cpu_dispatch declaration.
> The crash message is complaining it isn't external/weak.  However, WeakODR 
> should count, right?  Can you look into it a bit more to see what it thinks 
> is broken?
No, actually I've tried it earlier with the example I mentioned in my last 
comment, but WeakODR still makes compiler complaining. I think it's 
`foo.resolver` that cannot be declared with as WeakODR/LinkOnceODR without 
definition. But I'm really not familiar with these rules.


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

https://reviews.llvm.org/D67058



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


[PATCH] D60748: Fix i386 struct and union parameter alignment

2019-09-06 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon requested changes to this revision.
RKSimon added a comment.
This revision now requires changes to proceed.

In D60748#1524443 , @wxiao3 wrote:

> Thanks for the information!
>  We have reverted the patch and will resubmit it when we have a complete fix.


@wxiao3 Have you investigated this yet?


Repository:
  rC Clang

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

https://reviews.llvm.org/D60748



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


[PATCH] D62445: [test] Fix plugin tests

2019-09-06 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

In D62445#1630518 , @NoQ wrote:

> I didn't make much progress so far, but i marked the test as `// UNSUPPORTED: 
> darwin` in rC368765 , so the buildbot is 
> now green starting with 
> http://green.lab.llvm.org/green/job/clang-stage2-cmake-RgSan/6519/.


I haven't had a chance to check this, but I suspect these plugin tests need 
LLVM_NO_DEAD_STRIP, since the failing build is RelWithDebInfo.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D62445



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


r371222 - [Diagnostics] Refactor code for -Wsizeof-pointer-div, catch more cases; also add -Wsizeof-array-div

2019-09-06 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Fri Sep  6 09:12:48 2019
New Revision: 371222

URL: http://llvm.org/viewvc/llvm-project?rev=371222&view=rev
Log:
[Diagnostics] Refactor code for -Wsizeof-pointer-div, catch more cases; also 
add -Wsizeof-array-div

Previously, -Wsizeof-pointer-div failed to catch:
const int *r;
sizeof(r) / sizeof(int);

Now fixed.
Also introduced -Wsizeof-array-div which catches bugs like:
sizeof(r) / sizeof(short);

(Array element type does not match type of sizeof operand).


Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/test/Sema/div-sizeof-ptr.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=371222&r1=371221&r2=371222&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Sep  6 09:12:48 
2019
@@ -3391,6 +3391,10 @@ def note_pointer_declared_here : Note<
 def warn_division_sizeof_ptr : Warning<
   "'%0' will return the size of the pointer, not the array itself">,
   InGroup>;
+def warn_division_sizeof_array : Warning<
+  "expresion will return the incorrect number of elements in the array; the 
array "
+  "element type is %0, not %1">,
+  InGroup>;
 
 def note_function_warning_silence : Note<
 "prefix with the address-of operator to silence this warning">;
@@ -8003,7 +8007,7 @@ def warn_array_index_precedes_bounds : W
 def warn_array_index_exceeds_bounds : Warning<
   "array index %0 is past the end of the array (which contains %1 "
   "element%s2)">, InGroup;
-def note_array_index_out_of_bounds : Note<
+def note_array_declared_here : Note<
   "array %0 declared here">;
 
 def warn_printf_insufficient_data_args : Warning<

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=371222&r1=371221&r2=371222&view=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Fri Sep  6 09:12:48 2019
@@ -13008,7 +13008,7 @@ void Sema::CheckArrayAccess(const Expr *
 
   if (ND)
 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
-PDiag(diag::note_array_index_out_of_bounds)
+PDiag(diag::note_array_declared_here)
 << ND->getDeclName());
 }
 

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=371222&r1=371221&r2=371222&view=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Fri Sep  6 09:12:48 2019
@@ -9135,7 +9135,7 @@ static void checkArithmeticNull(Sema &S,
   << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
 }
 
-static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
+static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
   SourceLocation Loc) {
   const auto *LUE = dyn_cast(LHS);
   const auto *RUE = dyn_cast(RHS);
@@ -9154,16 +9154,29 @@ static void DiagnoseDivisionSizeofPointe
   else
 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
 
-  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
-return;
-  if (LHSTy->getPointeeType().getCanonicalType() != RHSTy.getCanonicalType())
-return;
-
-  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
-  if (const auto *DRE = dyn_cast(LHSArg)) {
-if (const ValueDecl *LHSArgDecl = DRE->getDecl())
-  S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
-  << LHSArgDecl;
+  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
+if (LHSTy->getPointeeType().getCanonicalType().getUnqualifiedType() !=
+RHSTy.getCanonicalType().getUnqualifiedType())
+  return;
+
+S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << 
LHS->getSourceRange();
+if (const auto *DRE = dyn_cast(LHSArg)) {
+  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
+S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
+<< LHSArgDecl;
+}
+  } else if (isa(LHSTy) && !RHSTy->isArrayType()) {
+QualType ArrayElemTy = cast(LHSTy)->getElementType();
+if (isa(ArrayElemTy) ||
+ArrayElemTy.getCanonicalType().getUnqualifiedType() ==
+RHSTy.getCanonicalType().getUnqualifiedType())
+  return;
+S.Diag(Loc, diag::warn_division_sizeof_array) << ArrayElemTy << RHSTy;
+if (const auto *DRE = dyn_cast(LHSArg)) {
+  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
+S.Diag(LHSArgDecl->getLoca

r371223 - [NFC] Added new tests for r371222

2019-09-06 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Fri Sep  6 09:18:18 2019
New Revision: 371223

URL: http://llvm.org/viewvc/llvm-project?rev=371223&view=rev
Log:
[NFC] Added new tests for r371222

Added:
cfe/trunk/test/Sema/div-sizeof-array.cpp

Added: cfe/trunk/test/Sema/div-sizeof-array.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/div-sizeof-array.cpp?rev=371223&view=auto
==
--- cfe/trunk/test/Sema/div-sizeof-array.cpp (added)
+++ cfe/trunk/test/Sema/div-sizeof-array.cpp Fri Sep  6 09:18:18 2019
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 %s -verify -Wsizeof-array-div -fsyntax-only
+
+template 
+int f(Ty (&Array)[N]) {
+  return sizeof(Array) / sizeof(Ty); // Should not warn
+}
+
+typedef int int32;
+
+void test(void) {
+  int arr[12]; // expected-note 2 {{array 'arr' declared here}}
+  unsigned long long arr2[4]; // expected-note {{array 'arr2' declared here}}
+  int *p = &arr[0];
+  int a1 = sizeof(arr) / sizeof(*arr);
+  int a2 = sizeof arr / sizeof p;   // expected-warning {{expresion will 
return the incorrect number of elements in the array; the array element type is 
'int', not 'int *'}}
+  int a4 = sizeof arr2 / sizeof p;  // expected-warning {{expresion will 
return the incorrect number of elements in the array; the array element type is 
'unsigned long long', not 'int *'}}
+  int a5 = sizeof(arr) / sizeof(short); // expected-warning {{expresion will 
return the incorrect number of elements in the array; the array element type is 
'int', not 'short'}}
+  int a6 = sizeof(arr) / sizeof(int32);
+  const char arr3[2] = "A";
+  int a7 = sizeof(arr3) / sizeof(char);
+
+  int arr4[10][12];
+  int b1 = sizeof(arr4) / sizeof(arr2[12]);
+  int b2 = sizeof(arr4) / sizeof(int *);
+  int b3 = sizeof(arr4) / sizeof(short *);
+}


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


r371226 - [NFCI] Unbreak buildbots

2019-09-06 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Fri Sep  6 09:30:44 2019
New Revision: 371226

URL: http://llvm.org/viewvc/llvm-project?rev=371226&view=rev
Log:
[NFCI] Unbreak buildbots

Removed:
cfe/trunk/test/Sema/div-sizeof-array.cpp
Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=371226&r1=371225&r2=371226&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Sep  6 09:30:44 
2019
@@ -3391,10 +3391,6 @@ def note_pointer_declared_here : Note<
 def warn_division_sizeof_ptr : Warning<
   "'%0' will return the size of the pointer, not the array itself">,
   InGroup>;
-def warn_division_sizeof_array : Warning<
-  "expresion will return the incorrect number of elements in the array; the 
array "
-  "element type is %0, not %1">,
-  InGroup>;
 
 def note_function_warning_silence : Note<
 "prefix with the address-of operator to silence this warning">;

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=371226&r1=371225&r2=371226&view=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Fri Sep  6 09:30:44 2019
@@ -9154,29 +9154,17 @@ static void DiagnoseDivisionSizeofPointe
   else
 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
 
-  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
-if (LHSTy->getPointeeType().getCanonicalType().getUnqualifiedType() !=
-RHSTy.getCanonicalType().getUnqualifiedType())
-  return;
+  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
+return;
+  if (LHSTy->getPointeeType().getCanonicalType().getUnqualifiedType() !=
+  RHSTy.getCanonicalType().getUnqualifiedType())
+return;
 
-S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << 
LHS->getSourceRange();
-if (const auto *DRE = dyn_cast(LHSArg)) {
-  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
-S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
-<< LHSArgDecl;
-}
-  } else if (isa(LHSTy) && !RHSTy->isArrayType()) {
-QualType ArrayElemTy = cast(LHSTy)->getElementType();
-if (isa(ArrayElemTy) ||
-ArrayElemTy.getCanonicalType().getUnqualifiedType() ==
-RHSTy.getCanonicalType().getUnqualifiedType())
-  return;
-S.Diag(Loc, diag::warn_division_sizeof_array) << ArrayElemTy << RHSTy;
-if (const auto *DRE = dyn_cast(LHSArg)) {
-  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
-S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
-<< LHSArgDecl;
-}
+  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
+  if (const auto *DRE = dyn_cast(LHSArg)) {
+if (const ValueDecl *LHSArgDecl = DRE->getDecl())
+  S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
+  << LHSArgDecl;
   }
 }
 

Removed: cfe/trunk/test/Sema/div-sizeof-array.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/div-sizeof-array.cpp?rev=371225&view=auto
==
--- cfe/trunk/test/Sema/div-sizeof-array.cpp (original)
+++ cfe/trunk/test/Sema/div-sizeof-array.cpp (removed)
@@ -1,26 +0,0 @@
-// RUN: %clang_cc1 %s -verify -Wsizeof-array-div -fsyntax-only
-
-template 
-int f(Ty (&Array)[N]) {
-  return sizeof(Array) / sizeof(Ty); // Should not warn
-}
-
-typedef int int32;
-
-void test(void) {
-  int arr[12]; // expected-note 2 {{array 'arr' declared here}}
-  unsigned long long arr2[4]; // expected-note {{array 'arr2' declared here}}
-  int *p = &arr[0];
-  int a1 = sizeof(arr) / sizeof(*arr);
-  int a2 = sizeof arr / sizeof p;   // expected-warning {{expresion will 
return the incorrect number of elements in the array; the array element type is 
'int', not 'int *'}}
-  int a4 = sizeof arr2 / sizeof p;  // expected-warning {{expresion will 
return the incorrect number of elements in the array; the array element type is 
'unsigned long long', not 'int *'}}
-  int a5 = sizeof(arr) / sizeof(short); // expected-warning {{expresion will 
return the incorrect number of elements in the array; the array element type is 
'int', not 'short'}}
-  int a6 = sizeof(arr) / sizeof(int32);
-  const char arr3[2] = "A";
-  int a7 = sizeof(arr3) / sizeof(char);
-
-  int arr4[10][12];
-  int b1 = sizeof(arr4) / sizeof(arr2[12]);
-  int b2 = sizeof(arr4) / sizeof(int *);
-  int b3 = sizeof(arr4) / sizeof(short *);
-}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://l

[PATCH] D66951: [ASTImporter] Add comprehensive tests for ODR violation handling strategies

2019-09-06 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 3 inline comments as done.
martong added a comment.

In D66951#1660886 , @balazske wrote:

> OK
>  Probably the `ClassTemplateSpec` can not be handled in liberal way because 
> the AST data structure for template specializations do not allow multiple 
> instances with same argument values?


Yes exactly, that is the case. The implementation holds the specializations in 
a set, and the key within the set is a hash calculated from the arguments of 
the specialization.
All specializations are implemented like this, this includes 
variabletemplatespecializations too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66951



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


Re: [PATCH] D67200: Add -static-openmp driver option

2019-09-06 Thread Joerg Sonnenberger via cfe-commits
On Wed, Sep 04, 2019 at 11:28:34PM +, Pirama Arumuga Nainar via Phabricator 
via cfe-commits wrote:
> pirama created this revision.
> pirama added reviewers: Hahnfeld, danalbert, srhines, joerg.
> Herald added a subscriber: guansong.
> Herald added a reviewer: jdoerfert.
> Herald added a project: clang.
> 
> This option forces linking with the static OpenMP host runtime (similar
> to -static-libgcc and -static-libstdcxx).
> 
> Android's NDK will start the shared OpenMP runtime in addition to the static
> libomp.  In this scenario, the linker will prefer to use the shared library by
> default.  Add this option to enable linking with the static libomp.

Needs testing for the -static interaction?

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


[PATCH] D64672: [X86] Prevent passing vectors of __int128 as in llvm IR

2019-09-06 Thread Craig Topper via Phabricator via cfe-commits
craig.topper closed this revision.
craig.topper added a comment.

Committed in r371169, but I forgot the Differential Revision line


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

https://reviews.llvm.org/D64672



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


[PATCH] D67290: [clangd] Add a new highlighting kind for typedefs

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked an inline comment as done.
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:530
+  case HighlightingKind::Typedef:
+return "entity.name.type.typedef.cpp";
   case HighlightingKind::Namespace:

Not sure what the rules for the scope names are, happy to change if I'm doing 
it wrong


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67290



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


[PATCH] D67290: [clangd] Add a new highlighting kind for typedefs

2019-09-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: hokein.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.
ilya-biryukov added a parent revision: D66516: [clangd] Highlight typedefs to 
template parameters as template parameters.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:530
+  case HighlightingKind::Typedef:
+return "entity.name.type.typedef.cpp";
   case HighlightingKind::Namespace:

Not sure what the rules for the scope names are, happy to change if I'm doing 
it wrong


We still attempt to highlight them as underlying types, but fallback to
the generic 'typedef' highlighting kind if the underlying type is too
complicated.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D67290

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/test/semantic-highlighting.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -499,11 +499,16 @@
 using $Primitive[[IntType]] = $Primitive[[int]];
 
 // These typedefs are not yet highlighted, their types are complicated.
-using Pointer = $TemplateParameter[[T]] *;
-using LVReference = $TemplateParameter[[T]] &;
-using RVReference = $TemplateParameter[[T]]&&;
-using Array = $TemplateParameter[[T]]*[3];
-using MemberPointer = $Primitive[[int]] (A::*)($Primitive[[int]]);
+using $Typedef[[Pointer]] = $TemplateParameter[[T]] *;
+using $Typedef[[LVReference]] = $TemplateParameter[[T]] &;
+using $Typedef[[RVReference]] = $TemplateParameter[[T]]&&;
+using $Typedef[[Array]] = $TemplateParameter[[T]]*[3];
+using $Typedef[[MemberPointer]] = $Primitive[[int]] (A::*)($Primitive[[int]]);
+
+// Use various defined typedef in a function type.
+$Primitive[[void]] $Method[[func]](
+  $Typedef[[Pointer]], $Typedef[[LVReference]], $Typedef[[RVReference]],
+  $Typedef[[Array]], $Typedef[[MemberPointer]]);
   };
 )cpp"};
   for (const auto &TestCase : TestCases) {
Index: clang-tools-extra/clangd/test/semantic-highlighting.test
===
--- clang-tools-extra/clangd/test/semantic-highlighting.test
+++ clang-tools-extra/clangd/test/semantic-highlighting.test
@@ -38,6 +38,9 @@
 # CHECK-NEXT:"variable.other.enummember.cpp"
 # CHECK-NEXT:  ],
 # CHECK-NEXT:  [
+# CHECK-NEXT:"entity.name.type.typedef.cpp"
+# CHECK-NEXT:  ],
+# CHECK-NEXT:  [
 # CHECK-NEXT:"entity.name.namespace.cpp"
 # CHECK-NEXT:  ],
 # CHECK-NEXT:  [
@@ -58,7 +61,7 @@
 # CHECK-NEXT:"lines": [
 # CHECK-NEXT:  {
 # CHECK-NEXT:"line": 0,
-# CHECK-NEXT:"tokens": "AAADAA0EAAEAAA=="
+# CHECK-NEXT:"tokens": "AAADAA4EAAEAAA=="
 # CHECK-NEXT:  }
 # CHECK-NEXT:],
 # CHECK-NEXT:"textDocument": {
@@ -73,11 +76,11 @@
 # CHECK-NEXT:"lines": [
 # CHECK-NEXT:  {
 # CHECK-NEXT:"line": 0,
-# CHECK-NEXT:"tokens": "AAADAA0EAAEAAA=="
+# CHECK-NEXT:"tokens": "AAADAA4EAAEAAA=="
 # CHECK-NEXT:  }
 # CHECK-NEXT:  {
 # CHECK-NEXT:"line": 1,
-# CHECK-NEXT:"tokens": "AAADAA0EAAEAAA=="
+# CHECK-NEXT:"tokens": "AAADAA4EAAEAAA=="
 # CHECK-NEXT:  }
 # CHECK-NEXT:],
 # CHECK-NEXT:"textDocument": {
@@ -92,7 +95,7 @@
 # CHECK-NEXT:"lines": [
 # CHECK-NEXT:  {
 # CHECK-NEXT:"line": 1,
-# CHECK-NEXT:"tokens": "AAADAA0EAAEAAA=="
+# CHECK-NEXT:"tokens": "AAADAA4EAAEAAA=="
 # CHECK-NEXT:  }
 # CHECK-NEXT:   ],
 # CHECK-NEXT:"textDocument": {
Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -36,6 +36,7 @@
   Class,
   Enum,
   EnumConstant,
+  Typedef,
   Namespace,
   TemplateParameter,
   Primitive,
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
+#include "clang/Basic/SourceLocation.h"
 #include 
 
 

[PATCH] D67253: clang-misexpect: a standalone tool for verifying the use of __builtin_expect with PGO data

2019-09-06 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp:33
+using namespace clang::tooling;
+using namespace clang::misexpect;
+using Path = std::string;

The `using` statements here should match 
clang-tools-extra/clang-misexpect/ClangMisExpect.cpp.



Comment at: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp:62
+  ExecutorName.setInitialValue("all-TUs");
+  // ExecutorName.setInitialValue("standalone");
+

accidentally committed?



Comment at: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp:78-79
+
+  auto &OS = llvm::errs();
+  OS << "Starting execution ... \n";
+  auto ArgAdjuster = getStripPluginsAdjuster();

I recognize the shorthand, but it seems like it could be created earlier?



Comment at: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp:89
+continue;
+  }
+  AdjustedArgs.push_back(Args[I]);

unnecessary



Comment at: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp:116
+
+  llvm::errs() << "Execution complete\n";
+

use `OS`



Comment at: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp:121
+  [](llvm::StringRef Key, llvm::StringRef Value) {
+llvm::errs() << "" << Key.str() << "\n" << Value.str() << "\n";
+  });

Capture/use `OS`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67253



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


[PATCH] D67292: [clang-tidy] Fix bug in bugprone-use-after-move check

2019-09-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr.
Herald added a subscriber: xazax.hun.
Herald added a project: clang.

The bugprone-use-after-move check exhibits false positives for certain uses of
the C++17 if/switch init statements. These false positives are caused by a bug
in the ExprSequence calculations.

This revision adds tests for the false positives and fixes the corresponding
sequence calculation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D67292

Files:
  clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
  clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp


Index: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
@@ -1190,6 +1190,12 @@
   std::move(a2);
 }
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+if (A a2 = std::move(a1); a2) {
+  std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 if (A a2 = std::move(a1); A a3 = std::move(a2)) {
@@ -1199,6 +1205,13 @@
   while (A a = A()) {
 std::move(a);
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+switch (A a2 = std::move(a1); a2) {
+  case true:
+std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 switch (A a2 = a1; A a3 = std::move(a2)) {
Index: clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
===
--- clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
+++ clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
@@ -145,17 +145,24 @@
 return ForRange->getBody();
 } else if (const auto *TheIfStmt = dyn_cast(Parent)) {
   // If statement:
-  // - Sequence init statement before variable declaration.
+  // - Sequence init statement before variable declaration, if present;
+  //   before condition evaluation, otherwise.
   // - Sequence variable declaration (along with the expression used to
   //   initialize it) before the evaluation of the condition.
-  if (S == TheIfStmt->getInit())
-return TheIfStmt->getConditionVariableDeclStmt();
+  if (S == TheIfStmt->getInit()) {
+if (TheIfStmt->getConditionVariableDeclStmt() != nullptr)
+  return TheIfStmt->getConditionVariableDeclStmt();
+return TheIfStmt->getCond();
+  }
   if (S == TheIfStmt->getConditionVariableDeclStmt())
 return TheIfStmt->getCond();
 } else if (const auto *TheSwitchStmt = dyn_cast(Parent)) {
   // Ditto for switch statements.
-  if (S == TheSwitchStmt->getInit())
-return TheSwitchStmt->getConditionVariableDeclStmt();
+  if (S == TheSwitchStmt->getInit()) {
+if (TheSwitchStmt->getConditionVariableDeclStmt() != nullptr)
+  return TheSwitchStmt->getConditionVariableDeclStmt();
+return TheSwitchStmt->getCond();
+  }
   if (S == TheSwitchStmt->getConditionVariableDeclStmt())
 return TheSwitchStmt->getCond();
 } else if (const auto *TheWhileStmt = dyn_cast(Parent)) {


Index: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
@@ -1190,6 +1190,12 @@
   std::move(a2);
 }
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+if (A a2 = std::move(a1); a2) {
+  std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 if (A a2 = std::move(a1); A a3 = std::move(a2)) {
@@ -1199,6 +1205,13 @@
   while (A a = A()) {
 std::move(a);
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+switch (A a2 = std::move(a1); a2) {
+  case true:
+std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 switch (A a2 = a1; A a3 = std::move(a2)) {
Index: clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
===
--- clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
+++ clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
@@ -145,17 +145,24 @@
 return ForRange->getBody();
 } else if (const auto *TheIfStmt = dyn_cast(Parent)) {
   // If statement:
-  // - Sequence init statement before variable declaration.
+  // - Sequence init statement before variable declaration, if present;
+  //   before condition evaluation, otherwise.
   // - Sequence variable declaration (along with the expression used to
   //   initialize it) before the evaluation of the condition.
-  if (S == TheIfStmt->getInit())
-return TheIfStmt->getConditionVariableDeclStmt();
+  if (S == TheIfStmt->getInit()) {
+if (TheIfStmt->getConditionVariableDeclStmt() != nullptr)
+  retur

[PATCH] D67294: Register and parse a simplified version of '#pragma omp declare variant'

2019-09-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar created this revision.
andwar added a reviewer: ABataev.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

  This patch implements the basic parsing and semantic analysis of
  `#pragma omp declare variant`:
* registers '#pragma omp declare variant' alongside other OpenMP
pragmas
* parses the 'variant(variant-func-id)' clause and verifies that
'variant-func-id' corresponds to a previously declared function
* template-is as 'variant-func-id' is not supported
* '#pragma omp declare variant` is not allowed in front of template
declarations.
  
  Note that this patch will only parse a subset of the required clauses,
  e.g. 'variant(variant-func-id)'. Any remaining tokens before
  'tok::annot_pragma_openmp_end' are ignored.  As per OpenMP 5 spec, this
  form of '#pragma omp declare variant' is incomplete and invalid and will
  be rejected with an error once the implementation is complete. In the
  meantime, this reduced form is treated as valid.


Repository:
  rC Clang

https://reviews.llvm.org/D67294

Files:
  include/clang/Basic/Attr.td
  include/clang/Basic/DiagnosticParseKinds.td
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Basic/OpenMPKinds.def
  include/clang/Parse/Parser.h
  include/clang/Sema/Sema.h
  lib/Basic/OpenMPKinds.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/Parse/ParseOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  test/AST/dump.cpp
  test/OpenMP/declare_variant_ast_print.c
  test/OpenMP/declare_variant_messages.cpp

Index: test/OpenMP/declare_variant_messages.cpp
===
--- /dev/null
+++ test/OpenMP/declare_variant_messages.cpp
@@ -0,0 +1,84 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp -x c++ -std=c++11 -fms-extensions -Wno-pragma-pack %s
+
+// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp-simd -x c++ -std=c++11 -fms-extensions -Wno-pragma-pack %s
+
+// The dummy vector variant
+void vector_foo();
+
+//=
+// Basic errors
+//=
+// This is (and should be) perfectly fine for the parser, although semantically
+// not valid OpenMP 5.
+#pragma omp declare variant(vector_foo)
+void foo();
+
+// expected-error@+1 {{expected an OpenMP directive}}
+#pragma omp declare
+
+// expected-error@+2 {{'#pragma omp declare variant' can only be applied to functions}}
+#pragma omp declare variant(vector_foo)
+int a;
+// expected-error@+2 {{'#pragma omp declare variant' can only be applied to functions}}
+#pragma omp declare variant (vector_foo)
+#pragma omp threadprivate(a)
+int var;
+#pragma omp threadprivate(var)
+
+// expected-error@+3 {{expected an OpenMP directive}}
+// expected-error@+1 {{function declaration is expected after 'declare variant' directive}}
+#pragma omp declare variant
+#pragma omp declare
+
+// expected-error@+1 {{single declaration is expected after 'declare variant' directive}}
+#pragma omp declare variant(vector_foo)
+int b, c;
+
+//=
+// Syntax/semantic error: everything excluding linear/aligned/uniform
+//=
+// expected-error@+1 {{expected an OpenMP directive}}
+#pragma omp variant
+// expected-error@+1 {{expected '(' after '#pragma omp declare variant'}}
+#pragma omp declare variant
+// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare variant' are ignored}}
+// expected-error@+1 {{expected '(' after '#pragma omp declare variant'}}
+#pragma omp declare variant )
+// expected-error@+1 {{expected unqualified-id representing 'vector-variant-id'}}
+#pragma omp declare variant()
+// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare variant' are ignored}}
+// expected-error@+1 {{no declaration for 'undeclared_func', only declared functions can be used as }}
+#pragma omp declare variant(undeclared_func)
+// expected-error@+2 {{expected ')'}}
+// expected-note@+1 {{to match this '('}}
+#pragma omp declare variant(vector_foo
+void foo();
+
+//=
+// Templates
+//=
+// expected-error@+1 {{'#pragma omp declare variant' can only be used to decorate instantiated templates}}
+#pragma omp declare variant(vector_foo)
+template 
+void h(C *hp, C *hp2, C *hq, C *lin) {
+  b = 0;
+}
+
+#pragma omp declare variant(vector_foo)
+template <>
+void h(int *hp, int *hp2, int *hq, int *lin) {
+  h((float *)hp, (float *)hp2, (float *)hq, (float *)lin);
+}
+
+//=
+// 'declare variant' embedded in namespaces
+//=

[PATCH] D67253: clang-misexpect: a standalone tool for verifying the use of __builtin_expect with PGO data

2019-09-06 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added inline comments.



Comment at: clang-tools-extra/clang-misexpect/ClangMisExpect.cpp:77
+break;
+llvm_unreachable("Bad Profile Format given to clang-misexpect use one of "
+ "(clang, llvm, csllvm, sample)");

Nit: llvm_unreackable is unneeded since you cover all `ProfileKind`s here. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67253



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


[PATCH] D65256: [Sema][ObjC] Mark C union fields that have non-trivial ObjC ownership qualifications as unavailable if the union is declared in a system header

2019-09-06 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.
Herald added a subscriber: ychen.



Comment at: lib/Sema/SemaDecl.cpp:11142
 
+bool ignoreForTrivialityComputation(const FieldDecl *FD) {
+  // Ignore unavailable fields since they don't affect the triviality of the

`shouldIgnoreForRecordTriviality` or something like that, please.



Comment at: lib/Sema/SemaDecl.cpp:11144
+  // Ignore unavailable fields since they don't affect the triviality of the
+  // containing struct/union.
+  return FD->hasAttr();

The "since" clause here is circular: this function *defines* what affects the 
triviality.  The comment should talk about the motivations (e.g. fields that 
aren't available in particular language modes) and why this might be okay or is 
the best-available option (despite e.g. the potential for ABI incompatibility 
across language modes),


Repository:
  rC Clang

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

https://reviews.llvm.org/D65256



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


[PATCH] D67294: Register and parse a simplified version of '#pragma omp declare variant'

2019-09-06 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: include/clang/Basic/Attr.td:3202
 
+def OMPDeclareVariantDecl : Attr {
+  let Spellings = [Pragma<"omp", "declare variant">];

For the first patch we don't need the attribute, just parsing/sema analysis



Comment at: include/clang/Basic/Attr.td:3220
+private:
+  NamedDecl *VecVarNamedDecl;
+

This is definitely wrong, especially if we need to handle templates.



Comment at: lib/Parse/ParseOpenMP.cpp:779-783
+  auto Identinfo = PP.getIdentifierInfo(VectorVariantId.Ident->getName());
+  LookupResult Lookup(Actions, Identinfo, VectorVariantId.Loc,
+  Sema::LookupOrdinaryName);
+  CXXScopeSpec SS;
+  if (!Actions.LookupParsedName(Lookup, getCurScope(), &SS)) {

1. All this lookup must be performed in Sema.
2. How do you want to handle templates?
3. Why just do not parse it as an expression? And rely on existing parsing/sema 
analysis for expressions.



Comment at: lib/Parse/ParseOpenMP.cpp:838
+  CachedTokens &Toks, SourceLocation Loc) {
+  PP.EnterToken(Tok, /*IsReinject*/ true);
+  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,

`/*IsReinject=*/` 



Comment at: lib/Parse/ParseOpenMP.cpp:840
+  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
+  /*IsReinject*/ true);
+  // Consume the previously pushed token.

Same here



Comment at: lib/Sema/SemaOpenMP.cpp:4886
 
+Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareVariantDirective(
+DeclGroupPtrTy DG, IdentifierLoc &VectorVariantId, SourceRange SR) {

In this patch need to implement just basic checks, no need to create 
attributes, etc. I would suggest to look at the checks for Target 
Multiversioning attribite (see D40819)


Repository:
  rC Clang

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

https://reviews.llvm.org/D67294



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


[PATCH] D58094: Fix -Wnonportable-include-path suppression for header maps with absolute paths.

2019-09-06 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai marked 3 inline comments as done.
vsapsai added inline comments.



Comment at: clang/lib/Lex/HeaderSearch.cpp:888
 bool InUserSpecifiedSystemFramework = false;
-bool HasBeenMapped = false;
+bool CurrentInHeaderMap = false;
 bool IsFrameworkFoundInDir = false;

dexonsmith wrote:
> Why not name this the same way as the parameter?  (`IsInHeaderMap`)
Wanted to emphasize it applies only to the current search directory. But I 
think what matters is to distinguish between being mentioned in header map and 
changing the search name. So I'll drop "Current" and suggestions for better 
naming are welcome.



Comment at: clang/lib/Lex/HeaderSearch.cpp:896-897
+  assert(CurrentInHeaderMap && "MappedName should come from a header map");
   CacheLookup.MappedName =
-  copyString(Filename, LookupFileCache.getAllocator());
-  if (IsMapped)
-*IsMapped = true;
+  copyString(MappedName, LookupFileCache.getAllocator());
+  HasBeenMapped = true;

dexonsmith wrote:
> It's not obvious to me why this changed from `Filename` to `MappedName`.  Can 
> you explain it?
Technically it doesn't matter because in this branch they are equal (would an 
assertion be useful?). But with my change `IsInHeaderMap` and `MappedName` can 
be different for absolute paths. So I think it is more natural

```lang=c++
if (!MappedName.empty())
  CacheLookup.MappedName = copyString(MappedName);
```

than

```lang=c++
if (!MappedName.empty())
  CacheLookup.MappedName = copyString(Filename);
```

In the second case I need to check that `LookupFile` can modify `Filename`. But 
I don't have a strong opinion about it.



Comment at: clang/lib/Lex/HeaderSearch.cpp:898
+  copyString(MappedName, LookupFileCache.getAllocator());
+  HasBeenMapped = true;
 }

dexonsmith wrote:
> Do we need `HasBeenMapped` outside of the loop, or can you just use the 
> loop-local variable?
Yes. Let me add a test case and a comment explaining it.


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

https://reviews.llvm.org/D58094



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


[PATCH] D65761: Add Windows Control Flow Guard checks (/guard:cf).

2019-09-06 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: llvm/lib/Target/X86/X86FixupCFGuard.cpp:13
+/// for such cases and replaces the pair of instructions with a single
+/// call/invoke. For example:
+///

hans wrote:
> Naive question: Why do we generate code as in the examples in the first 
> place, and can't some general optimization pass do this folding? From the 
> examples it looks like straight-forward constant propagation.
Actually, I used this test IR, LLVM seems to always fold the memory operand 
into the call:
```
@fptr = external dso_local global void()*
define i32 @foo() {
%fp1 = load void()*, void()** @fptr
call void %fp1()
%fp2 = load void()*, void()** @fptr
call void %fp2()
ret i32 0
}
```

Maybe it won't do it if there are more parameters, I'm not sure.

I ran llc with both isels for x64 and ia32, and it always folded the load into 
the call. Maybe it's best to make this a verification pass that emits an error 
via MCContext if there is an unfolded load of the CFG check function pointer?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65761



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


[PATCH] D67292: [clang-tidy] Fix bug in bugprone-use-after-move check

2019-09-06 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added a comment.
This revision is now accepted and ready to land.

Thanks for the quick fix!




Comment at: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp:1198
+}
+  }
   for (int i = 0; i < 10; ++i) {

Unless you think it is redundant, could you also add

```
if (A a1; A(std::move(a2)).getInt() > 0) {}
```

Also some true positive tests would be good:

```
if (A a1; A(std::move(a2)).getInt() > A(std::move(a2)).getInt()) {}
```

```
A a1;
if (A a2 = std::move(a1); A(std::move(a1)) > 0) {}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67292



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


[PATCH] D65917: [clang-tidy] Added check for the Google style guide's category method naming rule.

2019-09-06 Thread David Gatwood via Phabricator via cfe-commits
dgatwood updated this revision to Diff 219151.
dgatwood marked 9 inline comments as done.
dgatwood added a comment.

Tweaked documentation, and replaced the one remaining instance of 
getNameAsString().


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

https://reviews.llvm.org/D65917

Files:
  clang-tools-extra/clang-tidy/google/CMakeLists.txt
  clang-tools-extra/clang-tidy/google/GoogleTidyModule.cpp
  clang-tools-extra/clang-tidy/google/RequireCategoryMethodPrefixesCheck.cpp
  clang-tools-extra/clang-tidy/google/RequireCategoryMethodPrefixesCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/google-objc-require-category-method-prefixes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/google-objc-require-category-method-prefixes.m

Index: clang-tools-extra/test/clang-tidy/google-objc-require-category-method-prefixes.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/google-objc-require-category-method-prefixes.m
@@ -0,0 +1,35 @@
+// RUN: %check_clang_tidy %s google-objc-require-category-method-prefixes %t -config="{CheckOptions: [{key: google-objc-require-category-method-prefixes.ExpectedPrefixes, value: GMO}]}"
+
+@class NSString;
+
+@interface NSURL
++ (nullable instancetype)URLWithString:(NSString *)URLString;
++ (instancetype)alloc;
+- (instancetype)init;
+@end
+
+@interface NSURL (CustomExtension)
+
+- (void)unprefixedMethod;
+- (void)unprefixed;
+- (void)justprefixed_;
+
+@end
+
+// CHECK-MESSAGES: :[[@LINE-6]]:1: warning: the category method 'unprefixedMethod' is not properly prefixed [google-objc-require-category-method-prefixes]
+// CHECK-MESSAGES: :[[@LINE-6]]:1: warning: the category method 'unprefixed' is not properly prefixed [google-objc-require-category-method-prefixes]
+// CHECK-MESSAGES: :[[@LINE-6]]:1: warning: the category method 'justprefixed_' is not properly prefixed [google-objc-require-category-method-prefixes]
+
+@interface NSURL (CustomExtension2)
+- (void)gmo_prefixedMethod;
+@end
+
+@interface GMOURL
++ (nullable instancetype)URLWithString:(NSString *)URLString;
++ (instancetype)alloc;
+- (instancetype)init;
+@end
+
+@interface GMOURL (CustomExtension3)
+- (void)unprefixedMethodInClassWithExpectedPrefix;
+@end
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -230,6 +230,7 @@
google-objc-avoid-throwing-exception
google-objc-function-naming
google-objc-global-variable-declaration
+   google-objc-require-category-method-prefixes
google-readability-avoid-underscore-in-googletest-name
google-readability-braces-around-statements (redirects to readability-braces-around-statements) 
google-readability-casting
Index: clang-tools-extra/docs/clang-tidy/checks/google-objc-require-category-method-prefixes.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/google-objc-require-category-method-prefixes.rst
@@ -0,0 +1,45 @@
+.. title:: clang-tidy - google-objc-require-category-method-prefixes
+
+google-objc-require-category-method-prefixes
+
+
+Warns when Objective-C category method names are not properly prefixed (e.g.
+``gmo_methodName``) unless the category is extending a class with an
+expected prefix (configurable).
+
+The Google Objective-C style guide requires
+`prefixes for methods http://go/objc-style#Category_Names`_ in categories on
+classes that you don't control (for example, categories on Apple or third-party
+framework classes or classes created by other teams) to prevent name collisions
+when those frameworks are updated.
+
+This checker ensures that all methods in categories have some sort of prefix
+(e.g. ``gmo_``).  It allows you to provide a list of expected three-letter
+prefixes specific to your project, and ignores non-prefixed methods in
+categories on classes whose names start with any of those prefixes.
+
+For example, the following code sample is a properly prefixed method on a
+non-owned class (``NSObject``):
+
+.. code-block:: objc
+  @interface NSObject (QEDMyCategory)
+  - (BOOL)qed_myCustomMethod;
+  @end
+
+If you specify ``QED`` as an expected three-letter prefix, the following code
+sample is also allowed:
+
+.. code-block:: objc
+
+  @interface QEDMyClass (MyCategory)
+  - (BOOL)myCustomMethod;
+  @end
+
+Options
+---
+
+.. option:: ExpectedPrefixes
+
+   A semicolon-delimited list of class name prefixes.  Methods in categories
+   that extend classes whose names begin with any of these prefixes are exempt
+   from the method name prefixing requirement.
Index: clang-tools-extra/docs/ReleaseNotes.rst

[PATCH] D65917: [clang-tidy] Added check for the Google style guide's category method naming rule.

2019-09-06 Thread David Gatwood via Phabricator via cfe-commits
dgatwood added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/google/RequireCategoryMethodPrefixesCheck.cpp:57
+  }
+  std::string method_name = method_declaration->getNameAsString();
+  auto owning_objc_class_interface = method_declaration->getClassInterface();

aaron.ballman wrote:
> dgatwood wrote:
> > aaron.ballman wrote:
> > > dgatwood wrote:
> > > > aaron.ballman wrote:
> > > > > dgatwood wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > This should use `getName()` to get a `StringRef` to avoid the 
> > > > > > > copy.
> > > > > > That's actually what I originally tried, but that method won't work 
> > > > > > here, unless I'm missing something.  The getName() method crashes 
> > > > > > with a message saying that "Name is not a simple identifier".
> > > > > You can call `getIdentifier()` instead, and if you get a non-null 
> > > > > object back, you can call `getName()` on that. If it is null, there's 
> > > > > nothing to check.
> > > > I just tried it, and getIdentifier() returns NULL consistently for 
> > > > every category method, so I changed it back to getNameAsString(), which 
> > > > works.
> > > The comment to use `getIdentifier()` was marked as done but the changes 
> > > were not applied; was that a mistake? I'm pushing back on 
> > > `getNameAsString()` because the function is commented as having its use 
> > > discouraged, so we should not be adding new uses of it.
> > I marked that as done because I tried it and it didn't work.  The 
> > getIdentifier() method returned NULL for every category method.
> > 
> > BTW, this isn't my first attempt at writing this code in a way that doesn't 
> > require that method.  I literally fought with getting the name of category 
> > methods for a day or more when I first started writing this, because I kept 
> > getting NULLs or crashes.  At one point, I think I even tried looking for 
> > the owning class and querying its interface.  Nothing worked until I 
> > discovered getNameAsString().
> > 
> > I'm assuming that this is simply a bug somewhere in the LLVM core that 
> > nobody has noticed or bothered to fix, because it really should not be 
> > difficult to get the name of a method.  :-/
> > I'm assuming that this is simply a bug somewhere in the LLVM core that 
> > nobody has noticed or bothered to fix, because it really should not be 
> > difficult to get the name of a method. :-/
> 
> I am not certain if it's a bug or not, but we shouldn't be using essentially 
> deprecated APIs to work around bugs elsewhere. I'd really like to know what's 
> going on here. I am looking through the logic of DeclarationName::print() 
> (which is what getNameAsString() eventually calls into) and it doesn't look 
> like it makes any special accommodations for ObjC method declarations, but it 
> does for ObjC selectors. I'm not an ObjC expert, but I think that's what the 
> name of an ObjC method is, isn't it? If so, I think you would do (assuming 
> the methods can only be named using selectors):
> ```
> MethodDeclaration->getDeclName().getObjCSelector().getAsString()
> ```
Yeah, any Objective-C method inside a class is inherently named by a selector.  
That code works.  Thanks.  :-)



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/google-objc-require-category-method-prefixes.rst:28
+
+If you whitelist the ``QED`` three-letter prefix, the following code sample
+is also allowed:

aaron.ballman wrote:
> whitelist the QED three-letter prefix -> expect the three-letter prefix QED
Applied approximately.  :-)


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

https://reviews.llvm.org/D65917



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


[PATCH] D67292: [clang-tidy] Fix bug in bugprone-use-after-move check

2019-09-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 219152.
ymandel added a comment.

Added tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67292

Files:
  clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
  clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp


Index: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
@@ -1190,15 +1190,44 @@
   std::move(a2);
 }
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+if (A a2 = std::move(a1); a2) {
+  std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 if (A a2 = std::move(a1); A a3 = std::move(a2)) {
   std::move(a3);
 }
   }
+  for (int i = 0; i < 10; ++i) {
+// init followed by condition with move, but without variable declaration.
+if (A a1; A(std::move(a1)).getInt() > 0) {}
+  }
+  for (int i = 0; i < 10; ++i) {
+if (A a1; A(std::move(a1)).getInt() > a1.getInt()) {}
+// CHECK-NOTES: [[@LINE-1]]:43: warning: 'a1' used after it was moved
+// CHECK-NOTES: [[@LINE-2]]:15: note: move occurred here
+// CHECK-NOTES: [[@LINE-3]]:43: note: the use and move are unsequenced
+  }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+if (A a2 = std::move(a1); A(a1) > 0) {}
+// CHECK-NOTES: [[@LINE-1]]:33: warning: 'a1' used after it was moved
+// CHECK-NOTES: [[@LINE-2]]:16: note: move occurred here
+  }
   while (A a = A()) {
 std::move(a);
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+switch (A a2 = std::move(a1); a2) {
+  case true:
+std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 switch (A a2 = a1; A a3 = std::move(a2)) {
Index: clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
===
--- clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
+++ clang-tools-extra/clang-tidy/utils/ExprSequence.cpp
@@ -145,17 +145,24 @@
 return ForRange->getBody();
 } else if (const auto *TheIfStmt = dyn_cast(Parent)) {
   // If statement:
-  // - Sequence init statement before variable declaration.
+  // - Sequence init statement before variable declaration, if present;
+  //   before condition evaluation, otherwise.
   // - Sequence variable declaration (along with the expression used to
   //   initialize it) before the evaluation of the condition.
-  if (S == TheIfStmt->getInit())
-return TheIfStmt->getConditionVariableDeclStmt();
+  if (S == TheIfStmt->getInit()) {
+if (TheIfStmt->getConditionVariableDeclStmt() != nullptr)
+  return TheIfStmt->getConditionVariableDeclStmt();
+return TheIfStmt->getCond();
+  }
   if (S == TheIfStmt->getConditionVariableDeclStmt())
 return TheIfStmt->getCond();
 } else if (const auto *TheSwitchStmt = dyn_cast(Parent)) {
   // Ditto for switch statements.
-  if (S == TheSwitchStmt->getInit())
-return TheSwitchStmt->getConditionVariableDeclStmt();
+  if (S == TheSwitchStmt->getInit()) {
+if (TheSwitchStmt->getConditionVariableDeclStmt() != nullptr)
+  return TheSwitchStmt->getConditionVariableDeclStmt();
+return TheSwitchStmt->getCond();
+  }
   if (S == TheSwitchStmt->getConditionVariableDeclStmt())
 return TheSwitchStmt->getCond();
 } else if (const auto *TheWhileStmt = dyn_cast(Parent)) {


Index: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp
@@ -1190,15 +1190,44 @@
   std::move(a2);
 }
   }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+if (A a2 = std::move(a1); a2) {
+  std::move(a2);
+}
+  }
   for (int i = 0; i < 10; ++i) {
 A a1;
 if (A a2 = std::move(a1); A a3 = std::move(a2)) {
   std::move(a3);
 }
   }
+  for (int i = 0; i < 10; ++i) {
+// init followed by condition with move, but without variable declaration.
+if (A a1; A(std::move(a1)).getInt() > 0) {}
+  }
+  for (int i = 0; i < 10; ++i) {
+if (A a1; A(std::move(a1)).getInt() > a1.getInt()) {}
+// CHECK-NOTES: [[@LINE-1]]:43: warning: 'a1' used after it was moved
+// CHECK-NOTES: [[@LINE-2]]:15: note: move occurred here
+// CHECK-NOTES: [[@LINE-3]]:43: note: the use and move are unsequenced
+  }
+  for (int i = 0; i < 10; ++i) {
+A a1;
+if (A a2 = std::move(a1); A(a1) > 0) {}
+// CHECK-NOTES: [[@LINE-1]]:33: warning: 'a1' used after it was moved
+// CHECK-NOTES: [[@LINE-2]]:16: note: move occurred here
+  }
   while (A a = A()) {
 std::move(a);
   }
+  for

[PATCH] D67292: [clang-tidy] Fix bug in bugprone-use-after-move check

2019-09-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 2 inline comments as done.
ymandel added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp:1198
+}
+  }
   for (int i = 0; i < 10; ++i) {

gribozavr wrote:
> Unless you think it is redundant, could you also add
> 
> ```
> if (A a1; A(std::move(a2)).getInt() > 0) {}
> ```
> 
> Also some true positive tests would be good:
> 
> ```
> if (A a1; A(std::move(a2)).getInt() > A(std::move(a2)).getInt()) {}
> ```
> 
> ```
> A a1;
> if (A a2 = std::move(a1); A(std::move(a1)) > 0) {}
> ```
Done, but any idea why everything in this function is placed inside a loop?  
Looks like its just for scoping, but then why not just a compound statement, as 
is done above? This feels very odd.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67292



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


[PATCH] D64644: [Sema] Fixes an assertion failure while instantiation a template with an incomplete typo corrected type

2019-09-06 Thread Mark de Wever via Phabricator via cfe-commits
Mordante added a comment.

Thanks for the review.
Could you commit this patch? I don't have commit access.


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

https://reviews.llvm.org/D64644



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


r371241 - [LifetimeAnalysis] don't use raw string literals in macros

2019-09-06 Thread Matthias Gehre via cfe-commits
Author: mgehre
Date: Fri Sep  6 12:15:02 2019
New Revision: 371241

URL: http://llvm.org/viewvc/llvm-project?rev=371241&view=rev
Log:
[LifetimeAnalysis] don't use raw string literals in macros

They broke the AArch64 bots (gcc does not support it)

Modified:
cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp

Modified: cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp?rev=371241&r1=371240&r2=371241&view=diff
==
--- cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp (original)
+++ cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp Fri Sep  6 12:15:02 
2019
@@ -14,48 +14,42 @@ namespace clang {
 using namespace ast_matchers;
 
 TEST(OwnerPointer, BothHaveAttributes) {
-  EXPECT_TRUE(matches(
-R"cpp(
-  template
-  class [[gsl::Owner]] C;
-
-  template
-  class [[gsl::Owner]] C {};
-
-  C c;
-  )cpp",
-classTemplateSpecializationDecl(hasName("C"), 
hasAttr(clang::attr::Owner;
+  EXPECT_TRUE(matches("template"
+  "class [[gsl::Owner]] C;"
+
+  "template"
+  "class [[gsl::Owner]] C {};"
+
+  "C c;",
+  classTemplateSpecializationDecl(
+  hasName("C"), hasAttr(clang::attr::Owner;
 }
 
 TEST(OwnerPointer, ForwardDeclOnly) {
-  EXPECT_TRUE(matches(
-R"cpp(
-  template
-  class [[gsl::Owner]] C;
-
-  template
-  class C {};
-
-  C c;
-  )cpp",
-classTemplateSpecializationDecl(hasName("C"), 
hasAttr(clang::attr::Owner;
+  EXPECT_TRUE(matches("template"
+  "class [[gsl::Owner]] C;"
+
+  "template"
+  "class C {};"
+
+  "C c;",
+  classTemplateSpecializationDecl(
+  hasName("C"), hasAttr(clang::attr::Owner;
 }
 
 TEST(OwnerPointer, LateForwardDeclOnly) {
-  EXPECT_TRUE(matches(
-R"cpp(
-  template
-  class C;
-
-  template
-  class C {};
-
-  template
-  class [[gsl::Owner]] C;
-
-  C c;
-  )cpp",
-classTemplateSpecializationDecl(hasName("C"), 
hasAttr(clang::attr::Owner;
+  EXPECT_TRUE(matches("template"
+  "class C;"
+
+  "template"
+  "class C {};"
+
+  "template"
+  "class [[gsl::Owner]] C;"
+
+  "C c;",
+  classTemplateSpecializationDecl(
+  hasName("C"), hasAttr(clang::attr::Owner;
 }
 
 } // namespace clang


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


Re: r371182 - Reland [LifetimeAnalysis] Support more STL idioms (template forward declaration and DependentNameType)

2019-09-06 Thread Matthias Gehre via cfe-commits
Yvan, sorry!
Should be fixed now.

Am Fr., 6. Sept. 2019 um 16:40 Uhr schrieb Yvan Roux :

> Hi Matthias,
>
> this commit broke AArch64 bots, logs are available here:
>
>
> http://lab.llvm.org:8011/builders/clang-cmake-aarch64-quick/builds/19917/steps/ninja%20check%201/logs/stdio
>
> Thanks,
> Yvan
>
> On Fri, 6 Sep 2019 at 10:54, Matthias Gehre via cfe-commits
>  wrote:
> >
> > Author: mgehre
> > Date: Fri Sep  6 01:56:30 2019
> > New Revision: 371182
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=371182&view=rev
> > Log:
> > Reland [LifetimeAnalysis] Support more STL idioms (template forward
> declaration and DependentNameType)
> >
> > Reland after https://reviews.llvm.org/D66806 fixed the false-positive
> diagnostics.
> >
> > Summary:
> > This fixes inference of gsl::Pointer on std::set::iterator with
> libstdc++ (the typedef for iterator
> > on the template is a DependentNameType - we can only put the
> gsl::Pointer attribute
> > on the underlaying record after instantiation)
> >
> > inference of gsl::Pointer on std::vector::iterator with libc++ (the
> class was forward-declared,
> > we added the gsl::Pointer on the canonical decl (the forward decl), and
> later when the
> > template was instantiated, there was no attribute on the definition so
> it was not instantiated).
> >
> > and a duplicate gsl::Pointer on some class with libstdc++ (we first
> added an attribute to
> > a incomplete instantiation, and then another was copied from the
> template definition
> > when the instantiation was completed).
> >
> > We now add the attributes to all redeclarations to fix thos issues and
> make their usage easier.
> >
> > Reviewers: gribozavr
> >
> > Subscribers: Szelethus, xazax.hun, cfe-commits
> >
> > Tags: #clang
> >
> > Differential Revision: https://reviews.llvm.org/D66179
> >
> > Added:
> > cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp
> > Modified:
> > cfe/trunk/lib/Sema/SemaAttr.cpp
> > cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> > cfe/trunk/lib/Sema/SemaInit.cpp
> > cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
> > cfe/trunk/test/SemaCXX/attr-gsl-owner-pointer-std.cpp
> > cfe/trunk/test/SemaCXX/attr-gsl-owner-pointer.cpp
> > cfe/trunk/unittests/Sema/CMakeLists.txt
> >
> > Modified: cfe/trunk/lib/Sema/SemaAttr.cpp
> > URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAttr.cpp?rev=371182&r1=371181&r2=371182&view=diff
> >
> ==
> > --- cfe/trunk/lib/Sema/SemaAttr.cpp (original)
> > +++ cfe/trunk/lib/Sema/SemaAttr.cpp Fri Sep  6 01:56:30 2019
> > @@ -88,13 +88,11 @@ void Sema::AddMsStructLayoutForRecord(Re
> >  template 
> >  static void addGslOwnerPointerAttributeIfNotExisting(ASTContext
> &Context,
> >   CXXRecordDecl
> *Record) {
> > -  CXXRecordDecl *Canonical = Record->getCanonicalDecl();
> > -  if (Canonical->hasAttr() ||
> Canonical->hasAttr())
> > +  if (Record->hasAttr() || Record->hasAttr())
> >  return;
> >
> > -  Canonical->addAttr(::new (Context) Attribute(SourceRange{}, Context,
> > -   /*DerefType*/ nullptr,
> > -   /*Spelling=*/0));
> > +  for (Decl *Redecl : Record->redecls())
> > +Redecl->addAttr(Attribute::CreateImplicit(Context,
> /*DerefType=*/nullptr));
> >  }
> >
> >  void Sema::inferGslPointerAttribute(NamedDecl *ND,
> > @@ -189,8 +187,7 @@ void Sema::inferGslOwnerPointerAttribute
> >
> >// Handle classes that directly appear in std namespace.
> >if (Record->isInStdNamespace()) {
> > -CXXRecordDecl *Canonical = Record->getCanonicalDecl();
> > -if (Canonical->hasAttr() ||
> Canonical->hasAttr())
> > +if (Record->hasAttr() || Record->hasAttr())
> >return;
> >
> >  if (StdOwners.count(Record->getName()))
> >
> > Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> > URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=371182&r1=371181&r2=371182&view=diff
> >
> ==
> > --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
> > +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Fri Sep  6 01:56:30 2019
> > @@ -4592,9 +4592,11 @@ static void handleLifetimeCategoryAttr(S
> >}
> >return;
> >  }
> > -D->addAttr(::new (S.Context)
> > -   OwnerAttr(AL.getRange(), S.Context, DerefTypeLoc,
> > - AL.getAttributeSpellingListIndex()));
> > +for (Decl *Redecl : D->redecls()) {
> > +  Redecl->addAttr(::new (S.Context)
> > +  OwnerAttr(AL.getRange(), S.Context,
> DerefTypeLoc,
> > +
> AL.getAttributeSpellingListIndex()));
> > +}
> >} else {
> >  if (checkAttrMutualExclusion(S, D, AL))
> >return;
> > @@ -4609,9 +4611,11 @@ static void handleLifetimeCategoryAttr(S
> >}
> >ret

Re: r371222 - [Diagnostics] Refactor code for -Wsizeof-pointer-div, catch more cases; also add -Wsizeof-array-div

2019-09-06 Thread Nico Weber via cfe-commits
This reports things like

error: expresion will return the incorrect number of elements in the array;
the array element type is 'const char *', not 'char *'

which doesn't look quite right...

On Fri, Sep 6, 2019 at 12:11 PM David Bolvansky via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: xbolva00
> Date: Fri Sep  6 09:12:48 2019
> New Revision: 371222
>
> URL: http://llvm.org/viewvc/llvm-project?rev=371222&view=rev
> Log:
> [Diagnostics] Refactor code for -Wsizeof-pointer-div, catch more cases;
> also add -Wsizeof-array-div
>
> Previously, -Wsizeof-pointer-div failed to catch:
> const int *r;
> sizeof(r) / sizeof(int);
>
> Now fixed.
> Also introduced -Wsizeof-array-div which catches bugs like:
> sizeof(r) / sizeof(short);
>
> (Array element type does not match type of sizeof operand).
>
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> cfe/trunk/lib/Sema/SemaChecking.cpp
> cfe/trunk/lib/Sema/SemaExpr.cpp
> cfe/trunk/test/Sema/div-sizeof-ptr.cpp
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=371222&r1=371221&r2=371222&view=diff
>
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Sep  6
> 09:12:48 2019
> @@ -3391,6 +3391,10 @@ def note_pointer_declared_here : Note<
>  def warn_division_sizeof_ptr : Warning<
>"'%0' will return the size of the pointer, not the array itself">,
>InGroup>;
> +def warn_division_sizeof_array : Warning<
> +  "expresion will return the incorrect number of elements in the array;
> the array "
> +  "element type is %0, not %1">,
> +  InGroup>;
>
>  def note_function_warning_silence : Note<
>  "prefix with the address-of operator to silence this warning">;
> @@ -8003,7 +8007,7 @@ def warn_array_index_precedes_bounds : W
>  def warn_array_index_exceeds_bounds : Warning<
>"array index %0 is past the end of the array (which contains %1 "
>"element%s2)">, InGroup;
> -def note_array_index_out_of_bounds : Note<
> +def note_array_declared_here : Note<
>"array %0 declared here">;
>
>  def warn_printf_insufficient_data_args : Warning<
>
> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=371222&r1=371221&r2=371222&view=diff
>
> ==
> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Fri Sep  6 09:12:48 2019
> @@ -13008,7 +13008,7 @@ void Sema::CheckArrayAccess(const Expr *
>
>if (ND)
>  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
> -PDiag(diag::note_array_index_out_of_bounds)
> +PDiag(diag::note_array_declared_here)
>  << ND->getDeclName());
>  }
>
>
> Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=371222&r1=371221&r2=371222&view=diff
>
> ==
> --- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaExpr.cpp Fri Sep  6 09:12:48 2019
> @@ -9135,7 +9135,7 @@ static void checkArithmeticNull(Sema &S,
><< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
>  }
>
> -static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
> +static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr
> *RHS,
>SourceLocation Loc) {
>const auto *LUE = dyn_cast(LHS);
>const auto *RUE = dyn_cast(RHS);
> @@ -9154,16 +9154,29 @@ static void DiagnoseDivisionSizeofPointe
>else
>  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
>
> -  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
> -return;
> -  if (LHSTy->getPointeeType().getCanonicalType() !=
> RHSTy.getCanonicalType())
> -return;
> -
> -  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS <<
> LHS->getSourceRange();
> -  if (const auto *DRE = dyn_cast(LHSArg)) {
> -if (const ValueDecl *LHSArgDecl = DRE->getDecl())
> -  S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
> -  << LHSArgDecl;
> +  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
> +if (LHSTy->getPointeeType().getCanonicalType().getUnqualifiedType() !=
> +RHSTy.getCanonicalType().getUnqualifiedType())
> +  return;
> +
> +S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS <<
> LHS->getSourceRange();
> +if (const auto *DRE = dyn_cast(LHSArg)) {
> +  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
> +S.Diag(LHSArgDecl->getLocation(),
> diag::note_pointer_declared_here)
> +<< LHSArgDecl;

Re: r371241 - [LifetimeAnalysis] don't use raw string literals in macros

2019-09-06 Thread Nico Weber via cfe-commits
(The slightly more usual fix is to do `const char kFoo[] = R"cpp(...)cpp";
EXPECT_TRUE(matches(kFoo...)`)

On Fri, Sep 6, 2019 at 3:13 PM Matthias Gehre via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: mgehre
> Date: Fri Sep  6 12:15:02 2019
> New Revision: 371241
>
> URL: http://llvm.org/viewvc/llvm-project?rev=371241&view=rev
> Log:
> [LifetimeAnalysis] don't use raw string literals in macros
>
> They broke the AArch64 bots (gcc does not support it)
>
> Modified:
> cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp
>
> Modified: cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp?rev=371241&r1=371240&r2=371241&view=diff
>
> ==
> --- cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp (original)
> +++ cfe/trunk/unittests/Sema/GslOwnerPointerInference.cpp Fri Sep  6
> 12:15:02 2019
> @@ -14,48 +14,42 @@ namespace clang {
>  using namespace ast_matchers;
>
>  TEST(OwnerPointer, BothHaveAttributes) {
> -  EXPECT_TRUE(matches(
> -R"cpp(
> -  template
> -  class [[gsl::Owner]] C;
> -
> -  template
> -  class [[gsl::Owner]] C {};
> -
> -  C c;
> -  )cpp",
> -classTemplateSpecializationDecl(hasName("C"),
> hasAttr(clang::attr::Owner;
> +  EXPECT_TRUE(matches("template"
> +  "class [[gsl::Owner]] C;"
> +
> +  "template"
> +  "class [[gsl::Owner]] C {};"
> +
> +  "C c;",
> +  classTemplateSpecializationDecl(
> +  hasName("C"), hasAttr(clang::attr::Owner;
>  }
>
>  TEST(OwnerPointer, ForwardDeclOnly) {
> -  EXPECT_TRUE(matches(
> -R"cpp(
> -  template
> -  class [[gsl::Owner]] C;
> -
> -  template
> -  class C {};
> -
> -  C c;
> -  )cpp",
> -classTemplateSpecializationDecl(hasName("C"),
> hasAttr(clang::attr::Owner;
> +  EXPECT_TRUE(matches("template"
> +  "class [[gsl::Owner]] C;"
> +
> +  "template"
> +  "class C {};"
> +
> +  "C c;",
> +  classTemplateSpecializationDecl(
> +  hasName("C"), hasAttr(clang::attr::Owner;
>  }
>
>  TEST(OwnerPointer, LateForwardDeclOnly) {
> -  EXPECT_TRUE(matches(
> -R"cpp(
> -  template
> -  class C;
> -
> -  template
> -  class C {};
> -
> -  template
> -  class [[gsl::Owner]] C;
> -
> -  C c;
> -  )cpp",
> -classTemplateSpecializationDecl(hasName("C"),
> hasAttr(clang::attr::Owner;
> +  EXPECT_TRUE(matches("template"
> +  "class C;"
> +
> +  "template"
> +  "class C {};"
> +
> +  "template"
> +  "class [[gsl::Owner]] C;"
> +
> +  "C c;",
> +  classTemplateSpecializationDecl(
> +  hasName("C"), hasAttr(clang::attr::Owner;
>  }
>
>  } // namespace clang
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D67122: [UBSan][clang][compiler-rt] Applying non-zero offset to nullptr is undefined behaviour

2019-09-06 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

I will still need to see where else `EmitCheckedInBoundsGEP()` should be used, 
but i'm wondering
if it should be best done in follow-ups, since this already catches the 
interesting bits..

In D67122#1659721 , @vsk wrote:

> Still think this looks good. Have you tried running this on the llvm test 
> suite, or some other interesting corpus? Would be curious to see any pre/post 
> patch numbers.


There were 1.5 occurrences in test-suite.
I'd prefer not to try running it over llvm stage-2/3 (i can, but it's gonna be 
slow..)

Though i guess you were talking about *performance* numbers?

I'm not good with using test-suite for perf, so i'm yet again going to use my 
own bench.
F9934220: rawspeed-pointer-overflow-0-baseline.json 
 F9934221: 
rawspeed-pointer-overflow-1-old.json  
F9934222: rawspeed-pointer-overflow-2-new.json 


TLDR: (all measurements done with llvm ToT, the sanitizer never fired.)

- no sanitization vs. existing check: average `+20.75%` slowdown
- existing check vs. check after this patch: average `+26.36%` slowdown
- no sanitization vs. this patch: average `+52.58%` slowdown

I suspect some of this might be recoverable, but i don't know yet.

@vsk let me know if that answered your questions. thanks!

In D67122#1659896 , @lebedev.ri wrote:

> In D67122#1659882 , @rupprecht wrote:
>
> > > Still think this looks good. Have you tried running this on the llvm test 
> > > suite, or some other interesting corpus? Would be curious to see any 
> > > pre/post patch numbers.
> >
> > I finally had time this morning to patch this in and give it a shot. (Sorry 
> > for the delay... it's been a real busy week :( )
>
>
>
>
> > First, starting off with the good news: I reverted all the fixes I made, 
> > and now all the tests fail when running w/ ubsan. Yay!
> >  The error we see in each case is `UndefinedBehaviorSanitizer: 
> > nullptr-with-nonzero-offset` with the logs containing `runtime error: 
> > applying non-zero offset  to null pointer`. Which catches the two 
> > places where we were adding some non-zero offset to nullptr,
>
> That is good :)
>
> > but doesn't seem to catch the nullptr-after-nonzero-offset case in 
> > https://github.com/google/filament/pull/1566 -- instead, it fails later, 
> > when the pointer with a value of nullptr is incremented. (Or... maybe this 
> > is actually a separate bug. Hmm. Needs some more testing...)
>
> Well yeah, there are quite a few cases in clang codegen where we create `gep 
> inbounds` without sanitization, so it may or may not be one of those cases.
>
> > At any rate, I have some more tests to run to get some idea of what % of 
> > code this would flag as being bad.


@rupprecht

So i have tried to reduce https://github.com/google/filament/pull/1566/files
`CommandBase` by hand, and arrived at: https://godbolt.org/z/O7svxp

And it is clearly being sanitized, and you wouldn't even get to call `execute()`
with `this = nullptr`, a check for that was inserted too.

If you revert whatever fixes that were applied, fix the code
about which sanitizer complaints, does that fix miscompilation?

But TLDR, either the fix in https://github.com/google/filament/pull/1566
is incorrect and the actually-bad code is elsewhere,
or you have some other unsanitized UB elsewhere. Could be both :S


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67122



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


r371250 - [clang][Index][NFC] Put IndexingOptions to a separate header

2019-09-06 Thread Jan Korous via cfe-commits
Author: jkorous
Date: Fri Sep  6 13:08:32 2019
New Revision: 371250

URL: http://llvm.org/viewvc/llvm-project?rev=371250&view=rev
Log:
[clang][Index][NFC] Put IndexingOptions to a separate header

Added:
cfe/trunk/include/clang/Index/IndexingOptions.h
Modified:
cfe/trunk/include/clang/Index/IndexingAction.h

Modified: cfe/trunk/include/clang/Index/IndexingAction.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Index/IndexingAction.h?rev=371250&r1=371249&r2=371250&view=diff
==
--- cfe/trunk/include/clang/Index/IndexingAction.h (original)
+++ cfe/trunk/include/clang/Index/IndexingAction.h Fri Sep  6 13:08:32 2019
@@ -11,6 +11,7 @@
 
 #include "clang/AST/ASTConsumer.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Index/IndexingOptions.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -31,26 +32,6 @@ namespace serialization {
 namespace index {
   class IndexDataConsumer;
 
-struct IndexingOptions {
-  enum class SystemSymbolFilterKind {
-None,
-DeclarationsOnly,
-All,
-  };
-
-  SystemSymbolFilterKind SystemSymbolFilter
-= SystemSymbolFilterKind::DeclarationsOnly;
-  bool IndexFunctionLocals = false;
-  bool IndexImplicitInstantiation = false;
-  // Whether to index macro definitions in the Preprocesor when preprocessor
-  // callback is not available (e.g. after parsing has finished). Note that
-  // macro references are not available in Proprocessor.
-  bool IndexMacrosInPreprocessor = false;
-  // Has no effect if IndexFunctionLocals are false.
-  bool IndexParametersInDeclarations = false;
-  bool IndexTemplateParameters = false;
-};
-
 /// Creates an ASTConsumer that indexes all symbols (macros and AST decls).
 std::unique_ptr createIndexingASTConsumer(
 std::shared_ptr DataConsumer,

Added: cfe/trunk/include/clang/Index/IndexingOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Index/IndexingOptions.h?rev=371250&view=auto
==
--- cfe/trunk/include/clang/Index/IndexingOptions.h (added)
+++ cfe/trunk/include/clang/Index/IndexingOptions.h Fri Sep  6 13:08:32 2019
@@ -0,0 +1,42 @@
+//===--- IndexingOptions.h - Options for indexing ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_INDEX_INDEXINGOPTIONS_H
+#define LLVM_CLANG_INDEX_INDEXINGOPTIONS_H
+
+#include "clang/Frontend/FrontendOptions.h"
+#include 
+#include 
+
+namespace clang {
+namespace index {
+
+struct IndexingOptions {
+  enum class SystemSymbolFilterKind {
+None,
+DeclarationsOnly,
+All,
+  };
+
+  SystemSymbolFilterKind SystemSymbolFilter =
+  SystemSymbolFilterKind::DeclarationsOnly;
+  bool IndexFunctionLocals = false;
+  bool IndexImplicitInstantiation = false;
+  // Whether to index macro definitions in the Preprocesor when preprocessor
+  // callback is not available (e.g. after parsing has finished). Note that
+  // macro references are not available in Proprocessor.
+  bool IndexMacrosInPreprocessor = false;
+  // Has no effect if IndexFunctionLocals are false.
+  bool IndexParametersInDeclarations = false;
+  bool IndexTemplateParameters = false;
+};
+
+} // namespace index
+} // namespace clang
+
+#endif // LLVM_CLANG_INDEX_INDEXINGOPTIONS_H


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


[clang-tools-extra] r371250 - [clang][Index][NFC] Put IndexingOptions to a separate header

2019-09-06 Thread Jan Korous via cfe-commits
Author: jkorous
Date: Fri Sep  6 13:08:32 2019
New Revision: 371250

URL: http://llvm.org/viewvc/llvm-project?rev=371250&view=rev
Log:
[clang][Index][NFC] Put IndexingOptions to a separate header

Modified:
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.cpp
clang-tools-extra/trunk/clangd/index/IndexAction.cpp
clang-tools-extra/trunk/clangd/unittests/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/XRefs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/XRefs.cpp?rev=371250&r1=371249&r2=371250&view=diff
==
--- clang-tools-extra/trunk/clangd/XRefs.cpp (original)
+++ clang-tools-extra/trunk/clangd/XRefs.cpp Fri Sep  6 13:08:32 2019
@@ -33,6 +33,7 @@
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/None.h"

Modified: clang-tools-extra/trunk/clangd/index/FileIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/FileIndex.cpp?rev=371250&r1=371249&r2=371250&view=diff
==
--- clang-tools-extra/trunk/clangd/index/FileIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/FileIndex.cpp Fri Sep  6 13:08:32 2019
@@ -17,6 +17,7 @@
 #include "index/SymbolOrigin.h"
 #include "index/dex/Dex.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Index/IndexingOptions.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMap.h"

Modified: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/IndexAction.cpp?rev=371250&r1=371249&r2=371250&view=diff
==
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp Fri Sep  6 13:08:32 
2019
@@ -18,6 +18,7 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/MultiplexConsumer.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Index/IndexingOptions.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include 

Modified: clang-tools-extra/trunk/clangd/unittests/SymbolCollectorTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/SymbolCollectorTests.cpp?rev=371250&r1=371249&r2=371250&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/SymbolCollectorTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/SymbolCollectorTests.cpp Fri Sep  
6 13:08:32 2019
@@ -14,6 +14,7 @@
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Index/IndexingOptions.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/STLExtras.h"


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


Re: r371222 - [Diagnostics] Refactor code for -Wsizeof-pointer-div, catch more cases; also add -Wsizeof-array-div

2019-09-06 Thread Richard Smith via cfe-commits
In addition to the below, this also seems to be missing any test coverage
for the new warning. Did you forget to add a test file?

On Fri, 6 Sep 2019 at 12:38, Nico Weber via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> This reports things like
>
> error: expresion will return the incorrect number of elements in the
> array; the array element type is 'const char *', not 'char *'
>
> which doesn't look quite right...
>
> On Fri, Sep 6, 2019 at 12:11 PM David Bolvansky via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: xbolva00
>> Date: Fri Sep  6 09:12:48 2019
>> New Revision: 371222
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=371222&view=rev
>> Log:
>> [Diagnostics] Refactor code for -Wsizeof-pointer-div, catch more cases;
>> also add -Wsizeof-array-div
>>
>> Previously, -Wsizeof-pointer-div failed to catch:
>> const int *r;
>> sizeof(r) / sizeof(int);
>>
>> Now fixed.
>> Also introduced -Wsizeof-array-div which catches bugs like:
>> sizeof(r) / sizeof(short);
>>
>> (Array element type does not match type of sizeof operand).
>>
>>
>> Modified:
>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> cfe/trunk/lib/Sema/SemaChecking.cpp
>> cfe/trunk/lib/Sema/SemaExpr.cpp
>> cfe/trunk/test/Sema/div-sizeof-ptr.cpp
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=371222&r1=371221&r2=371222&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Sep  6
>> 09:12:48 2019
>> @@ -3391,6 +3391,10 @@ def note_pointer_declared_here : Note<
>>  def warn_division_sizeof_ptr : Warning<
>>"'%0' will return the size of the pointer, not the array itself">,
>>InGroup>;
>> +def warn_division_sizeof_array : Warning<
>> +  "expresion will return the incorrect number of elements in the array;
>> the array "
>> +  "element type is %0, not %1">,
>>
>
This warning text doesn't seem right (what is "the incorrect number of
elements"?).

Perhaps "expression does not compute the number of elements in the array
%0; element type is %1, not %2"?

(Also you misspelled "expression".)


> +  InGroup>;
>>
>>  def note_function_warning_silence : Note<
>>  "prefix with the address-of operator to silence this warning">;
>> @@ -8003,7 +8007,7 @@ def warn_array_index_precedes_bounds : W
>>  def warn_array_index_exceeds_bounds : Warning<
>>"array index %0 is past the end of the array (which contains %1 "
>>"element%s2)">, InGroup;
>> -def note_array_index_out_of_bounds : Note<
>> +def note_array_declared_here : Note<
>>"array %0 declared here">;
>>
>>  def warn_printf_insufficient_data_args : Warning<
>>
>> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=371222&r1=371221&r2=371222&view=diff
>>
>> ==
>> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Fri Sep  6 09:12:48 2019
>> @@ -13008,7 +13008,7 @@ void Sema::CheckArrayAccess(const Expr *
>>
>>if (ND)
>>  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
>> -PDiag(diag::note_array_index_out_of_bounds)
>> +PDiag(diag::note_array_declared_here)
>>  << ND->getDeclName());
>>  }
>>
>>
>> Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=371222&r1=371221&r2=371222&view=diff
>>
>> ==
>> --- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaExpr.cpp Fri Sep  6 09:12:48 2019
>> @@ -9135,7 +9135,7 @@ static void checkArithmeticNull(Sema &S,
>><< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
>>  }
>>
>> -static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
>> +static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS,
>> Expr *RHS,
>>SourceLocation Loc) {
>>const auto *LUE = dyn_cast(LHS);
>>const auto *RUE = dyn_cast(RHS);
>> @@ -9154,16 +9154,29 @@ static void DiagnoseDivisionSizeofPointe
>>else
>>  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
>>
>> -  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
>> -return;
>> -  if (LHSTy->getPointeeType().getCanonicalType() !=
>> RHSTy.getCanonicalType())
>> -return;
>> -
>> -  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS <<
>> LHS->getSourceRange();
>> -  if (const auto *DRE = dyn_cast(LHSArg)) {
>> -if (const ValueDecl *LHSArgDecl = DRE->getDecl())
>> -  S.Diag(LHSArgDecl->getLocation(), diag:

r371252 - Update comment for mangling to match extended mangling rule in r371004.

2019-09-06 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Fri Sep  6 13:32:01 2019
New Revision: 371252

URL: http://llvm.org/viewvc/llvm-project?rev=371252&view=rev
Log:
Update comment for  mangling to match extended mangling 
rule in r371004.

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

Modified: cfe/trunk/lib/AST/ItaniumMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ItaniumMangle.cpp?rev=371252&r1=371251&r2=371252&view=diff
==
--- cfe/trunk/lib/AST/ItaniumMangle.cpp (original)
+++ cfe/trunk/lib/AST/ItaniumMangle.cpp Fri Sep  6 13:32:01 2019
@@ -1688,6 +1688,7 @@ void CXXNameMangler::mangleUnqualifiedBl
 //   ::= Ty  # template type parameter
 //   ::= Tn# template non-type parameter
 //   ::= Tt * E # template template parameter
+//   ::= Tp # template parameter pack
 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
   if (auto *Ty = dyn_cast(Decl)) {
 if (Ty->isParameterPack())


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


Re: r371004 - [c++20] Fix some ambiguities in our mangling of lambdas with explicit

2019-09-06 Thread Richard Smith via cfe-commits
On Thu, 5 Sep 2019 at 17:39, Nico Weber via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> On Wed, Sep 4, 2019 at 9:22 PM Richard Smith via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: rsmith
>> Date: Wed Sep  4 18:23:47 2019
>> New Revision: 371004
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=371004&view=rev
>> Log:
>> [c++20] Fix some ambiguities in our mangling of lambdas with explicit
>> template parameters.
>>
>> This finishes the implementation of the proposal described in
>> https://github.com/itanium-cxx-abi/cxx-abi/issues/31. (We already
>> implemented the  extensions, but didn't take them into
>> account when computing mangling numbers, and didn't deal properly with
>> expanded parameter packs, and didn't disambiguate between different
>> levels of template parameters in manglings.)
>>
>> Modified:
>> cfe/trunk/include/clang/AST/Mangle.h
>> cfe/trunk/lib/AST/DeclBase.cpp
>> cfe/trunk/lib/AST/ItaniumCXXABI.cpp
>> cfe/trunk/lib/AST/ItaniumMangle.cpp
>> cfe/trunk/lib/Sema/SemaLambda.cpp
>> cfe/trunk/test/CodeGenCXX/mangle-lambda-explicit-template-params.cpp
>>
>> Modified: cfe/trunk/include/clang/AST/Mangle.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Mangle.h?rev=371004&r1=371003&r2=371004&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/AST/Mangle.h (original)
>> +++ cfe/trunk/include/clang/AST/Mangle.h Wed Sep  4 18:23:47 2019
>> @@ -170,6 +170,8 @@ public:
>>virtual void mangleCXXDtorComdat(const CXXDestructorDecl *D,
>> raw_ostream &) = 0;
>>
>> +  virtual void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream
>> &) = 0;
>> +
>>static bool classof(const MangleContext *C) {
>>  return C->getKind() == MK_Itanium;
>>}
>>
>> Modified: cfe/trunk/lib/AST/DeclBase.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/DeclBase.cpp?rev=371004&r1=371003&r2=371004&view=diff
>>
>> ==
>> --- cfe/trunk/lib/AST/DeclBase.cpp (original)
>> +++ cfe/trunk/lib/AST/DeclBase.cpp Wed Sep  4 18:23:47 2019
>> @@ -12,6 +12,7 @@
>>
>>  #include "clang/AST/DeclBase.h"
>>  #include "clang/AST/ASTContext.h"
>> +#include "clang/AST/ASTLambda.h"
>>  #include "clang/AST/ASTMutationListener.h"
>>  #include "clang/AST/Attr.h"
>>  #include "clang/AST/AttrIterator.h"
>> @@ -1043,6 +1044,12 @@ DeclContext *DeclContext::getLookupParen
>>  getLexicalParent()->getRedeclContext()->isRecord())
>>return getLexicalParent();
>>
>> +  // A lookup within the call operator of a lambda never looks in the
>> lambda
>> +  // class; instead, skip to the context in which that closure type is
>> +  // declared.
>> +  if (isLambdaCallOperator(this))
>> +return getParent()->getParent();
>> +
>>return getParent();
>>  }
>>
>>
>> Modified: cfe/trunk/lib/AST/ItaniumCXXABI.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ItaniumCXXABI.cpp?rev=371004&r1=371003&r2=371004&view=diff
>>
>> ==
>> --- cfe/trunk/lib/AST/ItaniumCXXABI.cpp (original)
>> +++ cfe/trunk/lib/AST/ItaniumCXXABI.cpp Wed Sep  4 18:23:47 2019
>> @@ -19,10 +19,12 @@
>>  #include "CXXABI.h"
>>  #include "clang/AST/ASTContext.h"
>>  #include "clang/AST/DeclCXX.h"
>> +#include "clang/AST/Mangle.h"
>>  #include "clang/AST/MangleNumberingContext.h"
>>  #include "clang/AST/RecordLayout.h"
>>  #include "clang/AST/Type.h"
>>  #include "clang/Basic/TargetInfo.h"
>> +#include "llvm/ADT/FoldingSet.h"
>>  #include "llvm/ADT/iterator.h"
>>
>>  using namespace clang;
>> @@ -73,10 +75,33 @@ struct DecompositionDeclName {
>>  }
>>
>>  namespace llvm {
>> +template bool isDenseMapKeyEmpty(T V) {
>> +  return llvm::DenseMapInfo::isEqual(
>> +  V, llvm::DenseMapInfo::getEmptyKey());
>> +}
>> +template bool isDenseMapKeyTombstone(T V) {
>> +  return llvm::DenseMapInfo::isEqual(
>> +  V, llvm::DenseMapInfo::getTombstoneKey());
>> +}
>> +
>> +template
>> +Optional areDenseMapKeysEqualSpecialValues(T LHS, T RHS) {
>> +  bool LHSEmpty = isDenseMapKeyEmpty(LHS);
>> +  bool RHSEmpty = isDenseMapKeyEmpty(RHS);
>> +  if (LHSEmpty || RHSEmpty)
>> +return LHSEmpty && RHSEmpty;
>> +
>> +  bool LHSTombstone = isDenseMapKeyTombstone(LHS);
>> +  bool RHSTombstone = isDenseMapKeyTombstone(RHS);
>> +  if (LHSTombstone || RHSTombstone)
>> +return LHSTombstone && RHSTombstone;
>> +
>> +  return None;
>> +}
>> +
>>  template<>
>>  struct DenseMapInfo {
>>using ArrayInfo = llvm::DenseMapInfo>;
>> -  using IdentInfo = llvm::DenseMapInfo;
>>static DecompositionDeclName getEmptyKey() {
>>  return {ArrayInfo::getEmptyKey()};
>>}
>> @@ -88,10 +113,10 @@ struct DenseMapInfo>  return llvm::hash_combine_range(Key.begin(), Key.end());
>>}
>>static bool isEqual(Decomposit

[PATCH] D67249: [Modules][PCH] Hash input files content

2019-09-06 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno marked 2 inline comments as done.
bruno added a comment.



> Nice! Are you planning to address the FIXME's in a later update of this patch?

The FIXME's are just replaying what the code around does, both error dropping 
and `FileEntryRef` are recent changes that didn't make all the way through yet. 
I should help improving that at some point cause it will overall be good for 
modules, but those changes are orthogonal to this patch.




Comment at: clang/lib/Serialization/ASTWriter.cpp:1767
   bool IsTopLevelModuleMap;
+  uint32_t ContentHash[2];
 };

aprantl wrote:
> Why is this not a uint64_t?
Serializing a `uint64_t` directly instead of two `uint32_t` gives me a slightly 
bigger final cache. One could argue that the value is negligible (+800 bytes 
for a 40MB cache), but here's the rationale :)



Comment at: clang/test/Modules/validate-file-content.m:14
+// RUN: %clang_cc1 -emit-pch -fmodules-cache-path=%t/cache -fmodules 
-fimplicit-module-maps -o %t/a.pch -I %t -x objective-c-header %t/a.h 
-fvalidate-ast-input-files-content
+// RUN: touch -m -a -A 01 %t/m.h
+// RUN: %clang_cc1 -fsyntax-only -fmodules-cache-path=%t/cache -fmodules 
-fimplicit-module-maps -I %t -include-pch %t/a.pch %s -verify 
-fvalidate-ast-input-files-content

aprantl wrote:
> Are there other tests that use touch and file timestamps in general? I wonder 
> if this could cause random issues when building on NFS or filesystems with a 
> really low timestamp granularity. I don't have a better suggestion either 
> since the mtime is part of the code being tested here.
> Are there other tests that use touch and file timestamps in general?

Yes, I found quite a few around the tests. However, I just tested `touch -m -a 
-A 01` on linux and it seems that `-A` isn't supported, maybe I'll just change 
the entire mtime for some time in the future, that's likely more portable.

> I wonder if this could cause random issues when building on NFS or 
> filesystems with a really low timestamp granularity. I don't have a better 
> suggestion either since the mtime is part of the code being tested here.

Right, perhaps changing the mtime completely might help here.





Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67249



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


[PATCH] D65182: [analyzer] Add fix-it hint support.

2019-09-06 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ marked an inline comment as done.
NoQ added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:343
+  /// to produce a good fix-it hint for most path-sensitive warnings.
+  void addFixItHint(const FixItHint &F) {
+Fixits.push_back(F);

gribozavr wrote:
> Are these fix-its notionally attached to the primary diagnostic itself?
Yup. I'll update the comment.


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

https://reviews.llvm.org/D65182



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


[PATCH] D65182: [analyzer] Add fix-it hint support.

2019-09-06 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ marked an inline comment as done.
NoQ added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:491
+   ArrayRef Ranges = None,
+   ArrayRef Fixits = None);
 

gribozavr wrote:
> NoQ wrote:
> > gribozavr wrote:
> > > I'm not sure if this is the right model for fixits. Fixits are usually 
> > > associated with a message that explains what the fixit does. Only in the 
> > > unusual case where Clang or ClangTidy is very confident that the fixit is 
> > > correct, it is attached to the warning. Most commonly, fixits are 
> > > attached to notes.
> > > 
> > > Also, for IDE support, it would be really nice if we could provide short 
> > > descriptions of edits themselves (e.g., "replace 'virtual' with 
> > > 'override") that can be displayed to the user instead of the diff when 
> > > possible -- right now we don't and tools using ClangTidy have to use a 
> > > subpar UI because of that. For example, when we show UI for fixing a 
> > > warning, displaying the complete diff is too much; a concise description 
> > > would be a lot better.
> > > Fixits are usually associated with a message that explains what the fixit 
> > > does. Only in the unusual case where Clang or ClangTidy is very confident 
> > > that the fixit is correct, it is attached to the warning.
> > 
> > Wait, you guys already have fixits attached to notes? Then, yeah, i need to 
> > support this.
> > 
> > > Also, for IDE support, it would be really nice if we could provide short 
> > > descriptions of edits themselves (e.g., "replace 'virtual' with 
> > > 'override") that can be displayed to the user instead of the diff when 
> > > possible -- right now we don't and tools using ClangTidy have to use a 
> > > subpar UI because of that.
> > 
> > Mmm, interesting. I've seen this IDE of ours autogenerate such messages as 
> > "replace '`$code_in_removed_range`' with '`$inserted_code`'" (while also 
> > combining multiple parts of the fixit into a single replacement under the 
> > hood) and it looked quite bearable most of the time and i silently assumed 
> > that everybody does the same thing.
> > 
> > I agree that a high-level description of a fixit is nice to have. But given 
> > that you're attaching fixits to notes, isn't the text of the note text 
> > itself sufficient? E.g.:
> > - warning: variable may be used uninitialized here
> > - note: initialize 'x' here to suppress the warning
> >   - fixit: add ' = 0' after 'x'
> > Wait, you guys already have fixits attached to notes? Then, yeah, i need to 
> > support this.
> 
> Yes, fixits are attached to notes in Clang and ClangTidy.
> 
> > Mmm, interesting. I've seen this IDE of ours autogenerate such messages as 
> > "replace '$code_in_removed_range' with '$inserted_code'" (while also 
> > combining multiple parts of the fixit into a single replacement under the 
> > hood) and it looked quite bearable most of the time and i silently assumed 
> > that everybody does the same thing.
> 
> We are doing the same thing, however, it only works well when the edit text 
> is meaningful. For example, a hypothetical "replace const with constexpr" 
> edit looks readable. However, "insert '(*' and insert ')'" does not read 
> well, "dereference the pointer" would be better.
> 
> > I agree that a high-level description of a fixit is nice to have. But given 
> > that you're attaching fixits to notes, isn't the text of the note text 
> > itself sufficient? E.g.:
> 
> Often yes, however not always. Also, fixits can be attached to warnings 
> themselves. For example:
> 
> warning: #includes are not sorted according to the style guide
> attached fixit: ,  different order>
I see, thanks! It sounds like we might want to extend the `FixItHint` class 
itself to include an optional note.


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

https://reviews.llvm.org/D65182



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


[PATCH] D64671: [clang-tidy] New check: misc-init-local-variables

2019-09-06 Thread Jussi Pakkanen via Phabricator via cfe-commits
jpakkane updated this revision to Diff 219162.
jpakkane added a comment.

Added documentation. Well, actually just swiped it from 
abseil-string-find-startswith.


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

https://reviews.llvm.org/D64671

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-init-variables.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/cppcoreguidelines-init-variables.cpp

Index: clang-tools-extra/test/clang-tidy/cppcoreguidelines-init-variables.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/cppcoreguidelines-init-variables.cpp
@@ -0,0 +1,80 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables %t
+
+// Ensure that function declarations are not changed.
+void some_func(int x, double d, bool b, const char *p);
+
+// Ensure that function arguments are not changed
+int identity_function(int x) {
+  return x;
+}
+
+int do_not_modify_me;
+
+static int should_not_be_initialized;
+extern int should_not_be_initialized2;
+
+typedef struct {
+  int unaltered1;
+  int unaltered2;
+} UnusedStruct;
+
+typedef int my_int_type;
+#define MACRO_INT int
+#define FULL_DECLARATION() int macrodecl;
+
+template 
+void template_test_function() {
+  T t;
+  int uninitialized;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'uninitialized' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int uninitialized = 0;{{$}}
+}
+
+void init_unit_tests() {
+  int x;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'x' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int x = 0;{{$}}
+  my_int_type myint;
+  // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: variable 'myint' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  my_int_type myint = 0;{{$}}
+
+  MACRO_INT macroint;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: variable 'macroint' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  MACRO_INT macroint = 0;{{$}}
+  FULL_DECLARATION();
+
+  int x0 = 1, x1, x2 = 2;
+  // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: variable 'x1' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int x0 = 1, x1 = 0, x2 = 2;{{$}}
+  int y0, y1 = 1, y2;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'y0' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-MESSAGES: :[[@LINE-2]]:19: warning: variable 'y2' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int y0 = 0, y1 = 1, y2 = 0;{{$}}
+  int hasval = 42;
+
+  float f;
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: variable 'f' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  float f = NAN;{{$}}
+  float fval = 85.0;
+  double d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: variable 'd' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  double d = NAN;{{$}}
+  double dval = 99.0;
+
+  bool b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: variable 'b' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  bool b = 0;{{$}}
+  bool bval = true;
+
+  const char *ptr;
+  // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: variable 'ptr' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  const char *ptr = nullptr;{{$}}
+  const char *ptrval = "a string";
+
+  UnusedStruct u;
+
+  static int does_not_need_an_initializer;
+  extern int does_not_need_an_initializer2;
+  int parens(42);
+  int braces{42};
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -193,6 +193,7 @@
cppcoreguidelines-avoid-magic-numbers (redirects to readability-magic-numbers) 
cppcoreguidelines-c-copy-assignment-signature (redirects to misc-unconventional-assign-operator) 
cppcoreguidelines-explicit-virtual-functions (redirects to modernize-use-override) 
+   cppcoreguidelines-init-variables
cppcoreguidelines-interfaces-global-init
cppcoreguidelines-macro-usage
cppcoreguidelines-narrowing-conversions
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-init-variables.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-init-variables.rst
@@ -0,0 +1,46 @@
+.. title:: clang-tidy - cppcoreguidelines-init-vari

[PATCH] D67292: [clang-tidy] Fix bug in bugprone-use-after-move check

2019-09-06 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/bugprone-use-after-move.cpp:1198
+}
+  }
   for (int i = 0; i < 10; ++i) {

ymandel wrote:
> gribozavr wrote:
> > Unless you think it is redundant, could you also add
> > 
> > ```
> > if (A a1; A(std::move(a2)).getInt() > 0) {}
> > ```
> > 
> > Also some true positive tests would be good:
> > 
> > ```
> > if (A a1; A(std::move(a2)).getInt() > A(std::move(a2)).getInt()) {}
> > ```
> > 
> > ```
> > A a1;
> > if (A a2 = std::move(a1); A(std::move(a1)) > 0) {}
> > ```
> Done, but any idea why everything in this function is placed inside a loop?  
> Looks like its just for scoping, but then why not just a compound statement, 
> as is done above? This feels very odd.
I think it is to ensure that the checker understands the sequencing. If it 
didn't, then the loop would trigger the "moved twice" logic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67292



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


[PATCH] D67019: [analyzer] pr43179: CallDescription: Check number of parameters as well as number of arguments.

2019-09-06 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL371256: [analyzer] pr43179: Make CallDescription defensive 
against C variadic functions. (authored by dergachev, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67019?vs=218160&id=219169#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67019

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
  cfe/trunk/test/Analysis/cast-value-weird.cpp


Index: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -368,7 +368,8 @@
 
   if (CD.Flags & CDF_MaybeBuiltin) {
 return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) &&
-   (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs());
+   (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) &&
+   (!CD.RequiredParams || CD.RequiredParams <= parameters().size());
   }
 
   if (!CD.IsLookupDone) {
@@ -407,7 +408,8 @@
   return false;
   }
 
-  return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs());
+  return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs()) &&
+ (!CD.RequiredParams || CD.RequiredParams == parameters().size());
 }
 
 SVal CallEvent::getArgSVal(unsigned Index) const {
Index: cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -116,7 +116,9 @@
 // vswprintf is the wide version of vsnprintf,
 // vsprintf has no wide version
 {{"vswscanf", 3}, 2}};
-const CallDescription ValistChecker::VaStart("__builtin_va_start", 2),
+
+const CallDescription
+ValistChecker::VaStart("__builtin_va_start", /*Args=*/2, /*Params=*/1),
 ValistChecker::VaCopy("__builtin_va_copy", 2),
 ValistChecker::VaEnd("__builtin_va_end", 1);
 } // end anonymous namespace
Index: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -1064,8 +1064,19 @@
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
   Optional RequiredArgs;
+  Optional RequiredParams;
   int Flags;
 
+  // A constructor helper.
+  static Optional readRequiredParams(Optional RequiredArgs,
+ Optional RequiredParams) {
+if (RequiredParams)
+  return RequiredParams;
+if (RequiredArgs)
+  return static_cast(*RequiredArgs);
+return None;
+  }
+
 public:
   /// Constructs a CallDescription object.
   ///
@@ -1078,14 +1089,17 @@
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(int Flags, ArrayRef QualifiedName,
-  Optional RequiredArgs = None)
+  Optional RequiredArgs = None,
+  Optional RequiredParams = None)
   : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
 Flags(Flags) {}
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  Optional RequiredArgs = None)
-  : CallDescription(0, QualifiedName, RequiredArgs) {}
+  Optional RequiredArgs = None,
+  Optional RequiredParams = None)
+  : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
   /// Get the name of the function that this object matches.
   StringRef getFunctionName() const { return QualifiedName.back(); }
Index: cfe/trunk/test/Analysis/cast-value-weird.cpp
===
--- cfe/trunk/test/Analysis/cast-value-weird.cpp
+++ cfe/trunk/test/Analysis/cast-value-weird.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,apiModeling -verify %s
+
+// expected-no-diagnostics
+
+namespace llvm {
+template 
+void cast(...);
+void a() { cast(int()); } // no-crash
+} // namespace llvm


Index: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -368,7 +368,8 @@
 
   if (CD.Flags & CDF_MaybeBuiltin) {
 retu

r371256 - [analyzer] pr43179: Make CallDescription defensive against C variadic functions.

2019-09-06 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Sep  6 13:55:24 2019
New Revision: 371256

URL: http://llvm.org/viewvc/llvm-project?rev=371256&view=rev
Log:
[analyzer] pr43179: Make CallDescription defensive against C variadic functions.

Most functions that our checkers react upon are not C-style variadic functions,
and therefore they have as many actual arguments as they have formal parameters.

However, it's not impossible to define a variadic function with the same name.
This will crash any checker that relies on CallDescription to check the number
of arguments but silently assumes that the number of parameters is the same.

Change CallDescription to check both the number of arguments and the number of
parameters by default.

If we're intentionally trying to match variadic functions, allow specifying
arguments and parameters separately (possibly omitting any of them).
For now we only have one CallDescription which would make use of those,
namely __builtin_va_start itself.

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

Added:
cfe/trunk/test/Analysis/cast-value-weird.cpp
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h?rev=371256&r1=371255&r2=371256&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h Fri 
Sep  6 13:55:24 2019
@@ -1064,8 +1064,19 @@ class CallDescription {
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
   Optional RequiredArgs;
+  Optional RequiredParams;
   int Flags;
 
+  // A constructor helper.
+  static Optional readRequiredParams(Optional RequiredArgs,
+ Optional RequiredParams) {
+if (RequiredParams)
+  return RequiredParams;
+if (RequiredArgs)
+  return static_cast(*RequiredArgs);
+return None;
+  }
+
 public:
   /// Constructs a CallDescription object.
   ///
@@ -1078,14 +1089,17 @@ public:
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(int Flags, ArrayRef QualifiedName,
-  Optional RequiredArgs = None)
+  Optional RequiredArgs = None,
+  Optional RequiredParams = None)
   : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
 Flags(Flags) {}
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  Optional RequiredArgs = None)
-  : CallDescription(0, QualifiedName, RequiredArgs) {}
+  Optional RequiredArgs = None,
+  Optional RequiredParams = None)
+  : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
   /// Get the name of the function that this object matches.
   StringRef getFunctionName() const { return QualifiedName.back(); }

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp?rev=371256&r1=371255&r2=371256&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp Fri Sep  6 13:55:24 
2019
@@ -116,7 +116,9 @@ const SmallVectorhttp://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=371256&r1=371255&r2=371256&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Fri Sep  6 13:55:24 2019
@@ -368,7 +368,8 @@ bool CallEvent::isCalled(const CallDescr
 
   if (CD.Flags & CDF_MaybeBuiltin) {
 return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) &&
-   (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs());
+   (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) &&
+   (!CD.RequiredParams || CD.RequiredParams <= parameters().size());
   }
 
   if (!CD.IsLookupDone) {
@@ -407,7 +408,8 @@ bool CallEvent::isCalled(const CallDescr
   return false;
   }
 
-  return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs());
+  return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs()) &&
+ (!CD.RequiredParams || CD.RequiredParams == parameters().size());
 }
 
 SVal CallEvent::getArgSVal(unsigned Index)

[PATCH] D67249: [Modules][PCH] Hash input files content

2019-09-06 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno updated this revision to Diff 219166.
bruno added a comment.

Update testcase to use a more portable version of `touch`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67249

Files:
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/HeaderSearchOptions.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/validate-file-content.m
  clang/test/PCH/validate-file-content.m

Index: clang/test/PCH/validate-file-content.m
===
--- /dev/null
+++ clang/test/PCH/validate-file-content.m
@@ -0,0 +1,29 @@
+// REQUIRES: shell
+//
+// Check driver works
+// RUN: %clang -x objective-c-header -fsyntax-only -fpch-validate-input-files-content %t/a.h -### 2>&1 | FileCheck --check-prefix=CHECK-CC1 %s
+// CHECK-CC1: -fvalidate-ast-input-files-content
+//
+// PCH only: Test that a mtime mismatch without content change is fine
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: %clang_cc1 -emit-pch -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: %clang_cc1 -fsyntax-only -I %t -include-pch %t/a.pch %s -verify -fvalidate-ast-input-files-content
+//
+// PCH only: Test that a mtime mismatch with content change
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: %clang_cc1 -emit-pch -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: echo '// m.x' > %t/m.h
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: not %clang_cc1 -fsyntax-only -I %t -include-pch %t/a.pch %s -fvalidate-ast-input-files-content 2> %t/stderr
+// RUN: FileCheck %s < %t/stderr
+//
+// CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed
+// CHECK: please rebuild precompiled header '[[A_PCH]]'
+// expected-no-diagnostics
Index: clang/test/Modules/validate-file-content.m
===
--- /dev/null
+++ clang/test/Modules/validate-file-content.m
@@ -0,0 +1,33 @@
+// REQUIRES: shell
+//
+// Check driver works
+// RUN: %clang -fmodules -fsyntax-only -fmodules-validate-input-files-content %s -### 2>&1 | FileCheck --check-prefix=CHECK-CC1 %s
+// CHECK-CC1: -fvalidate-ast-input-files-content
+//
+// PCH+Modules: Test that a mtime mismatch without content change is fine
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: echo 'module m { header "m.h" }' > %t/module.modulemap
+// RUN: %clang_cc1 -emit-pch -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: touch -m -a -t 20290101 /tmp/x %t/m.h
+// RUN: %clang_cc1 -fsyntax-only -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -I %t -include-pch %t/a.pch %s -verify -fvalidate-ast-input-files-content
+//
+// PCH+Modules: Test that a mtime mismatch with content change
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: echo 'module m { header "m.h" }' > %t/module.modulemap
+// RUN: %clang_cc1 -emit-pch -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: echo '// m.x' > %t/m.h
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: not %clang_cc1 -fsyntax-only -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -I %t -include-pch %t/a.pch %s -fvalidate-ast-input-files-content 2> %t/stderr
+// RUN: FileCheck %s < %t/stderr
+//
+// CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed
+// CHECK: '[[M_H]]' required by '[[M_PCM:.*[/\\]m.*\.pcm]]'
+// CHECK: '[[M_PCM]]' required by '[[A_PCH]]'
+// CHECK: please rebuild precompiled header '[[A_PCH]]'
+// expected-no-diagnostics
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1098,6 +1098,7 @@
 
   BLOCK(INPUT_FILES_BLOCK);
   RECORD(INPUT_FILE);
+  RECORD(INPUT_FILE_HASH);
 
   // AST Top-Level Block.
   BLOCK(AST_BLOCK);
@@ -1763,6 +1764,7 @@
   bool IsTransient;
   bool BufferOverridden;
   bool IsTopLevelModuleMap;
+  uint32_t C

[PATCH] D67249: [Modules][PCH] Hash input files content

2019-09-06 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno updated this revision to Diff 219168.
bruno added a comment.

Remove pasto from one of the testcases


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67249

Files:
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/HeaderSearchOptions.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/validate-file-content.m
  clang/test/PCH/validate-file-content.m

Index: clang/test/PCH/validate-file-content.m
===
--- /dev/null
+++ clang/test/PCH/validate-file-content.m
@@ -0,0 +1,29 @@
+// REQUIRES: shell
+//
+// Check driver works
+// RUN: %clang -x objective-c-header -fsyntax-only -fpch-validate-input-files-content %t/a.h -### 2>&1 | FileCheck --check-prefix=CHECK-CC1 %s
+// CHECK-CC1: -fvalidate-ast-input-files-content
+//
+// PCH only: Test that a mtime mismatch without content change is fine
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: %clang_cc1 -emit-pch -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: %clang_cc1 -fsyntax-only -I %t -include-pch %t/a.pch %s -verify -fvalidate-ast-input-files-content
+//
+// PCH only: Test that a mtime mismatch with content change
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: %clang_cc1 -emit-pch -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: echo '// m.x' > %t/m.h
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: not %clang_cc1 -fsyntax-only -I %t -include-pch %t/a.pch %s -fvalidate-ast-input-files-content 2> %t/stderr
+// RUN: FileCheck %s < %t/stderr
+//
+// CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed
+// CHECK: please rebuild precompiled header '[[A_PCH]]'
+// expected-no-diagnostics
Index: clang/test/Modules/validate-file-content.m
===
--- /dev/null
+++ clang/test/Modules/validate-file-content.m
@@ -0,0 +1,33 @@
+// REQUIRES: shell
+//
+// Check driver works
+// RUN: %clang -fmodules -fsyntax-only -fmodules-validate-input-files-content %s -### 2>&1 | FileCheck --check-prefix=CHECK-CC1 %s
+// CHECK-CC1: -fvalidate-ast-input-files-content
+//
+// PCH+Modules: Test that a mtime mismatch without content change is fine
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: echo 'module m { header "m.h" }' > %t/module.modulemap
+// RUN: %clang_cc1 -emit-pch -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: %clang_cc1 -fsyntax-only -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -I %t -include-pch %t/a.pch %s -verify -fvalidate-ast-input-files-content
+//
+// PCH+Modules: Test that a mtime mismatch with content change
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo '// m.h' > %t/m.h
+// RUN: echo '#include "m.h"' > %t/a.h
+// RUN: echo 'module m { header "m.h" }' > %t/module.modulemap
+// RUN: %clang_cc1 -emit-pch -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -o %t/a.pch -I %t -x objective-c-header %t/a.h -fvalidate-ast-input-files-content
+// RUN: echo '// m.x' > %t/m.h
+// RUN: touch -m -a -t 20290101 %t/m.h
+// RUN: not %clang_cc1 -fsyntax-only -fmodules-cache-path=%t/cache -fmodules -fimplicit-module-maps -I %t -include-pch %t/a.pch %s -fvalidate-ast-input-files-content 2> %t/stderr
+// RUN: FileCheck %s < %t/stderr
+//
+// CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed
+// CHECK: '[[M_H]]' required by '[[M_PCM:.*[/\\]m.*\.pcm]]'
+// CHECK: '[[M_PCM]]' required by '[[A_PCH]]'
+// CHECK: please rebuild precompiled header '[[A_PCH]]'
+// expected-no-diagnostics
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1098,6 +1098,7 @@
 
   BLOCK(INPUT_FILES_BLOCK);
   RECORD(INPUT_FILE);
+  RECORD(INPUT_FILE_HASH);
 
   // AST Top-Level Block.
   BLOCK(AST_BLOCK);
@@ -1763,6 +1764,7 @@
   bool IsTransient;
   bool BufferOverridden;
   bool IsTopLevelModuleMap;
+  uint32_t ContentHash[2];
 };
 
 } //

r371257 - [analyzer] Add minimal support for fix-it hints.

2019-09-06 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Sep  6 13:55:29 2019
New Revision: 371257

URL: http://llvm.org/viewvc/llvm-project?rev=371257&view=rev
Log:
[analyzer] Add minimal support for fix-it hints.

Allow attaching fixit hints to Static Analyzer BugReports.

Fixits are attached either to the bug report itself or to its notes
(path-sensitive event notes or path-insensitive extra notes).

Add support for fixits in text output (including the default text output that
goes without notes, as long as the fixit "belongs" to the warning).

Add support for fixits in the plist output mode.

Implement a fixit for the path-insensitive DeadStores checker. Only dead
initialization warning is currently covered.

Implement a fixit for the path-sensitive VirtualCall checker when the virtual
method is not pure virtual (in this case the "fix" is to suppress the warning
by qualifying the call).

Both fixits are under an off-by-default flag for now, because they
require more careful testing.

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

Added:
cfe/trunk/test/Analysis/virtualcall-fixits.cpp
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
cfe/trunk/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
cfe/trunk/test/Analysis/analyzer-config.c
cfe/trunk/test/Analysis/dead-stores.c
cfe/trunk/test/Analysis/edges-new.mm
cfe/trunk/test/Analysis/objc-arc.m
cfe/trunk/test/Analysis/plist-output.m

Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=371257&r1=371256&r2=371257&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Fri Sep  6 
13:55:29 2019
@@ -564,6 +564,11 @@ def VirtualCallChecker : Checker<"Virtua
   HelpText<"Check virtual function calls during construction/destruction">,
   CheckerOptions<[
 CmdLineOption,
+CmdLineOption
+  Released>,
+CmdLineOption
   ]>,
   Documentation;
 

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def?rev=371257&r1=371256&r2=371257&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def Fri Sep  6 
13:55:29 2019
@@ -300,6 +300,14 @@ ANALYZER_OPTION(bool, ShouldTrackConditi
 "Whether to place an event at each tracked condition.",
 false)
 
+ANALYZER_OPTION(bool, ShouldEmitFixItHintsAsRemarks, "fixits-as-remarks",
+"Emit fix-it hints as remarks for testing purposes",
+false)
+
+//===--===//
+// Unsigned analyzer options.
+//===--===//
+
 ANALYZER_OPTION(unsigned, CTUImportThreshold, "ctu-import-threshold",
 "The maximal amount of translation units that is considered "
 "for import when inlining functions during CTU analysis. "
@@ -308,10 +316,6 @@ ANALYZER_OPTION(unsigned, CTUImportThres
 "various translation units.",
 100u)
 
-//===--===//
-// Unsinged analyzer options.
-//===--===//
-
 ANALYZER_OPTION(
 unsigned, AlwaysInlineSize, "ipa-always-inline-size",
 "The size of the functions (in basic blocks), which should be considered "

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h?rev=371257&r1=371256&r2=371257&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h Fri 
Sep  6 13:55:29 2019
@@ -96,6 +96,7 @@ protected:
   SmallVector Ranges;
   const SourceRange ErrorNodeRange;
   NoteList Notes;
+  SmallVector Fixits;
 
   /// A (stack of) a

[PATCH] D65182: [analyzer] Add fix-it hint support.

2019-09-06 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL371257: [analyzer] Add minimal support for fix-it hints. 
(authored by dergachev, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65182?vs=218575&id=219170#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65182

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
  cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
  cfe/trunk/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  cfe/trunk/test/Analysis/analyzer-config.c
  cfe/trunk/test/Analysis/dead-stores.c
  cfe/trunk/test/Analysis/edges-new.mm
  cfe/trunk/test/Analysis/objc-arc.m
  cfe/trunk/test/Analysis/plist-output.m
  cfe/trunk/test/Analysis/virtualcall-fixits.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -300,6 +300,14 @@
 "Whether to place an event at each tracked condition.",
 false)
 
+ANALYZER_OPTION(bool, ShouldEmitFixItHintsAsRemarks, "fixits-as-remarks",
+"Emit fix-it hints as remarks for testing purposes",
+false)
+
+//===--===//
+// Unsigned analyzer options.
+//===--===//
+
 ANALYZER_OPTION(unsigned, CTUImportThreshold, "ctu-import-threshold",
 "The maximal amount of translation units that is considered "
 "for import when inlining functions during CTU analysis. "
@@ -308,10 +316,6 @@
 "various translation units.",
 100u)
 
-//===--===//
-// Unsinged analyzer options.
-//===--===//
-
 ANALYZER_OPTION(
 unsigned, AlwaysInlineSize, "ipa-always-inline-size",
 "The size of the functions (in basic blocks), which should be considered "
Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
@@ -393,6 +393,7 @@
   StringRef Tag;
 
   std::vector ranges;
+  std::vector fixits;
 
 protected:
   PathDiagnosticPiece(StringRef s, Kind k, DisplayHint hint = Below);
@@ -437,9 +438,16 @@
 ranges.push_back(SourceRange(B,E));
   }
 
+  void addFixit(FixItHint F) {
+fixits.push_back(F);
+  }
+
   /// Return the SourceRanges associated with this PathDiagnosticPiece.
   ArrayRef getRanges() const { return ranges; }
 
+  /// Return the fix-it hints associated with this PathDiagnosticPiece.
+  ArrayRef getFixits() const { return fixits; }
+
   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
 
   void setAsLastInMainSourceFile() {
Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -96,6 +96,7 @@
   SmallVector Ranges;
   const SourceRange ErrorNodeRange;
   NoteList Notes;
+  SmallVector Fixits;
 
   /// A (stack of) a set of symbols that are registered with this
   /// report as being "interesting", and thus used to help decide which
@@ -280,20 +281,17 @@
   /// allows you to specify where exactly in the auto-generated path diagnostic
   /// the extra note should appear.
   void addNote(StringRef Msg, const PathDiagnosticLocation &Pos,
-   ArrayRef Ranges) {
+   ArrayRef Ranges = {},
+   ArrayRef Fixits = {}) {
 auto P = std::make_shared(Pos, Msg);
 
 for (const auto &R : Ranges)
   P->addRange(R);
 
-Notes.push_back(std::move(P));
-  }
+for (const auto &F : Fixits)
+  P->addFixit(F);
 
-  // FIXME: Instead of making an override, we could have default-initialized
-  // Ranges with {}, however it crashes the MSVC 2013 compiler.
-  void addNote(StringRef Msg, const PathDiagnosticLocation &Pos) {
-std::vector Ranges;

[PATCH] D64671: [clang-tidy] New check: misc-init-local-variables

2019-09-06 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

It'll be reasonable to get IncludeStyle default from .clang-format.




Comment at: clang-tools-extra/docs/ReleaseNotes.rst:71
+
+- New :doc:`cppcoreguidelines-init-variables
+  ` check.

Please sort new checks list alphabetically.


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

https://reviews.llvm.org/D64671



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


[PATCH] D67253: clang-misexpect: a standalone tool for verifying the use of __builtin_expect with PGO data

2019-09-06 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 219171.
paulkirth added a comment.

Address code review


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67253

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/clang-misexpect/CMakeLists.txt
  clang-tools-extra/clang-misexpect/ClangMisExpect.cpp
  clang-tools-extra/clang-misexpect/ClangMisExpect.h
  clang-tools-extra/clang-misexpect/tool/CMakeLists.txt
  clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp
  clang/cmake/caches/Fuchsia-stage2.cmake
  llvm/lib/Transforms/Utils/MisExpect.cpp

Index: llvm/lib/Transforms/Utils/MisExpect.cpp
===
--- llvm/lib/Transforms/Utils/MisExpect.cpp
+++ llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -43,7 +43,8 @@
 static cl::opt PGOWarnMisExpect(
 "pgo-warn-misexpect", cl::init(false), cl::Hidden,
 cl::desc("Use this option to turn on/off "
- "warnings about incorrect usage of llvm.expect intrinsics."));
+ "warnings about incorrect usage of llvm.expect intrinsics."),
+cl::ZeroOrMore);
 
 } // namespace llvm
 
Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -207,6 +207,7 @@
   LTO
   clang-apply-replacements
   clang-doc
+  clang-misexpect
   clang-format
   clang-resource-headers
   clang-include-fixer
Index: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp
@@ -0,0 +1,121 @@
+//===-- ClangMisExpectMain.cpp - ClangMisexpect -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements the main function for clang misexpect. It uses a
+// libTooling exectutor to check each file in the compiler_commands.json against
+// a provided PGO profile. When profile counters disagree with the compiler's
+// threshold values for likely and unlike branches clang-misexpect will issue a
+// diagnostic message.
+//
+//===--===//
+
+#include "../ClangMisExpect.h"
+#include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Tooling/AllTUsExecution.h"
+#include "clang/Tooling/ArgumentsAdjusters.h"
+#include "clang/Tooling/CommonOptionsParser.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Signals.h"
+#include 
+
+using namespace clang;
+using namespace clang::tooling;
+using namespace clang::misexpect;
+using Path = std::string;
+
+static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
+static llvm::cl::OptionCategory
+ClangMisExpectCategory("clang-misexpect options");
+
+static llvm::cl::opt ProfileDir(
+"profile-dir",
+llvm::cl::desc(
+"Specify a path to the profile data to use during validation"),
+llvm::cl::cat(ClangMisExpectCategory));
+
+static llvm::cl::opt ProfFormat(
+"profile-format",
+llvm::cl::desc(
+"Specify the format of the profile data used during validation"),
+llvm::cl::init(Clang),
+llvm::cl::values(clEnumValN(Clang, "clang", "Clang Instrumentation"),
+ clEnumValN(IR, "llvm", "IR Instrumentation"),
+ clEnumValN(CSIR, "csllvm",
+"Context sensitive IR Instrumentation"),
+ clEnumValN(Sample, "sample", "Sampling Instrumentation")),
+llvm::cl::cat(ClangMisExpectCategory));
+
+int main(int argc, const char **argv) {
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+
+  ExecutorName.setInitialValue("all-TUs");
+  // ExecutorName.setInitialValue("standalone");
+
+  auto &OS = llvm::errs();
+  auto Executor =
+  createExecutorFromCommandLineArgs(argc, argv, ClangMisExpectCategory);
+
+  if (!Executor) {
+OS << "Failed to create executor --- "
+   << llvm::toString(Executor.takeError()) << "\n";
+return 1;
+  }
+
+  OS << "Executor Created ... \n";
+
+  CommonOptionsParser OptionsParser(argc, argv, ClangMisExpectCategory,
+llvm::cl::ZeroOrMore);
+
+  OS << "Starting execution ... \n";
+  auto ArgAdjuster = getStripPluginsAdjuster();
+  auto StripProfileWarnings = [](const CommandLineArguments &Args,
+ StringRef /*unused*/ Unused) {
+CommandLineArgum

[PATCH] D59637: [analyzer] Use the custom propagation rules and sinks in GenericTaintChecker

2019-09-06 Thread Borsik Gábor via Phabricator via cfe-commits
boga95 updated this revision to Diff 219172.
boga95 marked 7 inline comments as done.

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

https://reviews.llvm.org/D59637

Files:
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/test/Analysis/taint-generic.c

Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -338,3 +338,45 @@
   if (i < rhs)
 *(volatile int *) 0; // no-warning
 }
+
+
+// Test configuration
+int mySource1();
+void mySource2(int*);
+void myScanf(const char*, ...);
+int myPropagator(int, int*);
+int mySnprintf(char*, size_t, const char*, ...);
+void mySink(int, int, int);
+
+void testConfigurationSources1() {
+  int x = mySource1();
+  Buffer[x] = 1; // expected-warning {{Out of bound memory access }}
+}
+
+void testConfigurationSources2() {
+  int x;
+  mySource2(&x);
+  Buffer[x] = 1; // expected-warning {{Out of bound memory access }}
+}
+
+void testConfigurationSources3() {
+  int x, y;
+  myScanf("%d %d", &x, &y);
+  Buffer[y] = 1; // expected-warning {{Out of bound memory access }}
+}
+
+void testConfigurationPropagation() {
+  int x = mySource1();
+  int y;
+  myPropagator(x, &y);
+  Buffer[y] = 1; // expected-warning {{Out of bound memory access }}
+}
+
+void testConfigurationSinks() {
+  int x = mySource1();
+  mySink(x, 1, 2);
+  // expected-warning@-1 {{Untrusted data is passed to a user-defined sink}}
+  mySink(1, x, 2); // no-warning
+  mySink(1, 2, x);
+  // expected-warning@-1 {{Untrusted data is passed to a user-defined sink}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -115,27 +115,44 @@
   static Optional getPointedToSVal(CheckerContext &C, const Expr *Arg);
 
   /// Check for CWE-134: Uncontrolled Format String.
-  static const char MsgUncontrolledFormatString[];
+  static constexpr llvm::StringLiteral MsgUncontrolledFormatString =
+  "Untrusted data is used as a format string "
+  "(CWE-134: Uncontrolled Format String)";
   bool checkUncontrolledFormatString(const CallExpr *CE,
  CheckerContext &C) const;
 
   /// Check for:
   /// CERT/STR02-C. "Sanitize data passed to complex subsystems"
   /// CWE-78, "Failure to Sanitize Data into an OS Command"
-  static const char MsgSanitizeSystemArgs[];
+  static constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
+  "Untrusted data is passed to a system call "
+  "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
   bool checkSystemCall(const CallExpr *CE, StringRef Name,
CheckerContext &C) const;
 
   /// Check if tainted data is used as a buffer size ins strn.. functions,
   /// and allocators.
-  static const char MsgTaintedBufferSize[];
+  static constexpr llvm::StringLiteral MsgTaintedBufferSize =
+  "Untrusted data is used to specify the buffer size "
+  "(CERT/STR31-C. Guarantee that storage for strings has sufficient space "
+  "for character data and the null terminator)";
   bool checkTaintedBufferSize(const CallExpr *CE, const FunctionDecl *FDecl,
   CheckerContext &C) const;
 
+  /// Check if tainted data is used as a custom sink's parameter.
+  static constexpr llvm::StringLiteral MsgCustomSink =
+  "Untrusted data is passed to a user-defined sink";
+  bool checkCustomSinks(const CallExpr *CE, StringRef Name,
+CheckerContext &C) const;
+
   /// Generate a report if the expression is tainted or points to tainted data.
-  bool generateReportIfTainted(const Expr *E, const char Msg[],
+  bool generateReportIfTainted(const Expr *E, StringRef Msg,
CheckerContext &C) const;
 
+  struct TaintPropagationRule;
+  using NameRuleMap = llvm::StringMap;
+  using NameArgMap = llvm::StringMap;
+
   /// A struct used to specify taint propagation rules for a function.
   ///
   /// If any of the possible taint source arguments is tainted, all of the
@@ -175,7 +192,8 @@
 
 /// Get the propagation rule for a given function.
 static TaintPropagationRule
-getTaintPropagationRule(const FunctionDecl *FDecl, StringRef Name,
+getTaintPropagationRule(const NameRuleMap &CustomPropagations,
+const FunctionDecl *FDecl, StringRef Name,
 CheckerContext &C);
 
 void addSrcArg(unsigned A) { SrcArgs.push_back(A); }
@@ -211,9 +229,6 @@
CheckerContext &C);
   };
 
-  using NameRuleMap = llvm::StringMap;
-  using NameArgMap = llvm::StringMap;
-
   /// Defines a map between the propagation function's name and
   /// TaintPropagationRule.
   NameRuleMap CustomPropagations;
@@ -2

[PATCH] D67253: clang-misexpect: a standalone tool for verifying the use of __builtin_expect with PGO data

2019-09-06 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 219173.
paulkirth added a comment.

Remove commented out code


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

https://reviews.llvm.org/D67253

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/clang-misexpect/CMakeLists.txt
  clang-tools-extra/clang-misexpect/ClangMisExpect.cpp
  clang-tools-extra/clang-misexpect/ClangMisExpect.h
  clang-tools-extra/clang-misexpect/tool/CMakeLists.txt
  clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp
  clang/cmake/caches/Fuchsia-stage2.cmake
  llvm/lib/Transforms/Utils/MisExpect.cpp

Index: llvm/lib/Transforms/Utils/MisExpect.cpp
===
--- llvm/lib/Transforms/Utils/MisExpect.cpp
+++ llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -43,7 +43,8 @@
 static cl::opt PGOWarnMisExpect(
 "pgo-warn-misexpect", cl::init(false), cl::Hidden,
 cl::desc("Use this option to turn on/off "
- "warnings about incorrect usage of llvm.expect intrinsics."));
+ "warnings about incorrect usage of llvm.expect intrinsics."),
+cl::ZeroOrMore);
 
 } // namespace llvm
 
Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -207,6 +207,7 @@
   LTO
   clang-apply-replacements
   clang-doc
+  clang-misexpect
   clang-format
   clang-resource-headers
   clang-include-fixer
Index: clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-misexpect/tool/ClangMisExpectMain.cpp
@@ -0,0 +1,120 @@
+//===-- ClangMisExpectMain.cpp - ClangMisexpect -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements the main function for clang misexpect. It uses a
+// libTooling exectutor to check each file in the compiler_commands.json against
+// a provided PGO profile. When profile counters disagree with the compiler's
+// threshold values for likely and unlike branches clang-misexpect will issue a
+// diagnostic message.
+//
+//===--===//
+
+#include "../ClangMisExpect.h"
+#include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Tooling/AllTUsExecution.h"
+#include "clang/Tooling/ArgumentsAdjusters.h"
+#include "clang/Tooling/CommonOptionsParser.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Signals.h"
+#include 
+
+using namespace clang;
+using namespace clang::tooling;
+using namespace clang::misexpect;
+using Path = std::string;
+
+static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
+static llvm::cl::OptionCategory
+ClangMisExpectCategory("clang-misexpect options");
+
+static llvm::cl::opt ProfileDir(
+"profile-dir",
+llvm::cl::desc(
+"Specify a path to the profile data to use during validation"),
+llvm::cl::cat(ClangMisExpectCategory));
+
+static llvm::cl::opt ProfFormat(
+"profile-format",
+llvm::cl::desc(
+"Specify the format of the profile data used during validation"),
+llvm::cl::init(Clang),
+llvm::cl::values(clEnumValN(Clang, "clang", "Clang Instrumentation"),
+ clEnumValN(IR, "llvm", "IR Instrumentation"),
+ clEnumValN(CSIR, "csllvm",
+"Context sensitive IR Instrumentation"),
+ clEnumValN(Sample, "sample", "Sampling Instrumentation")),
+llvm::cl::cat(ClangMisExpectCategory));
+
+int main(int argc, const char **argv) {
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
+
+  ExecutorName.setInitialValue("all-TUs");
+
+  auto &OS = llvm::errs();
+  auto Executor =
+  createExecutorFromCommandLineArgs(argc, argv, ClangMisExpectCategory);
+
+  if (!Executor) {
+OS << "Failed to create executor --- "
+   << llvm::toString(Executor.takeError()) << "\n";
+return 1;
+  }
+
+  OS << "Executor Created ... \n";
+
+  CommonOptionsParser OptionsParser(argc, argv, ClangMisExpectCategory,
+llvm::cl::ZeroOrMore);
+
+  OS << "Starting execution ... \n";
+  auto ArgAdjuster = getStripPluginsAdjuster();
+  auto StripProfileWarnings = [](const CommandLineArguments &Args,
+ StringRef /*unused*/ Unused) {
+CommandLineArguments AdjustedArgs;
+std::set FilteredArgs = {"-Wprofile-instr-unprofiled",
+   

[PATCH] D64671: [clang-tidy] New check: misc-init-local-variables

2019-09-06 Thread Jussi Pakkanen via Phabricator via cfe-commits
jpakkane marked an inline comment as done.
jpakkane added a comment.

> It'll be reasonable to get IncludeStyle default from .clang-format.

I looked at existing checks and they all do the same thing as this one. In fact 
I got the code for this by directly copypasting an existing check.

Grepping for clang format in the check tree produces zero relevant matches, so 
it's unclear to me how this should be written (assuming that this is not taken 
care of automatically by utility code).




Comment at: clang-tools-extra/docs/ReleaseNotes.rst:71
+
+- New :doc:`cppcoreguidelines-init-variables
+  ` check.

Eugene.Zelenko wrote:
> Please sort new checks list alphabetically.
The list is already incorrectly alphabetized. Should I reorganize all the 
entries or just put mine in a "correct" spot (between "bugprone" and 
"linuxkernel")?


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

https://reviews.llvm.org/D64671



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


[PATCH] D67302: Configure my project to use arcanist.

2019-09-06 Thread Cong Liu via Phabricator via cfe-commits
congliu created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D67302

Files:
  clang-tools-extra/.arcconfig
  clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
  clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h
  
clang-tools-extra/docs/clang-tidy/checks/performance-inefficient-vector-operation.rst
  clang-tools-extra/test/clang-tidy/performance-inefficient-vector-operation.cpp

Index: clang-tools-extra/test/clang-tidy/performance-inefficient-vector-operation.cpp
===
--- clang-tools-extra/test/clang-tidy/performance-inefficient-vector-operation.cpp
+++ clang-tools-extra/test/clang-tidy/performance-inefficient-vector-operation.cpp
@@ -1,4 +1,7 @@
-// RUN: %check_clang_tidy %s performance-inefficient-vector-operation %t -- -format-style=llvm
+// RUN: %check_clang_tidy %s performance-inefficient-vector-operation %t -- \
+// RUN: -format-style=llvm \
+// RUN: -config='{CheckOptions: \
+// RUN:  [{key: performance-inefficient-vector-operation.EnableProto, value: 1}]}'
 
 namespace std {
 
@@ -62,6 +65,28 @@
 
 int Op(int);
 
+namespace proto2 {
+class MessageLite {};
+class Message : public MessageLite {};
+} // namespace proto2
+
+class FooProto : public proto2::Message {
+ public:
+  int *add_x();  // repeated int x;
+  void add_x(int x);
+  void mutable_x();
+  void mutable_y();
+  int add_z() const; // optional int add_z;
+};
+
+class BarProto : public proto2::Message {
+ public:
+  int *add_x();
+  void add_x(int x);
+  void mutable_x();
+  void mutable_y();
+};
+
 void f(std::vector& t) {
   {
 std::vector v0;
@@ -162,6 +187,15 @@
 }
   }
 
+  {
+FooProto foo;
+// CHECK-FIXES: foo.mutable_x()->Reserve(5);
+for (int i = 0; i < 5; i++) {
+  foo.add_x(i);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'add_x' is called inside a loop; consider pre-allocating the repeated field capacity before the loop
+}
+  }
+
   //  Non-fixed Cases 
   {
 std::vector z0;
@@ -274,4 +308,54 @@
   z12.push_back(e);
 }
   }
+
+  {
+FooProto foo;
+foo.mutable_x();
+// CHECK-FIXES-NOT: foo.mutable_x->Reserve(5);
+for (int i = 0; i < 5; i++) {
+  foo.add_x(i);
+}
+  }
+  {
+FooProto foo;
+// CHECK-FIXES-NOT: foo.mutable_x->Reserve(5);
+for (int i = 0; i < 5; i++) {
+  foo.add_x(i);
+  foo.add_x(i);
+}
+  }
+  {
+FooProto foo;
+// CHECK-FIXES-NOT: foo.mutable_x->Reserve(5);
+foo.add_x(-1);
+for (int i = 0; i < 5; i++) {
+  foo.add_x(i);
+}
+  }
+  {
+FooProto foo;
+BarProto bar;
+bar.mutable_x();
+// CHECK-FIXES-NOT: foo.mutable_x->Reserve(5);
+for (int i = 0; i < 5; i++) {
+  foo.add_x();
+  bar.add_x();
+}
+  }
+  {
+FooProto foo;
+foo.mutable_y();
+// CHECK-FIXES-NOT: foo.mutable_x()->Reserve(5);
+for (int i = 0; i < 5; i++) {
+  foo.add_x(i);
+}
+  }
+  {
+FooProto foo;
+// CHECK-FIXES-NOT: foo.mutable_z->Reserve(5);
+for (int i = 0; i < 5; i++) {
+  foo.add_z();
+}
+  }
 }
Index: clang-tools-extra/docs/clang-tidy/checks/performance-inefficient-vector-operation.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/performance-inefficient-vector-operation.rst
+++ clang-tools-extra/docs/clang-tidy/checks/performance-inefficient-vector-operation.rst
@@ -6,6 +6,10 @@
 Finds possible inefficient ``std::vector`` operations (e.g. ``push_back``,
 ``emplace_back``) that may cause unnecessary memory reallocations.
 
+It can also find calls that add element to protobuf repeated field in a loop
+without calling Reserve() before the loop. Calling Reserve() first can avoid
+unnecessary memory reallocations.
+
 Currently, the check only detects following kinds of loops with a single
 statement body:
 
@@ -21,6 +25,13 @@
 // statement before the for statement.
   }
 
+  SomeProto p;
+  for (int i = 0; i < n; ++i) {
+p.add_xxx(n);
+// This will trigger the warning since the add_xxx may cause multiple memory
+// relloacations. This can be avoid by inserting a
+// 'p.mutable_xxx().Reserve(n)' statement before the for statement.
+  }
 
 * For-range loops like ``for (range-declaration : range_expression)``, the type
   of ``range_expression`` can be ``std::vector``, ``std::array``,
@@ -47,3 +58,8 @@
 
Semicolon-separated list of names of vector-like classes. By default only
``::std::vector`` is considered.
+
+.. option:: EnableProto
+   When non-zero, the check will also warn on inefficient operations for proto
+   repeated fields. Otherwise, the check only warns on inefficient vector
+   operations. Default is `0`.
Index: clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h
=

  1   2   >