[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC option -EHa)

2020-05-22 Thread Ten Tzen via Phabricator via cfe-commits
tentzen updated this revision to Diff 265672.
tentzen added a comment.

avoid lint warnings and lint hang on Windows


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344

Files:
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCleanup.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGException.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/JumpDiagnostics.cpp
  clang/test/CodeGen/windows-seh-EHa-CppCatchDotDotDot.cpp
  clang/test/CodeGen/windows-seh-EHa-CppDtors01.cpp
  clang/test/CodeGen/windows-seh-EHa-TryInFinally.cpp
  llvm/include/llvm/CodeGen/SelectionDAGISel.h
  llvm/include/llvm/CodeGen/WinEHFuncInfo.h
  llvm/include/llvm/IR/BasicBlock.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/lib/Analysis/EHPersonalities.cpp
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/AsmPrinter/WinException.cpp
  llvm/lib/CodeGen/BranchFolding.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
  llvm/lib/CodeGen/WinEHPrepare.cpp
  llvm/lib/IR/BasicBlock.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/test/CodeGen/X86/windows-seh-EHa-CppCatchDotDotDot.ll
  llvm/test/CodeGen/X86/windows-seh-EHa-CppDtors01.ll
  llvm/test/CodeGen/X86/windows-seh-EHa-TryInFinally.ll

Index: llvm/test/CodeGen/X86/windows-seh-EHa-TryInFinally.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/windows-seh-EHa-TryInFinally.ll
@@ -0,0 +1,226 @@
+; RUN: llc -verify-machineinstrs < %s | FileCheck %s
+
+; CHECK-LABEL: "?fin$0@0@main@@"
+; CHECK:  .seh_handlerdata
+; CHECK:  .set ".L?fin$0@0@main@@$parent_frame_offset", 48
+; CHECK-NEXT:.long   (.Llsda_end1-.Llsda_begin1)/16 
+; CHECK-NEXT: .Llsda_begin1:
+; CHECK-NEXT:.long   .Ltmp
+; CHECK-NEXT:.long   .Ltmp
+; CHECK-NEXT:.long   "?dtor$
+; CHECK-NEXT:.long   0
+; CHECK-NEXT: .Llsda_end1:
+
+; ModuleID = 'windows-seh-EHa-TryInFinally.cpp'
+source_filename = "windows-seh-EHa-TryInFinally.cpp"
+target datalayout = "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+$"??_C@_0CI@MDFPIOJJ@?5?9?9?9?5Test?5_Try?5in?5_finally?5?9?9?9?5i@" = comdat any
+
+$"??_C@_0BN@HHKJHLBE@?5?5In?5Inner?5_finally?5i?5?$DN?5?$CFd?5?6?$AA@" = comdat any
+
+$"??_C@_0BN@HAIIIOKI@?5?5In?5outer?5_finally?5i?5?$DN?5?$CFd?5?6?$AA@" = comdat any
+
+$"??_C@_0BJ@OJMMAGCD@?5?5In?5outer?5_try?5i?5?$DN?5?$CFd?5?6?$AA@" = comdat any
+
+$"??_C@_0CG@ENDJHCGA@?5?9?9?9?5In?5outer?5except?5handler?5i?5?$DN@" = comdat any
+
+@"??_C@_0CI@MDFPIOJJ@?5?9?9?9?5Test?5_Try?5in?5_finally?5?9?9?9?5i@" = linkonce_odr dso_local unnamed_addr constant [40 x i8] c" --- Test _Try in _finally --- i = %d \0A\00", comdat, align 1
+@"??_C@_0BN@HHKJHLBE@?5?5In?5Inner?5_finally?5i?5?$DN?5?$CFd?5?6?$AA@" = linkonce_odr dso_local unnamed_addr constant [29 x i8] c"  In Inner _finally i = %d \0A\00", comdat, align 1
+@"??_C@_0BN@HAIIIOKI@?5?5In?5outer?5_finally?5i?5?$DN?5?$CFd?5?6?$AA@" = linkonce_odr dso_local unnamed_addr constant [29 x i8] c"  In outer _finally i = %d \0A\00", comdat, align 1
+@"??_C@_0BJ@OJMMAGCD@?5?5In?5outer?5_try?5i?5?$DN?5?$CFd?5?6?$AA@" = linkonce_odr dso_local unnamed_addr constant [25 x i8] c"  In outer _try i = %d \0A\00", comdat, align 1
+@"??_C@_0CG@ENDJHCGA@?5?9?9?9?5In?5outer?5except?5handler?5i?5?$DN@" = linkonce_odr dso_local unnamed_addr constant [38 x i8] c" --- In outer except handler i = %d \0A\00", comdat, align 1
+
+; Function Attrs: noinline norecurse optnone
+define dso_local i32 @main() #0 personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) {
+entry:
+  %retval = alloca i32, align 4
+  %i = alloca i32, align 4
+  %__exception_code = alloca i32, align 4
+  call void (...) @llvm.localescape(i32* %i)
+  store i32 0, i32* %retval, align 4
+  store i32 0, i32* %i, align 4
+  br label %for.cond
+
+for.cond: ; preds = %for.inc, %entry
+  %0 = load i32, i32* %i, align 4
+  %cmp = icmp slt i32 %0, 3
+  br i1 %cmp, label %for.body, label %for.end
+
+for.body: ; preds = %for.cond
+  %1 = load i32, i32* %i, align 4
+  call void (...) @"?printf@@YAXZZ"(i8* getelementptr inbounds ([40 x i8], [40 x i8]* @"??_C@_0CI@MDFPIOJJ@?5?9?9?9?5Test?5_Try?5in?5_finally?5?9?9?9?5i@", i64 0, i64 0), i32 %1)
+  invoke void @llvm.seh.try.begin()
+  to label %invoke.cont unwind label %catch.dispatch
+
+invoke.cont:  ; preds = %for.body
+  invoke void @llvm.seh.try.begin()
+  to label %invoke.cont1 unwind label %ehcleanup
+
+invo

[PATCH] D80366: [Analyzer] Add `getReturnValueUnderConstruction()` to `CallEvent`

2020-05-22 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h:435
+  /// If the call returns a C++ record type then the region of its return value
+  // can be retrieved from its construction context.
+  Optional getReturnValueUnderConstruction(unsigned BlockCount) const;

A `/` is missing (or too much of `/` above?).
It looks like that the comment tells something about how the function works, 
not what it does. Or not? (The function works by retrieving the construction 
context and something from it, but that seems to be the return value, not a 
region. This is why this comment can be confusing.) This belongs better to the 
implementation, not to the documentation part. The documentation could contain 
something about how and when the function can be used to get a non-null value.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80366



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


[PATCH] D80421: [Mips] use correct ld.so for musl soft float

2020-05-22 Thread Simon Atanasyan via Phabricator via cfe-commits
atanasyan added a reviewer: atanasyan.
atanasyan added a comment.

1. Please include as much context as possible with your diff. This instruction 

 helps to do that.
2. Such patch needs test case(s). Maybe it's enough to update the `linux-ld.c` 
test case which is failed now. Update failed cases and check both "soft" and 
"hard" float cases in this test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80421



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


[PATCH] D79800: [Sema] Remove default values for arguments prior to a parameter pack if the pack is used

2020-05-22 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/test/CXX/drs/dr7xx.cpp:225
 template 
 void f(int i = 0, T ...args) {}
 void ff() { f(); }

rjmccall wrote:
> Quuxplusone wrote:
> > Is this even supposed to compile? The only valid specializations of `f` 
> > require `T...` to be an empty pack, which violates 
> > [temp.res/8.3](https://timsong-cpp.github.io/cppwp/temp.res#8.3).
> > 
> > The comment mentions 
> > [DR777](http://cwg-issue-browser.herokuapp.com/cwg777), but DR777 doesn't 
> > explain the circumstances under which its wording change matters. It 
> > //seems// only to apply to templates that are already ill-formed by 
> > temp.res/8.3.
> Yeah, Richard made this point in 
> [[http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2233|DR2233]], 
> and the wording was weakened to allow it, in a way that essentially makes the 
> earlier default arguments dead.
Huh. Ick. Indeed the other vendors seem to be implementing DR777/DR2233, so I 
guess Clang ought to catch up even if it's a silly direction to go in. :( I do 
see a small bit of implementation divergence in https://godbolt.org/z/ZMCvAX —
```
template
int f(int i=1, Ts... ts) { return (i + ... + ts); }

template<>
int f(int i, int j) { return 42; }
```
GCC rejects as ill-formed. MSVC makes the specialization callable with 2 
arguments only. EDG (ICC) makes the specialization callable with 0 or 2 
arguments (and does [crazy things](https://godbolt.org/z/QTrVeh) when you call 
it with 0 arguments).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79800



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


[PATCH] D69764: [clang-format] Add Left/Right Const fixer capability

2020-05-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.



In D69764#2050226 , @steveire wrote:

> I like the approach of using clang-format to implement this. It's much faster 
> than a `clang-tidy` approach.
>
> The broader C++ community has already chosen `East`/`West` and it has 
> momentum. If you choose `Left`/`Right` now, you will get pressure to add 
> `East`/`West` in the future, which means we'll have the synonyms we want to 
> avoid.
>
> The broader C++ community already has understanding of `East`/`West`. Trying 
> to change that now should be out of scope for this patch. This patch should 
> use `East`/`West`.
>
> I ran this on a large codebase and discovered some problems with this patch. 
> Given this `.clang-format` file:


Thank you for this feedback @steveire, to be honest I agree, I didn't want to 
waste time arguing about the naming for now so simply gave in. Supporting 
multiple words from the outset also felt wrong, maybe we can spin around later 
towards the end of the review if there is more of a concencus on naming being 
the other way.

Thank you also for the failure scenarios I will add them as tests as I try to 
improve this further.

I think there was a suggestion that somehow this should cover all forms of 
identifier ordering but I actually think that is going to be incredibly complex 
especially if that configuration was completely dynamic and supported custom 
types and macros

For now let me pursue fixes for the cases you have identified.


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

https://reviews.llvm.org/D69764



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


[PATCH] D80279: [libclang] Extend clang_Cursor_Evaluate().

2020-05-22 Thread Christian Kandeler via Phabricator via cfe-commits
ckandeler added a comment.

Thanks for the quick review. I don't have commit access, so can someone please 
commit it for me?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80279



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


[PATCH] D80423: [analyzer] SATestBuild.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, dcoughlin.
Herald added subscribers: cfe-commits, ASDenysPetrov, Charusso, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: clang.

SATest scripts should be more python-style than they are now.
This includes better architecture, type annotations, naming
convesions, and up-to-date language features.  This commit starts
with two scripts SATestBuild and SATestAdd.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80423

Files:
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py

Index: clang/utils/analyzer/SATestUpdateDiffs.py
===
--- clang/utils/analyzer/SATestUpdateDiffs.py
+++ clang/utils/analyzer/SATestUpdateDiffs.py
@@ -21,21 +21,21 @@
 
 
 def updateReferenceResults(ProjName, ProjBuildMode):
-ProjDir = SATestBuild.getProjectDir(ProjName)
+ProjTester = SATestBuild.ProjectTester(ProjName, ProjBuildMode)
+ProjDir = ProjTester.get_project_dir()
 
-RefResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=True))
-CreatedResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
+ProjTester.is_reference_build = True
+RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+
+ProjTester.is_reference_build = False
+CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
 
 if not os.path.exists(CreatedResultsPath):
 print("New results not found, was SATestBuild.py "
   "previously run?", file=sys.stderr)
 sys.exit(1)
 
-BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath)
+BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
 Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
 runCmd("mkdir -p '%s'" % Dirname)
 with open(BuildLogPath, "w+") as PBuildLogFile:
@@ -50,13 +50,13 @@
stdout=PBuildLogFile)
 
 # Run cleanup script.
-SATestBuild.runCleanupScript(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
 
-SATestBuild.normalizeReferenceResults(
+SATestBuild.normalize_reference_results(
 ProjDir, RefResultsPath, ProjBuildMode)
 
 # Clean up the generated difference results.
-SATestBuild.cleanupReferenceResults(RefResultsPath)
+SATestBuild.cleanup_reference_results(RefResultsPath)
 
 runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
 
@@ -69,8 +69,8 @@
   file=sys.stderr)
 sys.exit(1)
 
-with SATestBuild.projectFileHandler() as f:
-for (ProjName, ProjBuildMode) in SATestBuild.iterateOverProjects(f):
+with open(SATestBuild.get_project_map_path(), "r") as f:
+for ProjName, ProjBuildMode in SATestBuild.get_projects(f):
 updateReferenceResults(ProjName, int(ProjBuildMode))
 
 
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -45,7 +45,6 @@
 import CmpRuns
 import SATestUtils
 
-from subprocess import CalledProcessError, check_call
 import argparse
 import csv
 import glob
@@ -59,59 +58,33 @@
 import threading
 import time
 
-try:
-import queue
-except ImportError:
-import Queue as queue
+from queue import Queue
+from subprocess import CalledProcessError, check_call
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
+TYPE_CHECKING)
+
 
 ###
 # Helper functions.
 ###
 
-Local = threading.local()
-Local.stdout = sys.stdout
-Local.stderr = sys.stderr
-logging.basicConfig(
-level=logging.DEBUG,
-format='%(asctime)s:%(levelname)s:%(name)s: %(message)s')
-
+LOCAL = threading.local()
+LOCAL.stdout = sys.stdout
+LOCAL.stderr = sys.stderr
 
-class StreamToLogger:
-def __init__(self, logger, log_level=logging.INFO):
-self.logger = logger
-self.log_level = log_level
 
-def write(self, buf):
-# Rstrip in order not to write an extra newline.
-self.logger.log(self.log_level, buf.rstrip())
+def stderr(message: str):
+LOCAL.stderr.write(message)
 
-def flush(self):
-pass
 
-def fileno(self):
-return 0
+def stdout(message: str):
+LOCAL.stdout.write(message)
 
 
-def getProjectMapPath():
-ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
-  ProjectMapFile)
-if not os.path.exists(ProjectMapPath):
-Local.stdout.write("Error: Cannot find the Project Map 

[PATCH] D80003: [clang][clang-scan-deps] Add a mode that can compute overhead in duplicated module builds

2020-05-22 Thread Daniel Grumberg via Phabricator via cfe-commits
dang updated this revision to Diff 265676.
dang added a comment.

Rebase this on top of the new AST Signature patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80003

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -6,12 +6,14 @@
 //
 //===--===//
 
+#include "clang/Basic/Module.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
 #include "clang/Tooling/JSONCompilationDatabase.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/InitLLVM.h"
@@ -20,6 +22,7 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/ThreadPool.h"
 #include "llvm/Support/Threading.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -165,6 +168,13 @@
 llvm::cl::init(false),
 llvm::cl::cat(DependencyScannerCategory));
 
+llvm::cl::opt GatherMetrics(
+"metrics", llvm::cl::Optional,
+llvm::cl::desc(
+"Gather metrics during tool operation to measure overhead of modules "
+"built in explicit mode with respect to implicit modules."),
+llvm::cl::init(false), llvm::cl::cat(DependencyScannerCategory));
+
 } // end anonymous namespace
 
 /// \returns object-file path derived from source-file path.
@@ -327,6 +337,65 @@
 OS << llvm::formatv("{0:2}\n", Value(std::move(Output)));
   }
 
+  void computeAndPrintBuildMetrics(raw_ostream &OS) {
+std::unordered_map
+RelaxedHashesEfficiencyInfo;
+std::set UniqueModuleSignatures;
+for (auto &&M : Modules) {
+  std::string RelaxedHashModule =
+  M.second.ModuleName + '-' + M.second.RelaxedContextHash;
+  auto &BuiltModulesInfo = RelaxedHashesEfficiencyInfo[RelaxedHashModule];
+  BuiltModulesInfo.BuiltModules.push_back(&M.second);
+  auto InsertionResult =
+  UniqueModuleSignatures.insert(M.second.ModuleSignature);
+  if (InsertionResult.second)
+BuiltModulesInfo.UniqueASTFileSignatures++;
+}
+
+size_t TotalStrictContextHashModules = Modules.size();
+size_t TotalRelaxedHashModules = RelaxedHashesEfficiencyInfo.size();
+auto PercentageModuleNumberIncrease =
+100 * ((TotalStrictContextHashModules - TotalRelaxedHashModules) /
+   TotalRelaxedHashModules);
+
+OS << "Total relaxed hash modules: " << TotalRelaxedHashModules << "\n";
+OS << "Total unique AST signatures: " << UniqueModuleSignatures.size()
+   << "\n";
+OS << "Total strict context hash modules: " << TotalStrictContextHashModules
+   << "\n";
+OS << "Module number increase: " << PercentageModuleNumberIncrease
+   << "%\n\n";
+
+OS << "Details:\n";
+for (auto &&It : RelaxedHashesEfficiencyInfo) {
+  auto &Duplicates = It.second.BuiltModules;
+  size_t NumDuplicates = Duplicates.size();
+
+  assert(NumDuplicates > 0 && "Cannot have a relaxed hash module that "
+  "doesn't map to at least a strict"
+  "one!");
+
+  if (NumDuplicates > 1) {
+OS << "Relaxed hash module: " << It.first << " gets duplicated as ("
+   << It.second.UniqueASTFileSignatures << "/" << NumDuplicates
+   << ") modules:\n\n";
+
+auto OutputModuleDep = [](raw_ostream &OS, ModuleDeps *MD) {
+  OS << MD->ModuleName << "-" << MD->ContextHash;
+};
+
+auto DuplicatesIt = Duplicates.begin();
+OutputModuleDep(OS, *DuplicatesIt);
+++DuplicatesIt;
+for (auto End = Duplicates.end(); DuplicatesIt != End; ++DuplicatesIt) {
+  OS << "; ";
+  OutputModuleDep(OS, *DuplicatesIt);
+}
+OS << "\n\n";
+  }
+}
+  }
+
 private:
   StringRef lookupPCMPath(ClangModuleDep CMD) {
 return Modules[ContextModulePair{CMD.ContextHash, CMD.ModuleName, 0}]
@@ -340,6 +409,11 @@
 return I->second;
   };
 
+  struct BuiltModulesEfficiencyInfo {
+std::vector BuiltModules;
+size_t UniqueASTFileSignatures;
+  };
+
   struct ContextModulePair {
 std::string ContextHash;
 std::string ModuleName;
@@ -543,5 +617,8

[PATCH] D80424: [analyzer] SATestUtils.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 265680.
vsavchenko added a comment.

Modify forgotten parts


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80424

Files:
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUtils.py

Index: clang/utils/analyzer/SATestUtils.py
===
--- clang/utils/analyzer/SATestUtils.py
+++ clang/utils/analyzer/SATestUtils.py
@@ -1,12 +1,11 @@
 import os
-from subprocess import check_call
 import sys
 
+from subprocess import CalledProcessError, check_call
+from typing import List, IO, Optional
 
-Verbose = 1
 
-
-def which(command, paths=None):
+def which(command: str, paths: Optional[str] = None) -> Optional[str]:
 """which(command, [paths]) - Look up the given command in the paths string
 (or the PATH environment variable, if unspecified)."""
 
@@ -38,41 +37,44 @@
 return None
 
 
-def hasNoExtension(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return (Ext == "")
+def has_no_extension(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext == ""
 
 
-def isValidSingleInputFile(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return Ext in (".i", ".ii", ".c", ".cpp", ".m", "")
+def is_valid_single_input_file(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext in (".i", ".ii", ".c", ".cpp", ".m", "")
 
 
-def runScript(ScriptPath, PBuildLogFile, Cwd, Stdout=sys.stdout,
-  Stderr=sys.stderr):
+def run_script(script_path: str, build_log_file: IO, cwd: str,
+   out=sys.stdout, err=sys.stderr, verbose: int = 0):
 """
 Run the provided script if it exists.
 """
-if os.path.exists(ScriptPath):
+if os.path.exists(script_path):
 try:
-if Verbose == 1:
-Stdout.write("  Executing: %s\n" % (ScriptPath,))
-check_call("chmod +x '%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
+if verbose == 1:
+out.write(f"  Executing: {script_path}\n")
+
+check_call(f"chmod +x '{script_path}'", cwd=cwd,
+   stderr=build_log_file,
+   stdout=build_log_file,
shell=True)
-check_call("'%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
+
+check_call(f"'{script_path}'", cwd=cwd,
+   stderr=build_log_file,
+   stdout=build_log_file,
shell=True)
-except:
-Stderr.write("Error: Running %s failed. See %s for details.\n" % (
- ScriptPath, PBuildLogFile.name))
+
+except CalledProcessError:
+err.write(f"Error: Running {script_path} failed. "
+  f"See {build_log_file.name} for details.\n")
 sys.exit(-1)
 
 
-def isCommentCSVLine(Entries):
+def is_comment_csv_line(entries: List[str]) -> bool:
 """
 Treat CSV lines starting with a '#' as a comment.
 """
-return len(Entries) > 0 and Entries[0].startswith("#")
+return len(entries) > 0 and entries[0].startswith("#")
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -60,8 +60,8 @@
 
 from queue import Queue
 from subprocess import CalledProcessError, check_call
-from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
-TYPE_CHECKING)
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Optional,
+Tuple, TYPE_CHECKING)
 
 
 ###
@@ -93,13 +93,15 @@
 
 # Find Clang for static analysis.
 if 'CC' in os.environ:
-CLANG = os.environ['CC']
+cc_candidate: Optional[str] = os.environ['CC']
 else:
-CLANG = SATestUtils.which("clang", os.environ['PATH'])
-if not CLANG:
+cc_candidate = SATestUtils.which("clang", os.environ['PATH'])
+if not cc_candidate:
 stderr("Error: cannot find 'clang' in PATH")
 sys.exit(1)
 
+CLANG = cc_candidate
+
 # Number of jobs.
 MAX_JOBS = int(math.ceil(multiprocessing.cpu_count() * 0.75))
 
@@ -204,8 +206,9 @@
 cwd = os.path.join(directory, PATCHED_SOURCE_DIR_NAME)
 script_path = os.path.join(directory, CLEANUP_SCRIPT)
 
-SATestUtils.runScript(script_path, build_log_file, cwd,
-  Stdout=LOCAL.stdout, Stderr=LOCAL.stderr)
+SATestUtils.run_script(script_path, build_log_file, cwd,
+   out=LOCAL.stdout, err=LOCAL.stderr,
+   verbose=VERBOSE)
 
 
 def download_and_patch(directory: str,

[PATCH] D80424: [analyzer] SATestUtils.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, dcoughlin.
Herald added subscribers: cfe-commits, ASDenysPetrov, Charusso, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: clang.
vsavchenko updated this revision to Diff 265680.
vsavchenko added a comment.
vsavchenko added a parent revision: D80423: [analyzer] SATestBuild.py: Refactor 
and add type annotations.

Modify forgotten parts


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80424

Files:
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUtils.py

Index: clang/utils/analyzer/SATestUtils.py
===
--- clang/utils/analyzer/SATestUtils.py
+++ clang/utils/analyzer/SATestUtils.py
@@ -1,12 +1,11 @@
 import os
-from subprocess import check_call
 import sys
 
+from subprocess import CalledProcessError, check_call
+from typing import List, IO, Optional
 
-Verbose = 1
 
-
-def which(command, paths=None):
+def which(command: str, paths: Optional[str] = None) -> Optional[str]:
 """which(command, [paths]) - Look up the given command in the paths string
 (or the PATH environment variable, if unspecified)."""
 
@@ -38,41 +37,44 @@
 return None
 
 
-def hasNoExtension(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return (Ext == "")
+def has_no_extension(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext == ""
 
 
-def isValidSingleInputFile(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return Ext in (".i", ".ii", ".c", ".cpp", ".m", "")
+def is_valid_single_input_file(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext in (".i", ".ii", ".c", ".cpp", ".m", "")
 
 
-def runScript(ScriptPath, PBuildLogFile, Cwd, Stdout=sys.stdout,
-  Stderr=sys.stderr):
+def run_script(script_path: str, build_log_file: IO, cwd: str,
+   out=sys.stdout, err=sys.stderr, verbose: int = 0):
 """
 Run the provided script if it exists.
 """
-if os.path.exists(ScriptPath):
+if os.path.exists(script_path):
 try:
-if Verbose == 1:
-Stdout.write("  Executing: %s\n" % (ScriptPath,))
-check_call("chmod +x '%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
+if verbose == 1:
+out.write(f"  Executing: {script_path}\n")
+
+check_call(f"chmod +x '{script_path}'", cwd=cwd,
+   stderr=build_log_file,
+   stdout=build_log_file,
shell=True)
-check_call("'%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
+
+check_call(f"'{script_path}'", cwd=cwd,
+   stderr=build_log_file,
+   stdout=build_log_file,
shell=True)
-except:
-Stderr.write("Error: Running %s failed. See %s for details.\n" % (
- ScriptPath, PBuildLogFile.name))
+
+except CalledProcessError:
+err.write(f"Error: Running {script_path} failed. "
+  f"See {build_log_file.name} for details.\n")
 sys.exit(-1)
 
 
-def isCommentCSVLine(Entries):
+def is_comment_csv_line(entries: List[str]) -> bool:
 """
 Treat CSV lines starting with a '#' as a comment.
 """
-return len(Entries) > 0 and Entries[0].startswith("#")
+return len(entries) > 0 and entries[0].startswith("#")
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -60,8 +60,8 @@
 
 from queue import Queue
 from subprocess import CalledProcessError, check_call
-from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
-TYPE_CHECKING)
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Optional,
+Tuple, TYPE_CHECKING)
 
 
 ###
@@ -93,13 +93,15 @@
 
 # Find Clang for static analysis.
 if 'CC' in os.environ:
-CLANG = os.environ['CC']
+cc_candidate: Optional[str] = os.environ['CC']
 else:
-CLANG = SATestUtils.which("clang", os.environ['PATH'])
-if not CLANG:
+cc_candidate = SATestUtils.which("clang", os.environ['PATH'])
+if not cc_candidate:
 stderr("Error: cannot find 'clang' in PATH")
 sys.exit(1)
 
+CLANG = cc_candidate
+
 # Number of jobs.
 MAX_JOBS = int(math.ceil(multiprocessing.cpu_count() * 0.75))
 
@@ -204,8 +206,9 @@
 cwd = os.path.join(directory, PATCHED_SOURCE_DIR_NAME)
 script_path = os.path.join(directory, CLEANUP_SCRIPT)
 
-SATestUtils.runScript(scr

[PATCH] D80423: [analyzer] SATestBuild.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 265682.
vsavchenko added a comment.

Fix update diffs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80423

Files:
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py

Index: clang/utils/analyzer/SATestUpdateDiffs.py
===
--- clang/utils/analyzer/SATestUpdateDiffs.py
+++ clang/utils/analyzer/SATestUpdateDiffs.py
@@ -21,21 +21,22 @@
 
 
 def updateReferenceResults(ProjName, ProjBuildMode):
-ProjDir = SATestBuild.getProjectDir(ProjName)
+ProjInfo = SATestBuild.ProjectInfo(ProjName, ProjBuildMode)
+ProjTester = SATestBuild.ProjectTester(ProjInfo)
+ProjDir = ProjTester.get_project_dir()
 
-RefResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=True))
-CreatedResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
+ProjTester.is_reference_build = True
+RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+
+ProjTester.is_reference_build = False
+CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
 
 if not os.path.exists(CreatedResultsPath):
 print("New results not found, was SATestBuild.py "
   "previously run?", file=sys.stderr)
 sys.exit(1)
 
-BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath)
+BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
 Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
 runCmd("mkdir -p '%s'" % Dirname)
 with open(BuildLogPath, "w+") as PBuildLogFile:
@@ -50,13 +51,13 @@
stdout=PBuildLogFile)
 
 # Run cleanup script.
-SATestBuild.runCleanupScript(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
 
-SATestBuild.normalizeReferenceResults(
+SATestBuild.normalize_reference_results(
 ProjDir, RefResultsPath, ProjBuildMode)
 
 # Clean up the generated difference results.
-SATestBuild.cleanupReferenceResults(RefResultsPath)
+SATestBuild.cleanup_reference_results(RefResultsPath)
 
 runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
 
@@ -69,8 +70,8 @@
   file=sys.stderr)
 sys.exit(1)
 
-with SATestBuild.projectFileHandler() as f:
-for (ProjName, ProjBuildMode) in SATestBuild.iterateOverProjects(f):
+with open(SATestBuild.get_project_map_path(), "r") as f:
+for ProjName, ProjBuildMode in SATestBuild.get_projects(f):
 updateReferenceResults(ProjName, int(ProjBuildMode))
 
 
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -45,7 +45,6 @@
 import CmpRuns
 import SATestUtils
 
-from subprocess import CalledProcessError, check_call
 import argparse
 import csv
 import glob
@@ -59,59 +58,33 @@
 import threading
 import time
 
-try:
-import queue
-except ImportError:
-import Queue as queue
+from queue import Queue
+from subprocess import CalledProcessError, check_call
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
+TYPE_CHECKING)
+
 
 ###
 # Helper functions.
 ###
 
-Local = threading.local()
-Local.stdout = sys.stdout
-Local.stderr = sys.stderr
-logging.basicConfig(
-level=logging.DEBUG,
-format='%(asctime)s:%(levelname)s:%(name)s: %(message)s')
-
+LOCAL = threading.local()
+LOCAL.stdout = sys.stdout
+LOCAL.stderr = sys.stderr
 
-class StreamToLogger:
-def __init__(self, logger, log_level=logging.INFO):
-self.logger = logger
-self.log_level = log_level
 
-def write(self, buf):
-# Rstrip in order not to write an extra newline.
-self.logger.log(self.log_level, buf.rstrip())
+def stderr(message: str):
+LOCAL.stderr.write(message)
 
-def flush(self):
-pass
 
-def fileno(self):
-return 0
+def stdout(message: str):
+LOCAL.stdout.write(message)
 
 
-def getProjectMapPath():
-ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
-  ProjectMapFile)
-if not os.path.exists(ProjectMapPath):
-Local.stdout.write("Error: Cannot find the Project Map file " +
-   ProjectMapPath +
-   "\nRunning script for the wrong directory?\n")
-sys.exit(1)
-return ProjectMapPath
-
-
-def getProjectDir(ID):
-return os.path.join(os.path.abspath(os.curdir), ID)
-
+logging.basicConfig(
+leve

[PATCH] D65050: [SemaTemplate] Mark a function type as dependent when its parameter list contains pack expansion

2020-05-22 Thread S. B. Tam via Phabricator via cfe-commits
cpplearner updated this revision to Diff 265683.
cpplearner added a comment.

rebase & ping @rsmith


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

https://reviews.llvm.org/D65050

Files:
  clang/lib/AST/Type.cpp
  clang/test/SemaTemplate/alias-templates.cpp


Index: clang/test/SemaTemplate/alias-templates.cpp
===
--- clang/test/SemaTemplate/alias-templates.cpp
+++ clang/test/SemaTemplate/alias-templates.cpp
@@ -265,3 +265,34 @@
 int z = Bar(); // expected-error {{use of template template parameter 
'Bar' requires template arguments}}
   }
 }
+
+namespace PR42654 {
+  template struct function { };
+
+  template
+  struct thing {
+void f(function) { }
+  };
+
+  template
+  struct Environment
+  {
+template
+using Integer = int;
+
+using Function = function...)>;
+using MyTuple = thing...>;
+
+void run(Function func)
+{
+  MyTuple t;
+  t.f(func);
+}
+  };
+
+  void f()
+  {
+Environment env;
+env.run({});
+  }
+}
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -3110,6 +3110,11 @@
   for (unsigned i = 0; i != getNumParams(); ++i) {
 addDependence(params[i]->getDependence() &
   ~TypeDependence::VariablyModified);
+// A pack expansion with a non-dependent pattern affects the number of
+// parameters, thus we mark such function type as dependent, even though
+// this isn't listed in N4861 [temp.dep.type].
+if (params[i]->getAs())
+  addDependence(TypeDependence::Dependent);
 argSlot[i] = params[i];
   }
 


Index: clang/test/SemaTemplate/alias-templates.cpp
===
--- clang/test/SemaTemplate/alias-templates.cpp
+++ clang/test/SemaTemplate/alias-templates.cpp
@@ -265,3 +265,34 @@
 int z = Bar(); // expected-error {{use of template template parameter 'Bar' requires template arguments}}
   }
 }
+
+namespace PR42654 {
+  template struct function { };
+
+  template
+  struct thing {
+void f(function) { }
+  };
+
+  template
+  struct Environment
+  {
+template
+using Integer = int;
+
+using Function = function...)>;
+using MyTuple = thing...>;
+
+void run(Function func)
+{
+  MyTuple t;
+  t.f(func);
+}
+  };
+
+  void f()
+  {
+Environment env;
+env.run({});
+  }
+}
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -3110,6 +3110,11 @@
   for (unsigned i = 0; i != getNumParams(); ++i) {
 addDependence(params[i]->getDependence() &
   ~TypeDependence::VariablyModified);
+// A pack expansion with a non-dependent pattern affects the number of
+// parameters, thus we mark such function type as dependent, even though
+// this isn't listed in N4861 [temp.dep.type].
+if (params[i]->getAs())
+  addDependence(TypeDependence::Dependent);
 argSlot[i] = params[i];
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80079: [clang-format] [NFC] isCpp() is inconsistently used to mean both C++ and Objective C, add language specific isXXX() functions

2020-05-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 265684.
MyDeveloperDay added a comment.

Switch to new function name suggestions


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

https://reviews.llvm.org/D80079

Files:
  clang/include/clang/Format/Format.h
  clang/lib/Format/BreakableToken.cpp
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/lib/Format/UnwrappedLineParser.cpp

Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -299,11 +299,10 @@
 void UnwrappedLineParser::parseFile() {
   // The top-level context in a file always has declarations, except for pre-
   // processor directives and JavaScript files.
-  bool MustBeDeclaration =
-  !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
+  bool MustBeDeclaration = !Line->InPPDirective && !Style.isJavaScript();
   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
   MustBeDeclaration);
-  if (Style.Language == FormatStyle::LK_TextProto)
+  if (Style.isTextProtoBuf())
 parseBracedList();
   else
 parseLevel(/*HasOpeningBrace=*/false);
@@ -317,8 +316,7 @@
   //   // endfile comment
   // do not have a chance to be put on a line of their own until this point.
   // Here we add this newline before end-of-file comments.
-  if (Style.Language == FormatStyle::LK_TextProto &&
-  !CommentsBeforeNextToken.empty())
+  if (Style.isTextProtoBuf() && !CommentsBeforeNextToken.empty())
 addUnwrappedLine();
   flushComments(true);
   addUnwrappedLine();
@@ -411,8 +409,7 @@
   LLVM_FALLTHROUGH;
 }
 case tok::kw_case:
-  if (Style.Language == FormatStyle::LK_JavaScript &&
-  Line->MustBeDeclaration) {
+  if (Style.isJavaScript() && Line->MustBeDeclaration) {
 // A 'case: string' style field declaration.
 parseStructuralElement();
 break;
@@ -461,7 +458,7 @@
 
 switch (Tok->Tok.getKind()) {
 case tok::l_brace:
-  if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
+  if (Style.isJavaScript() && PrevTok) {
 if (PrevTok->isOneOf(tok::colon, tok::less))
   // A ':' indicates this code is in a type, or a braced list
   // following a label in an object literal ({a: {b: 1}}).
@@ -486,7 +483,7 @@
 break;
   if (LBraceStack.back()->BlockKind == BK_Unknown) {
 bool ProbablyBracedList = false;
-if (Style.Language == FormatStyle::LK_Proto) {
+if (Style.isProto()) {
   ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
 } else {
   // Using OriginalColumn to distinguish between ObjC methods and
@@ -503,10 +500,10 @@
   // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
   // braced list in JS.
   ProbablyBracedList =
-  (Style.Language == FormatStyle::LK_JavaScript &&
+  (Style.isJavaScript() &&
NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
 Keywords.kw_as)) ||
-  (Style.isCpp() && NextTok->is(tok::l_paren)) ||
+  (Style.isCppOrObjC() && NextTok->is(tok::l_paren)) ||
   NextTok->isOneOf(tok::comma, tok::period, tok::colon,
tok::r_paren, tok::r_square, tok::l_brace,
tok::ellipsis) ||
@@ -693,7 +690,7 @@
   FormatTok->BlockKind = BK_Block;
   nextToken();
   {
-bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
+bool SkipIndent = (Style.isJavaScript() &&
(isGoogScope(*Line) || isIIFE(*Line, Keywords)));
 ScopedLineState LineState(*this);
 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
@@ -1021,8 +1018,7 @@
 
 void UnwrappedLineParser::parseStructuralElement() {
   assert(!FormatTok->is(tok::l_brace));
-  if (Style.Language == FormatStyle::LK_TableGen &&
-  FormatTok->is(tok::pp_include)) {
+  if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
 nextToken();
 if (FormatTok->is(tok::string_literal))
   nextToken();
@@ -1053,39 +1049,38 @@
   case tok::kw_public:
   case tok::kw_protected:
   case tok::kw_private:
-if (Style.Language == FormatStyle::LK_Java ||
-Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
+if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
   nextToken();
 else
   parseAccessSpecifier();
 return;
   case tok::kw_if:
-if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
+if (Style.isJavaScript() && Line->MustBeDeclaration)
   // 

[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-22 Thread Tobias Hieta via Phabricator via cfe-commits
thieta created this revision.
Herald added subscribers: llvm-commits, cfe-commits, mstorsjo, dexonsmith, 
mgorny.
Herald added projects: clang, LLVM.

These are a collection of small fixes to make LLVM/Clang build with a 
clang+mingw toolchain to target Windows.

The three commits address the following problems:

- When using LTO we pass --lto-cache-directory to lld - but this option is not 
supported by the lld MingW driver so it fails with unknown argument.
- Don't symlink the tools - a MingW build version of clang should be assumed to 
be used on Windows - which doesn't support symlinks correctly - so instead use 
the copy path of the code for MingW as well.
- The logic for linking libclang with libdl was a bit flawed - use the similar 
logic as to other places in the CMake build system.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80425

Files:
  clang/tools/libclang/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/cmake/modules/HandleLLVMOptions.cmake


Index: clang/tools/libclang/CMakeLists.txt
===
--- clang/tools/libclang/CMakeLists.txt
+++ clang/tools/libclang/CMakeLists.txt
@@ -66,9 +66,8 @@
   endif ()
 endif ()
 
-find_library(DL_LIBRARY_PATH dl)
-if (DL_LIBRARY_PATH)
-  list(APPEND LIBS dl)
+if (HAVE_LIBDL)
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 
 option(LIBCLANG_BUILD_STATIC
Index: llvm/cmake/modules/HandleLLVMOptions.cmake
===
--- llvm/cmake/modules/HandleLLVMOptions.cmake
+++ llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -953,6 +953,8 @@
   # time a little since we re-link a lot of the same objects, and significantly
   # improves incremental build time.
   # FIXME: We should move all this logic into the clang driver.
+  #
+  # FIXME; mingw lld driver doesn't support any of the options below
   if(APPLE)
 append("-Wl,-cache_path_lto,${PROJECT_BINARY_DIR}/lto.cache"
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
@@ -962,7 +964,7 @@
   elseif(LLVM_USE_LINKER STREQUAL "gold")
 append("-Wl,--plugin-opt,cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
   endif()
Index: llvm/cmake/modules/AddLLVM.cmake
===
--- llvm/cmake/modules/AddLLVM.cmake
+++ llvm/cmake/modules/AddLLVM.cmake
@@ -1868,7 +1868,7 @@
   if(NOT ARG_OUTPUT_DIR)
 # If you're not overriding the OUTPUT_DIR, we can make the link relative in
 # the same directory.
-if(CMAKE_HOST_UNIX)
+if(CMAKE_HOST_UNIX AND NOT MINGW)
   set(dest_binary "$")
 endif()
 if(CMAKE_CONFIGURATION_TYPES)
@@ -1894,7 +1894,7 @@
 endif()
   endif()
 
-  if(CMAKE_HOST_UNIX)
+  if(CMAKE_HOST_UNIX AND NOT MINGW)
 set(LLVM_LINK_OR_COPY create_symlink)
   else()
 set(LLVM_LINK_OR_COPY copy)


Index: clang/tools/libclang/CMakeLists.txt
===
--- clang/tools/libclang/CMakeLists.txt
+++ clang/tools/libclang/CMakeLists.txt
@@ -66,9 +66,8 @@
   endif ()
 endif ()
 
-find_library(DL_LIBRARY_PATH dl)
-if (DL_LIBRARY_PATH)
-  list(APPEND LIBS dl)
+if (HAVE_LIBDL)
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 
 option(LIBCLANG_BUILD_STATIC
Index: llvm/cmake/modules/HandleLLVMOptions.cmake
===
--- llvm/cmake/modules/HandleLLVMOptions.cmake
+++ llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -953,6 +953,8 @@
   # time a little since we re-link a lot of the same objects, and significantly
   # improves incremental build time.
   # FIXME: We should move all this logic into the clang driver.
+  #
+  # FIXME; mingw lld driver doesn't support any of the options below
   if(APPLE)
 append("-Wl,-cache_path_lto,${PROJECT_BINARY_DIR}/lto.cache"
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
@@ -962,7 +964,7 @@
   elseif(LLVM_USE_LINKER STREQUAL "gold")
 append("-Wl,--plugin-opt,cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
   endif()
Index: llvm/cmake/modules/AddLLVM.cmake
===
--- llvm/cmake/modules/AddLLVM.cmake
+++ llvm/cmake/modules/AddLLVM.cmake
@@ -1868,7 +1868,7 @@
   if(NOT ARG_OUTPUT_DIR)
 # If you're not overriding the OUTPUT_DIR, we can make the link relative in
 # the same directory.
-if(CMAKE_HOST_UNIX)
+if(CMAKE_HOST_UNIX AND NOT MINGW)
   set(dest_binary "$")
  

[PATCH] D80426: [analyzer] SATestUpdateDiffs.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, dcoughlin.
Herald added subscribers: cfe-commits, ASDenysPetrov, Charusso, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: clang.
vsavchenko added a parent revision: D80424: [analyzer] SATestUtils.py: Refactor 
and add type annotations.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80426

Files:
  clang/utils/analyzer/SATestUpdateDiffs.py

Index: clang/utils/analyzer/SATestUpdateDiffs.py
===
--- clang/utils/analyzer/SATestUpdateDiffs.py
+++ clang/utils/analyzer/SATestUpdateDiffs.py
@@ -3,67 +3,67 @@
 """
 Update reference results for static analyzer.
 """
-from __future__ import absolute_import, division, print_function
-
 import SATestBuild
 
-from subprocess import check_call
 import os
+import shutil
 import sys
 
+from subprocess import check_call
+
 Verbose = 0
 
 
-def runCmd(Command, **kwargs):
-if Verbose:
-print("Executing %s" % Command)
-check_call(Command, shell=True, **kwargs)
+def update_reference_results(project_name: str, build_mode: int):
+project_info = SATestBuild.ProjectInfo(project_name, build_mode)
+tester = SATestBuild.ProjectTester(project_info)
+project_dir = tester.get_project_dir()
 
+tester.is_reference_build = True
+ref_results_path = os.path.join(project_dir, tester.get_output_dir())
 
-def updateReferenceResults(ProjName, ProjBuildMode):
-ProjInfo = SATestBuild.ProjectInfo(ProjName, ProjBuildMode)
-ProjTester = SATestBuild.ProjectTester(ProjInfo)
-ProjDir = ProjTester.get_project_dir()
+tester.is_reference_build = False
+created_results_path = os.path.join(project_dir, tester.get_output_dir())
 
-ProjTester.is_reference_build = True
-RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+if not os.path.exists(created_results_path):
+print("New results not found, was SATestBuild.py previously run?",
+  file=sys.stderr)
+sys.exit(1)
 
-ProjTester.is_reference_build = False
-CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+build_log_path = SATestBuild.get_build_log_path(ref_results_path)
+build_log_dir = os.path.dirname(os.path.abspath(build_log_path))
 
-if not os.path.exists(CreatedResultsPath):
-print("New results not found, was SATestBuild.py "
-  "previously run?", file=sys.stderr)
-sys.exit(1)
+os.makedirs(build_log_dir)
+
+with open(build_log_path, "w+") as build_log_file:
+def run_cmd(command: str):
+if Verbose:
+print(f"Executing {command}")
+check_call(command, shell=True, stdout=build_log_file)
 
-BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
-Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
-runCmd("mkdir -p '%s'" % Dirname)
-with open(BuildLogPath, "w+") as PBuildLogFile:
 # Remove reference results: in git, and then again for a good measure
 # with rm, as git might not remove things fully if there are empty
 # directories involved.
-runCmd('git rm -r -q "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
-runCmd('rm -rf "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
+run_cmd(f"git rm -r -q '{ref_results_path}'")
+shutil.rmtree(ref_results_path)
 
 # Replace reference results with a freshly computed once.
-runCmd('cp -r "%s" "%s"' % (CreatedResultsPath, RefResultsPath,),
-   stdout=PBuildLogFile)
+shutil.copytree(created_results_path, ref_results_path, symlinks=True)
 
 # Run cleanup script.
-SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(project_dir, build_log_file)
 
 SATestBuild.normalize_reference_results(
-ProjDir, RefResultsPath, ProjBuildMode)
+project_dir, ref_results_path, build_mode)
 
 # Clean up the generated difference results.
-SATestBuild.cleanup_reference_results(RefResultsPath)
+SATestBuild.cleanup_reference_results(ref_results_path)
 
-runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
+run_cmd(f"git add '{ref_results_path}'")
 
 
 def main(argv):
-if len(argv) == 2 and argv[1] in ('-h', '--help'):
+if len(argv) == 2 and argv[1] in ("-h", "--help"):
 print("Update static analyzer reference results based "
   "\non the previous run of SATestBuild.py.\n"
   "\nN.B.: Assumes that SATestBuild.py was just run",
@@ -71,8 +71,8 @@
 sys.exit(1)
 
 with open(SATestBuild.get_project_map_path(), "r") as f:
-for ProjName, ProjBuildMode in SATestBuild.get_projects(f):
-updateReferenceResults(ProjName, int(ProjBuildMode))
+for project_name, build_mode i

[PATCH] D50078: clang-format: support aligned nested conditionals formatting

2020-05-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I get the point about Opt In, and if we are going to add an option it needs to 
go in ASAP otherwise too many people will then start complaining it was on by 
default before.

To be honest I think the question is do we consider this a bug or a feature, 
because we DO NOT provide Opt In on bug fixes (and there is no Opt Out).

If its a bug, there is no need for us to not have this on by default, its 
better to drive the improvement than 10,000's of .clang-format files needing to 
be updated just to get reasonable behavior.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D50078



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


[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-22 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

Super-nitpick: If you want to capitalize mingw, it's MinGW (minimalist gnu for 
windows) 😛 But as that's rather annoying to type, the all-lowercase version is 
quite fine as well.




Comment at: clang/tools/libclang/CMakeLists.txt:71
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 

If you say this is the same way it's done elsewhere, then sure - although I 
have no idea about what the issue is, why I haven't run into it, etc. Normally 
you wouldn't have a `libdl` on mingw right? What's the concrete issue you're 
running into, and in which conditions would one run into it?



Comment at: llvm/cmake/modules/AddLLVM.cmake:1872
+if(CMAKE_HOST_UNIX AND NOT MINGW)
   set(dest_binary "$")
 endif()

Not entirely sure what this one does - is it just a condition that needs to 
match the one for `create_symlink` below?



Comment at: llvm/cmake/modules/AddLLVM.cmake:1898
+  if(CMAKE_HOST_UNIX AND NOT MINGW)
 set(LLVM_LINK_OR_COPY create_symlink)
   else()

What's the practical issue you're trying to fix with this one here? If 
`CMAKE_HOST_UNIX`, i.e. when cross compiling, it does work fine to create 
symlinks (saving a bit of disk space and bandwidth). Then when transferring the 
built products to an actual windows system, they're converted into copies at 
some point (e.g. when zipping up the results).



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:957
+  #
+  # FIXME; mingw lld driver doesn't support any of the options below
   if(APPLE)

We could certainly add support for it in the mingw driver - ideally with the 
same name as for ELF, which then would be remapped to the corresponding 
lld-link option. This takes just a couple lines in lld/MinGW/Options.td, 
lld/MinGW/Driver.cpp and lld/test/MinGW/driver.test.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:967
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"

Do you happen to know why `LINKER_IS_LLD_LINK` gets set in this case? `ld.lld` 
(the ELF linker interface, which then the MinGW driver remaps onto the COFF 
backend with the `lld-link` interface) certainly doesn't take `lld-link` style 
options. I believe (without diving further into it) that we shouldn't be 
setting this flag in this combination, but with the option implemented, we 
should fit it into the case further above, `elseif((UNIX OR MINGW) AND 
LLVM_USE_LINKER STREQUAL "lld")`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80416: [RFC][OpenCL] Set fp contract flag on -cl-mad-enable

2020-05-22 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D80416#2050250 , @arsenm wrote:

> The langref wording makes me think this isn't quite right. This depends on 
> your definition of floating point contraction. I've always assumed it meant 
> allow FMA, potentially increasing precision. Is contracting into something 
> less precise allowed?


I don't see anywhere it says that contraction is for higher precision only. If 
I check the LLVM language manual `fast` flag implies `contract` which is what 
we are setting with `-cl-fast-relaxed-math` known to result in lower accuracy.

> If not, that's stricter / the opposite of what -cl-mad-enable implies. My 
> interpretation of the CL spec description would be to use fmuladd with an afn 
> flag (although that still can allow for increasing precision)

Currently `fmuladd` is produced with `LangOptions::FPM_On` that is used with 
FP_CONTRACT pragma. If I look at the documentation `LangOptions::FPM_Fast` is 
serving the same  purpose just allowing more cases to be contracted (i.e. 
across statements). Hence due to this it sets contract flag rather than 
emitting intrinsic directly providing more freedom to the backend to optimise 
and combine fused computations.


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

https://reviews.llvm.org/D80416



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


[PATCH] D80427: [analyzer] SumTimerInfo.py: Partially modernize

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, dcoughlin.
Herald added subscribers: cfe-commits, ASDenysPetrov, Charusso, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80427

Files:
  clang/utils/analyzer/SumTimerInfo.py

Index: clang/utils/analyzer/SumTimerInfo.py
===
--- clang/utils/analyzer/SumTimerInfo.py
+++ clang/utils/analyzer/SumTimerInfo.py
@@ -6,8 +6,6 @@
 Statistics are enabled by passing '-internal-stats' option to scan-build
 (or '-analyzer-stats' to the analyzer).
 """
-from __future__ import absolute_import, division, print_function
-
 import sys
 
 if __name__ == '__main__':
@@ -17,64 +15,65 @@
 sys.exit(-1)
 
 f = open(sys.argv[1], 'r')
-Time = 0.0
-TotalTime = 0.0
-MaxTime = 0.0
-Warnings = 0
-Count = 0
-FunctionsAnalyzed = 0
-ReachableBlocks = 0
-ReachedMaxSteps = 0
-NumSteps = 0
-NumInlinedCallSites = 0
-NumBifurcatedCallSites = 0
-MaxCFGSize = 0
+time = 0.0
+total_time = 0.0
+max_time = 0.0
+warnings = 0
+count = 0
+functions_analyzed = 0
+reachable_blocks = 0
+reached_max_steps = 0
+num_steps = 0
+num_inlined_call_sites = 0
+num_bifurcated_call_sites = 0
+max_cfg_size = 0
+
 for line in f:
-if ("Analyzer Total Time" in line):
+if "Analyzer total time" in line:
 s = line.split()
-Time = Time + float(s[6])
-Count = Count + 1
-if (float(s[6]) > MaxTime):
-MaxTime = float(s[6])
-if ("warning generated." in line) or ("warnings generated" in line):
+time = time + float(s[6])
+count = count + 1
+if float(s[6]) > max_time:
+max_time = float(s[6])
+if "warning generated." in line or "warnings generated" in line:
 s = line.split()
-Warnings = Warnings + int(s[0])
+warnings = warnings + int(s[0])
 if "The # of functions analysed (as top level)" in line:
 s = line.split()
-FunctionsAnalyzed = FunctionsAnalyzed + int(s[0])
+functions_analyzed = functions_analyzed + int(s[0])
 if "The % of reachable basic blocks" in line:
 s = line.split()
-ReachableBlocks = ReachableBlocks + int(s[0])
+reachable_blocks = reachable_blocks + int(s[0])
 if "The # of times we reached the max number of steps" in line:
 s = line.split()
-ReachedMaxSteps = ReachedMaxSteps + int(s[0])
+reached_max_steps = reached_max_steps + int(s[0])
 if "The maximum number of basic blocks in a function" in line:
 s = line.split()
-if MaxCFGSize < int(s[0]):
-MaxCFGSize = int(s[0])
+if max_cfg_size < int(s[0]):
+max_cfg_size = int(s[0])
 if "The # of steps executed" in line:
 s = line.split()
-NumSteps = NumSteps + int(s[0])
+num_steps = num_steps + int(s[0])
 if "The # of times we inlined a call" in line:
 s = line.split()
-NumInlinedCallSites = NumInlinedCallSites + int(s[0])
+num_inlined_call_sites = num_inlined_call_sites + int(s[0])
 if "The # of times we split the path due \
 to imprecise dynamic dispatch info" in line:
 s = line.split()
-NumBifurcatedCallSites = NumBifurcatedCallSites + int(s[0])
+num_bifurcated_call_sites = num_bifurcated_call_sites + int(s[0])
 if ")  Total" in line:
 s = line.split()
-TotalTime = TotalTime + float(s[6])
+total_time = total_time + float(s[6])
 
-print("TU Count %d" % (Count))
-print("Time %f" % (Time))
-print("Warnings %d" % (Warnings))
-print("Functions Analyzed %d" % (FunctionsAnalyzed))
-print("Reachable Blocks %d" % (ReachableBlocks))
-print("Reached Max Steps %d" % (ReachedMaxSteps))
-print("Number of Steps %d" % (NumSteps))
-print("Number of Inlined calls %d (bifurcated %d)" % (
-NumInlinedCallSites, NumBifurcatedCallSites))
-print("MaxTime %f" % (MaxTime))
-print("TotalTime %f" % (TotalTime))
-print("Max CFG Size %d" % (MaxCFGSize))
+print(f"TU count {count}")
+print(f"Time {time}")
+print(f"Warnings {warnings}")
+print(f"Functions analyzed {functions_analyzed}")
+print(f"Reachable blocks {reachable_blocks}")
+print(f"Reached max steps {reached_max_steps}")
+print(f"Number of steps {num_steps}")
+print(f"Number of inlined calls {num_inlined_call_sites} "
+  f"(bifurcated {num_bifurcated_call_sites})")
+print(f"Max time {max_time}")
+print(f"Total time {total_time}")
+print(

[PATCH] D80294: Add support for vmsumudm

2020-05-22 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai accepted this revision.
nemanjai added a comment.
This revision is now accepted and ready to land.

LGTM.


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

https://reviews.llvm.org/D80294



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


[PATCH] D80423: [analyzer] SATestBuild.py: Refactor and add type annotations

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Nice!

I guess next time it'd be easier to review if you split up style changes from 
structural changes.




Comment at: clang/utils/analyzer/SATestBuild.py:276
 
-AllCheckers = Checkers
-if 'SA_ADDITIONAL_CHECKERS' in os.environ:
-AllCheckers = AllCheckers + ',' + os.environ['SA_ADDITIONAL_CHECKERS']
+if TYPE_CHECKING:
+ProjectQueue = Queue[ProjectInfo]  # this is only processed by mypy

What's this idiom? Like, can you explain why do we have to do this?



Comment at: clang/utils/analyzer/SATestBuild.py:284
+"""
+A component all of the project testing.
+"""

Something's missing in this sentence.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80423



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


[PATCH] D80424: [analyzer] SATestUtils.py: Refactor and add type annotations

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Sure thanks!




Comment at: clang/utils/analyzer/SATestUtils.py:47
+root, ext = os.path.splitext(file_name)
+return ext in (".i", ".ii", ".c", ".cpp", ".m", "")
 

Oof this list is weird.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80424



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


[PATCH] D80423: [analyzer] SATestBuild.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 265691.
vsavchenko added a comment.

Fix code review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80423

Files:
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py

Index: clang/utils/analyzer/SATestUpdateDiffs.py
===
--- clang/utils/analyzer/SATestUpdateDiffs.py
+++ clang/utils/analyzer/SATestUpdateDiffs.py
@@ -21,21 +21,22 @@
 
 
 def updateReferenceResults(ProjName, ProjBuildMode):
-ProjDir = SATestBuild.getProjectDir(ProjName)
+ProjInfo = SATestBuild.ProjectInfo(ProjName, ProjBuildMode)
+ProjTester = SATestBuild.ProjectTester(ProjInfo)
+ProjDir = ProjTester.get_project_dir()
 
-RefResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=True))
-CreatedResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
+ProjTester.is_reference_build = True
+RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+
+ProjTester.is_reference_build = False
+CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
 
 if not os.path.exists(CreatedResultsPath):
 print("New results not found, was SATestBuild.py "
   "previously run?", file=sys.stderr)
 sys.exit(1)
 
-BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath)
+BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
 Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
 runCmd("mkdir -p '%s'" % Dirname)
 with open(BuildLogPath, "w+") as PBuildLogFile:
@@ -50,13 +51,13 @@
stdout=PBuildLogFile)
 
 # Run cleanup script.
-SATestBuild.runCleanupScript(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
 
-SATestBuild.normalizeReferenceResults(
+SATestBuild.normalize_reference_results(
 ProjDir, RefResultsPath, ProjBuildMode)
 
 # Clean up the generated difference results.
-SATestBuild.cleanupReferenceResults(RefResultsPath)
+SATestBuild.cleanup_reference_results(RefResultsPath)
 
 runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
 
@@ -69,8 +70,8 @@
   file=sys.stderr)
 sys.exit(1)
 
-with SATestBuild.projectFileHandler() as f:
-for (ProjName, ProjBuildMode) in SATestBuild.iterateOverProjects(f):
+with open(SATestBuild.get_project_map_path(), "r") as f:
+for ProjName, ProjBuildMode in SATestBuild.get_projects(f):
 updateReferenceResults(ProjName, int(ProjBuildMode))
 
 
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -45,7 +45,6 @@
 import CmpRuns
 import SATestUtils
 
-from subprocess import CalledProcessError, check_call
 import argparse
 import csv
 import glob
@@ -59,59 +58,33 @@
 import threading
 import time
 
-try:
-import queue
-except ImportError:
-import Queue as queue
+from queue import Queue
+from subprocess import CalledProcessError, check_call
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
+TYPE_CHECKING)
+
 
 ###
 # Helper functions.
 ###
 
-Local = threading.local()
-Local.stdout = sys.stdout
-Local.stderr = sys.stderr
-logging.basicConfig(
-level=logging.DEBUG,
-format='%(asctime)s:%(levelname)s:%(name)s: %(message)s')
-
+LOCAL = threading.local()
+LOCAL.stdout = sys.stdout
+LOCAL.stderr = sys.stderr
 
-class StreamToLogger:
-def __init__(self, logger, log_level=logging.INFO):
-self.logger = logger
-self.log_level = log_level
 
-def write(self, buf):
-# Rstrip in order not to write an extra newline.
-self.logger.log(self.log_level, buf.rstrip())
+def stderr(message: str):
+LOCAL.stderr.write(message)
 
-def flush(self):
-pass
 
-def fileno(self):
-return 0
+def stdout(message: str):
+LOCAL.stdout.write(message)
 
 
-def getProjectMapPath():
-ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
-  ProjectMapFile)
-if not os.path.exists(ProjectMapPath):
-Local.stdout.write("Error: Cannot find the Project Map file " +
-   ProjectMapPath +
-   "\nRunning script for the wrong directory?\n")
-sys.exit(1)
-return ProjectMapPath
-
-
-def getProjectDir(ID):
-return os.path.join(os.path.abspath(os.curdir), ID)
-
+logging.basicConfig(
+

[PATCH] D80427: [analyzer] SumTimerInfo.py: Partially modernize

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

This one's straightforward too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80427



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


[PATCH] D77542: [PowerPC] Treat 'Z' inline asm constraint as a true memory constraint

2020-05-22 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai marked an inline comment as done.
nemanjai added inline comments.



Comment at: clang/test/CodeGen/ppc64-inline-asm.c:50
+// CHECK-LABEL: void @testZwOff(i8* %addr, i64 %off)
+// CHEC: %[[VAL:[^ ]+]] = getelementptr i8, i8* %addr, i64 %off
+// CHEC: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* 
%[[VAL]])

amyk wrote:
> Missing a `k` in `CHECK`?
Great catch! Thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77542



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


[clang] e95ee30 - [SYCL] Prohibit arithmetic operations for incompatible pointers

2020-05-22 Thread Alexey Bader via cfe-commits

Author: Alexey Bader
Date: 2020-05-22T13:43:24+03:00
New Revision: e95ee300c0530158d86430fd82ffabd36262e862

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

LOG: [SYCL] Prohibit arithmetic operations for incompatible pointers

Summary:
This change enables OpenCL diagnostics for the pointers annotated with
address space attribute SYCL mode.

Move `isAddressSpaceOverlapping` method from PointerType to QualType.

Reviewers: Anastasia, rjmccall

Reviewed By: rjmccall

Subscribers: rjmccall, jeroen.dobbelaere, Fznamznon, yaxunl, ebevhan, 
cfe-commits

Tags: #clang

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

Added: 
clang/test/SemaCXX/address-space-arithmetic.cpp

Modified: 
clang/include/clang/AST/Type.h
clang/lib/Sema/SemaCast.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/address_spaces.c

Removed: 




diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 21b14de997cb..ed31dea925f3 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1064,6 +1064,21 @@ class QualType {
   /// Return the address space of this type.
   inline LangAS getAddressSpace() const;
 
+  /// Returns true if address space qualifiers overlap with T address space
+  /// qualifiers.
+  /// OpenCL C defines conversion rules for pointers to 
diff erent address spaces
+  /// and notion of overlapping address spaces.
+  /// CL1.1 or CL1.2:
+  ///   address spaces overlap iff they are they same.
+  /// OpenCL C v2.0 s6.5.5 adds:
+  ///   __generic overlaps with any address space except for __constant.
+  bool isAddressSpaceOverlapping(QualType T) const {
+Qualifiers Q = getQualifiers();
+Qualifiers TQ = T.getQualifiers();
+// Address spaces overlap if at least one of them is a superset of another
+return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
+  }
+
   /// Returns gc attribute of this type.
   inline Qualifiers::GC getObjCGCAttr() const;
 
@@ -2631,22 +2646,6 @@ class PointerType : public Type, public 
llvm::FoldingSetNode {
 public:
   QualType getPointeeType() const { return PointeeType; }
 
-  /// Returns true if address spaces of pointers overlap.
-  /// OpenCL v2.0 defines conversion rules for pointers to 
diff erent
-  /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
-  /// address spaces.
-  /// CL1.1 or CL1.2:
-  ///   address spaces overlap iff they are they same.
-  /// CL2.0 adds:
-  ///   __generic overlaps with any address space except for __constant.
-  bool isAddressSpaceOverlapping(const PointerType &other) const {
-Qualifiers thisQuals = PointeeType.getQualifiers();
-Qualifiers otherQuals = other.getPointeeType().getQualifiers();
-// Address spaces overlap if at least one of them is a superset of another
-return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
-   otherQuals.isAddressSpaceSupersetOf(thisQuals);
-  }
-
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
 

diff  --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index a4fe90f79eb9..fe4fcdd01301 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -2391,7 +2391,7 @@ static TryCastResult TryAddressSpaceCast(Sema &Self, 
ExprResult &SrcExpr,
 return TC_NotApplicable;
   auto SrcPointeeType = SrcPtrType->getPointeeType();
   auto DestPointeeType = DestPtrType->getPointeeType();
-  if (!DestPtrType->isAddressSpaceOverlapping(*SrcPtrType)) {
+  if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
 return TC_Failed;
   }
@@ -2434,9 +2434,9 @@ void CastOperation::checkAddressSpaceCast(QualType 
SrcType, QualType DestType) {
   const PointerType *SrcPPtr = cast(SrcPtr);
   QualType DestPPointee = DestPPtr->getPointeeType();
   QualType SrcPPointee = SrcPPtr->getPointeeType();
-  if (Nested ? DestPPointee.getAddressSpace() !=
-   SrcPPointee.getAddressSpace()
- : !DestPPtr->isAddressSpaceOverlapping(*SrcPPtr)) {
+  if (Nested
+  ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
+  : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
 Self.Diag(OpRange.getBegin(), DiagID)
 << SrcType << DestType << Sema::AA_Casting
 << SrcExpr.get()->getSourceRange();

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 93e67ad2940c..261e69b44052 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -10087,10 +10087,8 @@ static bool checkArithmeticBinOpPointerOperands(Sema 
&S, SourceLocation Loc,
   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()

[clang] 7cebfa4 - [analyzer] SATestUtils.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2020-05-22T13:51:58+03:00
New Revision: 7cebfa4e069265a146186e90bfa0a36135bf8aba

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

LOG: [analyzer] SATestUtils.py: Refactor and add type annotations

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

Added: 


Modified: 
clang/utils/analyzer/SATestBuild.py
clang/utils/analyzer/SATestUtils.py

Removed: 




diff  --git a/clang/utils/analyzer/SATestBuild.py 
b/clang/utils/analyzer/SATestBuild.py
index 09f2bc14c8bc..39fa7ece4362 100755
--- a/clang/utils/analyzer/SATestBuild.py
+++ b/clang/utils/analyzer/SATestBuild.py
@@ -60,8 +60,8 @@
 
 from queue import Queue
 from subprocess import CalledProcessError, check_call
-from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
-TYPE_CHECKING)
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Optional,
+Tuple, TYPE_CHECKING)
 
 
 ###
@@ -93,13 +93,15 @@ def stdout(message: str):
 
 # Find Clang for static analysis.
 if 'CC' in os.environ:
-CLANG = os.environ['CC']
+cc_candidate: Optional[str] = os.environ['CC']
 else:
-CLANG = SATestUtils.which("clang", os.environ['PATH'])
-if not CLANG:
+cc_candidate = SATestUtils.which("clang", os.environ['PATH'])
+if not cc_candidate:
 stderr("Error: cannot find 'clang' in PATH")
 sys.exit(1)
 
+CLANG = cc_candidate
+
 # Number of jobs.
 MAX_JOBS = int(math.ceil(multiprocessing.cpu_count() * 0.75))
 
@@ -204,8 +206,9 @@ def run_cleanup_script(directory: str, build_log_file: IO):
 cwd = os.path.join(directory, PATCHED_SOURCE_DIR_NAME)
 script_path = os.path.join(directory, CLEANUP_SCRIPT)
 
-SATestUtils.runScript(script_path, build_log_file, cwd,
-  Stdout=LOCAL.stdout, Stderr=LOCAL.stderr)
+SATestUtils.run_script(script_path, build_log_file, cwd,
+   out=LOCAL.stdout, err=LOCAL.stderr,
+   verbose=VERBOSE)
 
 
 def download_and_patch(directory: str, build_log_file: IO):
@@ -238,8 +241,9 @@ def download(directory: str, build_log_file: IO):
 Run the script to download the project, if it exists.
 """
 script_path = os.path.join(directory, DOWNLOAD_SCRIPT)
-SATestUtils.runScript(script_path, build_log_file, directory,
-  Stdout=LOCAL.stdout, Stderr=LOCAL.stderr)
+SATestUtils.run_script(script_path, build_log_file, directory,
+   out=LOCAL.stdout, err=LOCAL.stderr,
+   verbose=VERBOSE)
 
 
 def apply_patch(directory: str, build_log_file: IO):
@@ -557,9 +561,9 @@ def analyze_preprocessed(self, directory: str, output_dir: 
str):
 failed = False
 
 # Only run the analyzes on supported files.
-if SATestUtils.hasNoExtension(file_name):
+if SATestUtils.has_no_extension(file_name):
 continue
-if not SATestUtils.isValidSingleInputFile(file_name):
+if not SATestUtils.is_valid_single_input_file(file_name):
 stderr(f"Error: Invalid single input file {full_file_name}.\n")
 raise Exception()
 
@@ -859,7 +863,7 @@ def get_projects(map_file: IO) -> Iterable[Tuple[str, str]]:
 map_file.seek(0)
 # TODO: csv format is not very readable, change it to JSON
 for project_info in csv.reader(map_file):
-if (SATestUtils.isCommentCSVLine(project_info)):
+if SATestUtils.is_comment_csv_line(project_info):
 continue
 # suppress mypy error
 yield cast(Tuple[str, str], project_info)

diff  --git a/clang/utils/analyzer/SATestUtils.py 
b/clang/utils/analyzer/SATestUtils.py
index 079b06a4cbb7..4e126e66b869 100644
--- a/clang/utils/analyzer/SATestUtils.py
+++ b/clang/utils/analyzer/SATestUtils.py
@@ -1,12 +1,11 @@
 import os
-from subprocess import check_call
 import sys
 
+from subprocess import CalledProcessError, check_call
+from typing import List, IO, Optional
 
-Verbose = 1
 
-
-def which(command, paths=None):
+def which(command: str, paths: Optional[str] = None) -> Optional[str]:
 """which(command, [paths]) - Look up the given command in the paths string
 (or the PATH environment variable, if unspecified)."""
 
@@ -38,41 +37,44 @@ def which(command, paths=None):
 return None
 
 
-def hasNoExtension(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return (Ext == "")
+def has_no_extension(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext == ""
 
 
-def isValidSingleInputFile(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return Ext in (".i", ".ii", ".c", "

[clang] 4902ca6 - [analyzer] SATestBuild.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2020-05-22T13:51:58+03:00
New Revision: 4902ca6da49b10dbc62e8e02109bf84ce96c94b5

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

LOG: [analyzer] SATestBuild.py: Refactor and add type annotations

Summary:
SATest scripts should be more python-style than they are now.
This includes better architecture, type annotations, naming
convesions, and up-to-date language features.  This commit starts
with two scripts SATestBuild and SATestAdd.

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

Added: 


Modified: 
clang/utils/analyzer/SATestAdd.py
clang/utils/analyzer/SATestBuild.py
clang/utils/analyzer/SATestUpdateDiffs.py

Removed: 




diff  --git a/clang/utils/analyzer/SATestAdd.py 
b/clang/utils/analyzer/SATestAdd.py
index e0e267bb259b..012d8ec3fd9a 100755
--- a/clang/utils/analyzer/SATestAdd.py
+++ b/clang/utils/analyzer/SATestAdd.py
@@ -42,75 +42,80 @@
   
diff  -ur CachedSource PatchedSource \
   > changes_for_analyzer.patch
 """
-from __future__ import absolute_import, division, print_function
 import SATestBuild
 
-import os
 import csv
+import os
 import sys
 
+from typing import IO
 
-def isExistingProject(PMapFile, projectID):
-PMapReader = csv.reader(PMapFile)
-for ProjectInfo in PMapReader:
-if projectID == ProjectInfo[0]:
-return True
-return False
 
-
-def addNewProject(ID, BuildMode):
+def add_new_project(name: str, build_mode: int):
 """
 Add a new project for testing: build it and add to the Project Map file.
-:param ID: is a short string used to identify a project.
+:param name: is a short string used to identify a project.
 """
 
-CurDir = os.path.abspath(os.curdir)
-Dir = SATestBuild.getProjectDir(ID)
-if not os.path.exists(Dir):
-print("Error: Project directory is missing: %s" % Dir)
+project_info = SATestBuild.ProjectInfo(name, build_mode,
+   is_reference_build=True)
+tester = SATestBuild.ProjectTester(project_info)
+
+project_dir = tester.get_project_dir()
+if not os.path.exists(project_dir):
+print(f"Error: Project directory is missing: {project_dir}")
 sys.exit(-1)
 
 # Build the project.
-# TODO: Repair this call.  We give it a wrong amount wrong arguments and it
-#   is not trivial to construct argparse arguments in here.
-#   Requires refactoring of the 'testProject' function.
-SATestBuild.testProject(ID, BuildMode, IsReferenceBuild=True)
+tester.test()
 
-# Add the project ID to the project map.
-ProjectMapPath = os.path.join(CurDir, SATestBuild.ProjectMapFile)
+# Add the project name to the project map.
+project_map_path = SATestBuild.get_project_map_path(should_exist=False)
 
-if os.path.exists(ProjectMapPath):
-FileMode = "r+"
+if os.path.exists(project_map_path):
+file_mode = "r+"
 else:
-print("Warning: Creating the Project Map file!!")
-FileMode = "w+"
+print("Warning: Creating the project map file!")
+file_mode = "w+"
 
-with open(ProjectMapPath, FileMode) as PMapFile:
-if (isExistingProject(PMapFile, ID)):
-print('Warning: Project with ID \'', ID,
-  '\' already exists.', file=sys.stdout)
+with open(project_map_path, file_mode) as map_file:
+if is_existing_project(map_file, name):
+print(f"Warning: Project with name '{name}' already exists.",
+  file=sys.stdout)
 print("Reference output has been regenerated.", file=sys.stdout)
 else:
-PMapWriter = csv.writer(PMapFile)
-PMapWriter.writerow((ID, int(BuildMode)))
-print("The project map is updated: ", ProjectMapPath)
+map_writer = csv.writer(map_file)
+map_writer.writerow((name, build_mode))
+print(f"The project map is updated: {project_map_path}")
+
 
+def is_existing_project(map_file: IO, project_name: str) -> bool:
+map_reader = csv.reader(map_file)
 
+for raw_info in map_reader:
+if project_name == raw_info[0]:
+return True
+
+return False
+
+
+# TODO: Use argparse
 # TODO: Add an option not to build.
 # TODO: Set the path to the Repository directory.
-if __name__ == '__main__':
-if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
-print('Add a new project for testing to the analyzer'
-  '\nUsage: ', sys.argv[0],
-  'project_ID \n'
-  'mode: 0 for single file project, '
-  '1 for scan_build, '
-  '2 for single file c++11 project', file=sys.stder

[clang] 5a9aff1 - [analyzer] SATestUpdateDiffs.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2020-05-22T13:51:58+03:00
New Revision: 5a9aff12ff3bc68109f41930ec296b7a19cbe76c

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

LOG: [analyzer] SATestUpdateDiffs.py: Refactor and add type annotations

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

Added: 


Modified: 
clang/utils/analyzer/SATestUpdateDiffs.py

Removed: 




diff  --git a/clang/utils/analyzer/SATestUpdateDiffs.py 
b/clang/utils/analyzer/SATestUpdateDiffs.py
index ac2832d40e6e..e89b06dd75eb 100755
--- a/clang/utils/analyzer/SATestUpdateDiffs.py
+++ b/clang/utils/analyzer/SATestUpdateDiffs.py
@@ -3,67 +3,67 @@
 """
 Update reference results for static analyzer.
 """
-from __future__ import absolute_import, division, print_function
-
 import SATestBuild
 
-from subprocess import check_call
 import os
+import shutil
 import sys
 
+from subprocess import check_call
+
 Verbose = 0
 
 
-def runCmd(Command, **kwargs):
-if Verbose:
-print("Executing %s" % Command)
-check_call(Command, shell=True, **kwargs)
+def update_reference_results(project_name: str, build_mode: int):
+project_info = SATestBuild.ProjectInfo(project_name, build_mode)
+tester = SATestBuild.ProjectTester(project_info)
+project_dir = tester.get_project_dir()
 
+tester.is_reference_build = True
+ref_results_path = os.path.join(project_dir, tester.get_output_dir())
 
-def updateReferenceResults(ProjName, ProjBuildMode):
-ProjInfo = SATestBuild.ProjectInfo(ProjName, ProjBuildMode)
-ProjTester = SATestBuild.ProjectTester(ProjInfo)
-ProjDir = ProjTester.get_project_dir()
+tester.is_reference_build = False
+created_results_path = os.path.join(project_dir, tester.get_output_dir())
 
-ProjTester.is_reference_build = True
-RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+if not os.path.exists(created_results_path):
+print("New results not found, was SATestBuild.py previously run?",
+  file=sys.stderr)
+sys.exit(1)
 
-ProjTester.is_reference_build = False
-CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+build_log_path = SATestBuild.get_build_log_path(ref_results_path)
+build_log_dir = os.path.dirname(os.path.abspath(build_log_path))
 
-if not os.path.exists(CreatedResultsPath):
-print("New results not found, was SATestBuild.py "
-  "previously run?", file=sys.stderr)
-sys.exit(1)
+os.makedirs(build_log_dir)
+
+with open(build_log_path, "w+") as build_log_file:
+def run_cmd(command: str):
+if Verbose:
+print(f"Executing {command}")
+check_call(command, shell=True, stdout=build_log_file)
 
-BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
-Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
-runCmd("mkdir -p '%s'" % Dirname)
-with open(BuildLogPath, "w+") as PBuildLogFile:
 # Remove reference results: in git, and then again for a good measure
 # with rm, as git might not remove things fully if there are empty
 # directories involved.
-runCmd('git rm -r -q "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
-runCmd('rm -rf "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
+run_cmd(f"git rm -r -q '{ref_results_path}'")
+shutil.rmtree(ref_results_path)
 
 # Replace reference results with a freshly computed once.
-runCmd('cp -r "%s" "%s"' % (CreatedResultsPath, RefResultsPath,),
-   stdout=PBuildLogFile)
+shutil.copytree(created_results_path, ref_results_path, symlinks=True)
 
 # Run cleanup script.
-SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(project_dir, build_log_file)
 
 SATestBuild.normalize_reference_results(
-ProjDir, RefResultsPath, ProjBuildMode)
+project_dir, ref_results_path, build_mode)
 
 # Clean up the generated 
diff erence results.
-SATestBuild.cleanup_reference_results(RefResultsPath)
+SATestBuild.cleanup_reference_results(ref_results_path)
 
-runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
+run_cmd(f"git add '{ref_results_path}'")
 
 
 def main(argv):
-if len(argv) == 2 and argv[1] in ('-h', '--help'):
+if len(argv) == 2 and argv[1] in ("-h", "--help"):
 print("Update static analyzer reference results based "
   "\non the previous run of SATestBuild.py.\n"
   "\nN.B.: Assumes that SATestBuild.py was just run",
@@ -71,8 +71,8 @@ def main(argv):
 sys.exit(1)
 
 with open(SATestBuild.get_project_map_path(), "r") as f:
-for ProjName, ProjBui

[clang] 475d120 - [analyzer] SumTimerInfo.py: Partially modernize

2020-05-22 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2020-05-22T13:51:58+03:00
New Revision: 475d1202837071959f3f69d3512c820538d81543

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

LOG: [analyzer] SumTimerInfo.py: Partially modernize

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

Added: 


Modified: 
clang/utils/analyzer/SumTimerInfo.py

Removed: 




diff  --git a/clang/utils/analyzer/SumTimerInfo.py 
b/clang/utils/analyzer/SumTimerInfo.py
index 5d86f763f001..eed17e02e32e 100644
--- a/clang/utils/analyzer/SumTimerInfo.py
+++ b/clang/utils/analyzer/SumTimerInfo.py
@@ -6,8 +6,6 @@
 Statistics are enabled by passing '-internal-stats' option to scan-build
 (or '-analyzer-stats' to the analyzer).
 """
-from __future__ import absolute_import, division, print_function
-
 import sys
 
 if __name__ == '__main__':
@@ -17,64 +15,65 @@
 sys.exit(-1)
 
 f = open(sys.argv[1], 'r')
-Time = 0.0
-TotalTime = 0.0
-MaxTime = 0.0
-Warnings = 0
-Count = 0
-FunctionsAnalyzed = 0
-ReachableBlocks = 0
-ReachedMaxSteps = 0
-NumSteps = 0
-NumInlinedCallSites = 0
-NumBifurcatedCallSites = 0
-MaxCFGSize = 0
+time = 0.0
+total_time = 0.0
+max_time = 0.0
+warnings = 0
+count = 0
+functions_analyzed = 0
+reachable_blocks = 0
+reached_max_steps = 0
+num_steps = 0
+num_inlined_call_sites = 0
+num_bifurcated_call_sites = 0
+max_cfg_size = 0
+
 for line in f:
-if ("Analyzer Total Time" in line):
+if "Analyzer total time" in line:
 s = line.split()
-Time = Time + float(s[6])
-Count = Count + 1
-if (float(s[6]) > MaxTime):
-MaxTime = float(s[6])
-if ("warning generated." in line) or ("warnings generated" in line):
+time = time + float(s[6])
+count = count + 1
+if float(s[6]) > max_time:
+max_time = float(s[6])
+if "warning generated." in line or "warnings generated" in line:
 s = line.split()
-Warnings = Warnings + int(s[0])
+warnings = warnings + int(s[0])
 if "The # of functions analysed (as top level)" in line:
 s = line.split()
-FunctionsAnalyzed = FunctionsAnalyzed + int(s[0])
+functions_analyzed = functions_analyzed + int(s[0])
 if "The % of reachable basic blocks" in line:
 s = line.split()
-ReachableBlocks = ReachableBlocks + int(s[0])
+reachable_blocks = reachable_blocks + int(s[0])
 if "The # of times we reached the max number of steps" in line:
 s = line.split()
-ReachedMaxSteps = ReachedMaxSteps + int(s[0])
+reached_max_steps = reached_max_steps + int(s[0])
 if "The maximum number of basic blocks in a function" in line:
 s = line.split()
-if MaxCFGSize < int(s[0]):
-MaxCFGSize = int(s[0])
+if max_cfg_size < int(s[0]):
+max_cfg_size = int(s[0])
 if "The # of steps executed" in line:
 s = line.split()
-NumSteps = NumSteps + int(s[0])
+num_steps = num_steps + int(s[0])
 if "The # of times we inlined a call" in line:
 s = line.split()
-NumInlinedCallSites = NumInlinedCallSites + int(s[0])
+num_inlined_call_sites = num_inlined_call_sites + int(s[0])
 if "The # of times we split the path due \
 to imprecise dynamic dispatch info" in line:
 s = line.split()
-NumBifurcatedCallSites = NumBifurcatedCallSites + int(s[0])
+num_bifurcated_call_sites = num_bifurcated_call_sites + int(s[0])
 if ")  Total" in line:
 s = line.split()
-TotalTime = TotalTime + float(s[6])
+total_time = total_time + float(s[6])
 
-print("TU Count %d" % (Count))
-print("Time %f" % (Time))
-print("Warnings %d" % (Warnings))
-print("Functions Analyzed %d" % (FunctionsAnalyzed))
-print("Reachable Blocks %d" % (ReachableBlocks))
-print("Reached Max Steps %d" % (ReachedMaxSteps))
-print("Number of Steps %d" % (NumSteps))
-print("Number of Inlined calls %d (bifurcated %d)" % (
-NumInlinedCallSites, NumBifurcatedCallSites))
-print("MaxTime %f" % (MaxTime))
-print("TotalTime %f" % (TotalTime))
-print("Max CFG Size %d" % (MaxCFGSize))
+print(f"TU count {count}")
+print(f"Time {time}")
+print(f"Warnings {warnings}")
+print(f"Functions analyzed {functions_analyzed}")
+print(f"Reachable blocks {reachable_blocks}")
+print(f"Reached max steps {reached_max_steps}")
+print(f"Number of steps {num_steps

[clang] bf897e6 - Remove superfluous semicolon to stop Wpedantic warning. NFCI.

2020-05-22 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-05-22T12:05:56+01:00
New Revision: bf897e6ea122c07b8848133beee749fd96895c14

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

LOG: Remove superfluous semicolon to stop Wpedantic warning. NFCI.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index cb76f576ac34..168cfd511170 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -55,7 +55,7 @@ const CXXRecordDecl *isRefCountable(const CXXBaseSpecifier 
*Base) {
 return nullptr;
 
   return hasPublicRefAndDeref(R) ? R : nullptr;
-};
+}
 
 bool isRefCountable(const CXXRecordDecl *R) {
   assert(R);



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


[clang] 733505a - Replace dyn_cast<> with isa<> to fix unused variable warning. NFCI.

2020-05-22 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-05-22T12:05:56+01:00
New Revision: 733505abf471b66458a9eab24521dba9a4b6239e

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

LOG: Replace dyn_cast<> with isa<> to fix unused variable warning. NFCI.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index adb6253df965..cb76f576ac34 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -114,7 +114,7 @@ bool isUncountedPtr(const Type *T) {
 bool isGetterOfRefCounted(const CXXMethodDecl *M) {
   assert(M);
 
-  if (auto *calleeMethodDecl = dyn_cast(M)) {
+  if (isa(M)) {
 const CXXRecordDecl *calleeMethodsClass = M->getParent();
 auto className = safeGetName(calleeMethodsClass);
 auto methodName = safeGetName(M);



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


[PATCH] D71739: [AssumeBundles] Use operand bundles to encode alignment assumptions

2020-05-22 Thread Tyker via Phabricator via cfe-commits
Tyker added a comment.

In D71739#2048409 , @rjmccall wrote:

> Is there a good reason for this to use the same `llvm.assume` intrinsic as 
> before?


thee hasn't been any discussion i am aware of on this topic.
but personally i think keeping the same intrinsic makes sens because it 
logically expresses an assumption hence `assume` is a good name.
and most passes don't need to treat classic assumes differently from assume 
with operand bundles.

> Are there restrictions about what assumptions can be combined on a single 
> intrinsic call?  There can only be one bundle of a particular name on an 
> instruction, right?

there is any IR legality restriction about what combination or number of 
bundles can be present in an assume. however there is restrictions about 
argument of a given bundle.
having a single "align" bundle is just how the front-end used assume bundles 
for its alignment assumptions.

for example:
to salvage a store like 
`store i8 0, i8* %P, align 1`
we could generate
`call void @llvm.assume(i1 true) [ "dereferenceable"(i8* %P, i64 1), 
"nonnull"(i8* %P) ]`




Comment at: llvm/lib/Analysis/AssumeBundleQueries.cpp:104
+return 1;
+  };
   if (BOI.End - BOI.Begin > ABA_Argument)

jdoerfert wrote:
> I think this is a problem for things like `deref` which should default to 0?
currently only Alignment can have a non constant argument. but yes this will 
change if we support non-constant integer for deref.

the verifier has been updated this way, but i added an assert to make it clear.



Comment at: llvm/lib/Analysis/AssumeBundleQueries.cpp:110
+if (BOI.End - BOI.Begin > ABA_Argument + 1)
+  Result.ArgValue = MinAlign(Result.ArgValue, GetArgOr1(1));
   return Result;

jdoerfert wrote:
> Is this the min of the alignment and offset? If so, I'm not sure about min. 
> Either way, can you clang format this and add a comment why alignment is 
> special and how it looks?
> Is this the min of the alignment and offset?
Yes
> If so, I'm not sure about min
the objective of this is to make sure that getKnowledgeFromBundle doesn't 
misinterpret the contents of a bundles with a non-zero offset.
the description of MinAlign seems to match with what i needed
```
/// A and B are either alignments or offsets. Return the minimum alignment that
/// may be assumed after adding the two together.
```
the results seems to be correct aswell.



Comment at: llvm/lib/IR/Verifier.cpp:4418
+if (ArgCount == 3)
+  Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(), 
"third argument should be an integer if present");
+return;

rjmccall wrote:
> Should the alignment and offset be restricted to constants and given value 
> restrictions?
the system operand bundles are replacing could deal with non-constant indexes 
and offsets
so i adapted alignment assume bundles to handle non-constant arguments.



Comment at: llvm/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp:273
+  if (!isValidAssumeForContext(ACall, J, DT))
+continue;
   Align NewDestAlignment =

jdoerfert wrote:
> I'm curious, why was this needed? 
this code is part of the from the previous version of the patch, i left it 
untouched because it seemed to work as intended.

changes in this function seem to have no impact on the resulting behavior. and 
could be removed.



Comment at: llvm/test/Transforms/InstCombine/assume.ll:380
 ; CHECK-NEXT:[[CMP2:%.*]] = icmp ne i8 [[X:%.*]], 0
+; CHECK-NEXT:tail call void @llvm.assume(i1 false)
 ; CHECK-NEXT:tail call void @llvm.dbg.value(metadata i32 5, metadata !7, 
metadata !DIExpression()), !dbg !9

jdoerfert wrote:
> Can you add the "beginning" of the operand bundles here so it becomes clear 
> we do not have a no-op assume.
i don't think `call void @llvm.assume(i1 false)` is no-op since it exhibits UB. 
but it is redundant.
anyway this has been split of to an other patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71739



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


[PATCH] D79842: [clang][Driver] Correct tool search path priority

2020-05-22 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett updated this revision to Diff 265694.
DavidSpickett added a comment.

- Addressed comments from nickdesaulniers


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79842

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/program-path-priority.c
  clang/test/lit.cfg.py

Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -46,6 +46,8 @@
 config.substitutions.append(
 ('%src_include_dir', config.clang_src_dir + '/include'))
 
+config.substitutions.append(
+('%target_triple', config.target_triple))
 
 # Propagate path to symbolizer for ASan/MSan.
 llvm_config.with_system_environment(
Index: clang/test/Driver/program-path-priority.c
===
--- /dev/null
+++ clang/test/Driver/program-path-priority.c
@@ -0,0 +1,112 @@
+// Check the priority used when searching for tools
+// Names and locations are usually in this order:
+// -tool, tool, -tool
+// program path, PATH
+// (from highest to lowest priority)
+// A higher priority name found in a lower priority
+// location will win over a lower priority name in a
+// higher priority location.
+// Prefix dirs (added with -B) override the location,
+// so only name priority is accounted for, unless we fail to find
+// anything at all in the prefix.
+
+// Copy clang to a new dir which will be its
+// "program path" for these tests
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: cp %clang %t
+
+// No gccs at all, nothing is found
+// RUN: env "PATH=" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=NO_NOTREAL_GCC %s
+// NO_NOTREAL_GCC-NOT: notreal-none-elf-gcc
+// NO_NOTREAL_GCC-NOT: {{/|}}gcc
+
+// -gcc in program path is found
+// RUN: touch %t/notreal-none-elf-gcc
+// RUN: chmod +x %t/notreal-none-elf-gcc
+// RUN: env "PATH=" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=PROG_PATH_NOTREAL_GCC %s
+// PROG_PATH_NOTREAL_GCC: notreal-none-elf-gcc
+
+// -gcc on the PATH is found
+// RUN: mkdir -p %t/env
+// RUN: rm %t/notreal-none-elf-gcc
+// RUN: touch %t/env/notreal-none-elf-gcc
+// RUN: chmod +x %t/env/notreal-none-elf-gcc
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=ENV_PATH_NOTREAL_GCC %s
+// ENV_PATH_NOTREAL_GCC: env{{/|}}notreal-none-elf-gcc
+
+// -gcc in program path is preferred to one on the PATH
+// RUN: touch %t/notreal-none-elf-gcc
+// RUN: chmod +x %t/notreal-none-elf-gcc
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=BOTH_NOTREAL_GCC %s
+// BOTH_NOTREAL_GCC: notreal-none-elf-gcc
+// BOTH_NOTREAL_GCC-NOT: env{{/|}}notreal-none-elf-gcc
+
+// On program path, -gcc is preferred to plain gcc
+// RUN: touch %t/gcc
+// RUN: chmod +x %t/gcc
+// RUN: env "PATH=" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=NOTREAL_GCC_PREFERRED %s
+// NOTREAL_GCC_PREFERRED: notreal-none-elf-gcc
+// NOTREAL_GCC_PREFERRED-NOT: {{/|}}gcc
+
+// -gcc on the PATH is preferred to gcc in program path
+// RUN: rm %t/notreal-none-elf-gcc
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=NOTREAL_PATH_OVER_GCC_PROG %s
+// NOTREAL_PATH_OVER_GCC_PROG: env{{/|}}notreal-none-elf-gcc
+// NOTREAL_PATH_OVER_GCC_PROG-NOT: {{/|}}gcc
+
+// -gcc on the PATH is preferred to gcc on the PATH
+// RUN: rm %t/gcc
+// RUN: touch %t/env/gcc
+// RUN: chmod +x %t/env/gcc
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=NOTREAL_PATH_OVER_GCC_PATH %s
+// NOTREAL_PATH_OVER_GCC_PATH: env{{/|}}notreal-none-elf-gcc
+// NOTREAL_PATH_OVER_GCC_PATH-NOT: {{/|}}gcc
+
+// -gcc has lowest priority
+// RUN: touch %t/%target_triple-gcc
+// RUN: chmod +x %t/%target_triple-gcc
+
+// -gcc on PATH beats default triple in program path
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=DEFAULT_TRIPLE_GCC %s
+// DEFAULT_TRIPLE_GCC: env{{/|}}notreal-none-elf-gcc
+
+// plain gcc on PATH beats default triple in program path
+// RUN: rm %t/env/notreal-none-elf-gcc
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=DEFAULT_TRIPLE_NO_NOTREAL %s
+// DEFAULT_TRIPLE_NO_NOTREAL: env{{/|}}gcc
+// DEFAULT_TRIPLE_NO_NOTREAL-NOT: -gcc
+
+// default triple only chosen when no others are present
+// RUN: rm %t/env/gcc
+// RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 \
+// RUN: | FileCheck --check-prefix=DEFAULT_TRIPLE_NO_OTHERS %s
+// DEFAULT_TRIPLE_NO_OTHERS: -gcc
+// DEFAULT_TRIPLE_NO_OTHERS-NOT: notreal-none-elf-gcc
+// DEFAULT_TR

[PATCH] D79842: [clang][Driver] Correct tool search path priority

2020-05-22 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

Comments on cfe-dev 
(http://lists.llvm.org/pipermail/cfe-dev/2020-May/065432.html) also in favour 
of removing the default triple lookup. I tend to agree but think it makes more 
sense to land this first and address it in a follow up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79842



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


[PATCH] D80317: [SYCL] Prohibit arithmetic operations for incompatible pointers

2020-05-22 Thread Alexey Bader via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe95ee300c053: [SYCL] Prohibit arithmetic operations for 
incompatible pointers (authored by bader).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80317

Files:
  clang/include/clang/AST/Type.h
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/address_spaces.c
  clang/test/SemaCXX/address-space-arithmetic.cpp

Index: clang/test/SemaCXX/address-space-arithmetic.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/address-space-arithmetic.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int *foo(__attribute__((opencl_private)) int *p,
+ __attribute__((opencl_local)) int *l) {
+  return p - l; // expected-error {{arithmetic operation with operands of type  ('__private int *' and '__local int *') which are pointers to non-overlapping address spaces}}
+}
Index: clang/test/Sema/address_spaces.c
===
--- clang/test/Sema/address_spaces.c
+++ clang/test/Sema/address_spaces.c
@@ -74,6 +74,10 @@
   return x < y ? x : y; // expected-error{{conditional operator with the second and third operands of type  ('_AS1 char *' and '_AS2 char *') which are pointers to non-overlapping address spaces}}
 }
 
+char *sub(_AS1 char *x, _AS2 char *y) {
+  return x - y; // expected-error {{arithmetic operation with operands of type  ('_AS1 char *' and '_AS2 char *') which are pointers to non-overlapping address spaces}}
+}
+
 struct SomeStruct {
   int a;
   long b;
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -10087,10 +10087,8 @@
   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
 
   // if both are pointers check if operation is valid wrt address spaces
-  if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
-const PointerType *lhsPtr = LHSExpr->getType()->castAs();
-const PointerType *rhsPtr = RHSExpr->getType()->castAs();
-if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
+  if (isLHSPointer && isRHSPointer) {
+if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
   S.Diag(Loc,
  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
   << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
@@ -11444,8 +11442,7 @@
 if (LCanPointeeTy != RCanPointeeTy) {
   // Treat NULL constant as a special case in OpenCL.
   if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
-const PointerType *LHSPtr = LHSType->castAs();
-if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs())) {
+if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
   Diag(Loc,
diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
   << LHSType << RHSType << 0 /* comparison */
Index: clang/lib/Sema/SemaCast.cpp
===
--- clang/lib/Sema/SemaCast.cpp
+++ clang/lib/Sema/SemaCast.cpp
@@ -2391,7 +2391,7 @@
 return TC_NotApplicable;
   auto SrcPointeeType = SrcPtrType->getPointeeType();
   auto DestPointeeType = DestPtrType->getPointeeType();
-  if (!DestPtrType->isAddressSpaceOverlapping(*SrcPtrType)) {
+  if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
 return TC_Failed;
   }
@@ -2434,9 +2434,9 @@
   const PointerType *SrcPPtr = cast(SrcPtr);
   QualType DestPPointee = DestPPtr->getPointeeType();
   QualType SrcPPointee = SrcPPtr->getPointeeType();
-  if (Nested ? DestPPointee.getAddressSpace() !=
-   SrcPPointee.getAddressSpace()
- : !DestPPtr->isAddressSpaceOverlapping(*SrcPPtr)) {
+  if (Nested
+  ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
+  : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
 Self.Diag(OpRange.getBegin(), DiagID)
 << SrcType << DestType << Sema::AA_Casting
 << SrcExpr.get()->getSourceRange();
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -1064,6 +1064,21 @@
   /// Return the address space of this type.
   inline LangAS getAddressSpace() const;
 
+  /// Returns true if address space qualifiers overlap with T address space
+  /// qualifiers.
+  /// OpenCL C defines conversion rules for pointers to different address spaces
+  /// and notion of overlapping address spaces.
+  /// CL1.1 or CL1.2:
+  ///   address spaces overlap iff they are they same.
+  /// OpenCL C v2.0 s6.5.5 adds:
+  ///  

[PATCH] D80423: [analyzer] SATestBuild.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4902ca6da49b: [analyzer] SATestBuild.py: Refactor and add 
type annotations (authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80423

Files:
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py

Index: clang/utils/analyzer/SATestUpdateDiffs.py
===
--- clang/utils/analyzer/SATestUpdateDiffs.py
+++ clang/utils/analyzer/SATestUpdateDiffs.py
@@ -21,21 +21,22 @@
 
 
 def updateReferenceResults(ProjName, ProjBuildMode):
-ProjDir = SATestBuild.getProjectDir(ProjName)
+ProjInfo = SATestBuild.ProjectInfo(ProjName, ProjBuildMode)
+ProjTester = SATestBuild.ProjectTester(ProjInfo)
+ProjDir = ProjTester.get_project_dir()
 
-RefResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=True))
-CreatedResultsPath = os.path.join(
-ProjDir,
-SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
+ProjTester.is_reference_build = True
+RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+
+ProjTester.is_reference_build = False
+CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
 
 if not os.path.exists(CreatedResultsPath):
 print("New results not found, was SATestBuild.py "
   "previously run?", file=sys.stderr)
 sys.exit(1)
 
-BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath)
+BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
 Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
 runCmd("mkdir -p '%s'" % Dirname)
 with open(BuildLogPath, "w+") as PBuildLogFile:
@@ -50,13 +51,13 @@
stdout=PBuildLogFile)
 
 # Run cleanup script.
-SATestBuild.runCleanupScript(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
 
-SATestBuild.normalizeReferenceResults(
+SATestBuild.normalize_reference_results(
 ProjDir, RefResultsPath, ProjBuildMode)
 
 # Clean up the generated difference results.
-SATestBuild.cleanupReferenceResults(RefResultsPath)
+SATestBuild.cleanup_reference_results(RefResultsPath)
 
 runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
 
@@ -69,8 +70,8 @@
   file=sys.stderr)
 sys.exit(1)
 
-with SATestBuild.projectFileHandler() as f:
-for (ProjName, ProjBuildMode) in SATestBuild.iterateOverProjects(f):
+with open(SATestBuild.get_project_map_path(), "r") as f:
+for ProjName, ProjBuildMode in SATestBuild.get_projects(f):
 updateReferenceResults(ProjName, int(ProjBuildMode))
 
 
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -45,7 +45,6 @@
 import CmpRuns
 import SATestUtils
 
-from subprocess import CalledProcessError, check_call
 import argparse
 import csv
 import glob
@@ -59,59 +58,33 @@
 import threading
 import time
 
-try:
-import queue
-except ImportError:
-import Queue as queue
+from queue import Queue
+from subprocess import CalledProcessError, check_call
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
+TYPE_CHECKING)
+
 
 ###
 # Helper functions.
 ###
 
-Local = threading.local()
-Local.stdout = sys.stdout
-Local.stderr = sys.stderr
-logging.basicConfig(
-level=logging.DEBUG,
-format='%(asctime)s:%(levelname)s:%(name)s: %(message)s')
-
+LOCAL = threading.local()
+LOCAL.stdout = sys.stdout
+LOCAL.stderr = sys.stderr
 
-class StreamToLogger:
-def __init__(self, logger, log_level=logging.INFO):
-self.logger = logger
-self.log_level = log_level
 
-def write(self, buf):
-# Rstrip in order not to write an extra newline.
-self.logger.log(self.log_level, buf.rstrip())
+def stderr(message: str):
+LOCAL.stderr.write(message)
 
-def flush(self):
-pass
 
-def fileno(self):
-return 0
+def stdout(message: str):
+LOCAL.stdout.write(message)
 
 
-def getProjectMapPath():
-ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
-  ProjectMapFile)
-if not os.path.exists(ProjectMapPath):
-Local.stdout.write("Error: Cannot find the Project Map file " +
-   ProjectMapPath +
-   "\nRunning script for the wrong directory?\n")
-sys.exit(1)
-return ProjectMapPath
-
-
-def getProject

[PATCH] D80426: [analyzer] SATestUpdateDiffs.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5a9aff12ff3b: [analyzer] SATestUpdateDiffs.py: Refactor and 
add type annotations (authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80426

Files:
  clang/utils/analyzer/SATestUpdateDiffs.py

Index: clang/utils/analyzer/SATestUpdateDiffs.py
===
--- clang/utils/analyzer/SATestUpdateDiffs.py
+++ clang/utils/analyzer/SATestUpdateDiffs.py
@@ -3,67 +3,67 @@
 """
 Update reference results for static analyzer.
 """
-from __future__ import absolute_import, division, print_function
-
 import SATestBuild
 
-from subprocess import check_call
 import os
+import shutil
 import sys
 
+from subprocess import check_call
+
 Verbose = 0
 
 
-def runCmd(Command, **kwargs):
-if Verbose:
-print("Executing %s" % Command)
-check_call(Command, shell=True, **kwargs)
+def update_reference_results(project_name: str, build_mode: int):
+project_info = SATestBuild.ProjectInfo(project_name, build_mode)
+tester = SATestBuild.ProjectTester(project_info)
+project_dir = tester.get_project_dir()
 
+tester.is_reference_build = True
+ref_results_path = os.path.join(project_dir, tester.get_output_dir())
 
-def updateReferenceResults(ProjName, ProjBuildMode):
-ProjInfo = SATestBuild.ProjectInfo(ProjName, ProjBuildMode)
-ProjTester = SATestBuild.ProjectTester(ProjInfo)
-ProjDir = ProjTester.get_project_dir()
+tester.is_reference_build = False
+created_results_path = os.path.join(project_dir, tester.get_output_dir())
 
-ProjTester.is_reference_build = True
-RefResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+if not os.path.exists(created_results_path):
+print("New results not found, was SATestBuild.py previously run?",
+  file=sys.stderr)
+sys.exit(1)
 
-ProjTester.is_reference_build = False
-CreatedResultsPath = os.path.join(ProjDir, ProjTester.get_output_dir())
+build_log_path = SATestBuild.get_build_log_path(ref_results_path)
+build_log_dir = os.path.dirname(os.path.abspath(build_log_path))
 
-if not os.path.exists(CreatedResultsPath):
-print("New results not found, was SATestBuild.py "
-  "previously run?", file=sys.stderr)
-sys.exit(1)
+os.makedirs(build_log_dir)
+
+with open(build_log_path, "w+") as build_log_file:
+def run_cmd(command: str):
+if Verbose:
+print(f"Executing {command}")
+check_call(command, shell=True, stdout=build_log_file)
 
-BuildLogPath = SATestBuild.get_build_log_path(RefResultsPath)
-Dirname = os.path.dirname(os.path.abspath(BuildLogPath))
-runCmd("mkdir -p '%s'" % Dirname)
-with open(BuildLogPath, "w+") as PBuildLogFile:
 # Remove reference results: in git, and then again for a good measure
 # with rm, as git might not remove things fully if there are empty
 # directories involved.
-runCmd('git rm -r -q "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
-runCmd('rm -rf "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
+run_cmd(f"git rm -r -q '{ref_results_path}'")
+shutil.rmtree(ref_results_path)
 
 # Replace reference results with a freshly computed once.
-runCmd('cp -r "%s" "%s"' % (CreatedResultsPath, RefResultsPath,),
-   stdout=PBuildLogFile)
+shutil.copytree(created_results_path, ref_results_path, symlinks=True)
 
 # Run cleanup script.
-SATestBuild.run_cleanup_script(ProjDir, PBuildLogFile)
+SATestBuild.run_cleanup_script(project_dir, build_log_file)
 
 SATestBuild.normalize_reference_results(
-ProjDir, RefResultsPath, ProjBuildMode)
+project_dir, ref_results_path, build_mode)
 
 # Clean up the generated difference results.
-SATestBuild.cleanup_reference_results(RefResultsPath)
+SATestBuild.cleanup_reference_results(ref_results_path)
 
-runCmd('git add "%s"' % (RefResultsPath,), stdout=PBuildLogFile)
+run_cmd(f"git add '{ref_results_path}'")
 
 
 def main(argv):
-if len(argv) == 2 and argv[1] in ('-h', '--help'):
+if len(argv) == 2 and argv[1] in ("-h", "--help"):
 print("Update static analyzer reference results based "
   "\non the previous run of SATestBuild.py.\n"
   "\nN.B.: Assumes that SATestBuild.py was just run",
@@ -71,8 +71,8 @@
 sys.exit(1)
 
 with open(SATestBuild.get_project_map_path(), "r") as f:
-for ProjName, ProjBuildMode in SATestBuild.get_projects(f):
-updateReferenceResults(ProjName, int(ProjBuildMode))
+for project_name, build_mode in SATestBuild.get_projects(f):
+update_reference_results(project_name, int(build_mode))
 
 
 if __nam

[PATCH] D80424: [analyzer] SATestUtils.py: Refactor and add type annotations

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7cebfa4e0692: [analyzer] SATestUtils.py: Refactor and add 
type annotations (authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80424

Files:
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUtils.py

Index: clang/utils/analyzer/SATestUtils.py
===
--- clang/utils/analyzer/SATestUtils.py
+++ clang/utils/analyzer/SATestUtils.py
@@ -1,12 +1,11 @@
 import os
-from subprocess import check_call
 import sys
 
+from subprocess import CalledProcessError, check_call
+from typing import List, IO, Optional
 
-Verbose = 1
 
-
-def which(command, paths=None):
+def which(command: str, paths: Optional[str] = None) -> Optional[str]:
 """which(command, [paths]) - Look up the given command in the paths string
 (or the PATH environment variable, if unspecified)."""
 
@@ -38,41 +37,44 @@
 return None
 
 
-def hasNoExtension(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return (Ext == "")
+def has_no_extension(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext == ""
 
 
-def isValidSingleInputFile(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return Ext in (".i", ".ii", ".c", ".cpp", ".m", "")
+def is_valid_single_input_file(file_name: str) -> bool:
+root, ext = os.path.splitext(file_name)
+return ext in (".i", ".ii", ".c", ".cpp", ".m", "")
 
 
-def runScript(ScriptPath, PBuildLogFile, Cwd, Stdout=sys.stdout,
-  Stderr=sys.stderr):
+def run_script(script_path: str, build_log_file: IO, cwd: str,
+   out=sys.stdout, err=sys.stderr, verbose: int = 0):
 """
 Run the provided script if it exists.
 """
-if os.path.exists(ScriptPath):
+if os.path.exists(script_path):
 try:
-if Verbose == 1:
-Stdout.write("  Executing: %s\n" % (ScriptPath,))
-check_call("chmod +x '%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
+if verbose == 1:
+out.write(f"  Executing: {script_path}\n")
+
+check_call(f"chmod +x '{script_path}'", cwd=cwd,
+   stderr=build_log_file,
+   stdout=build_log_file,
shell=True)
-check_call("'%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
+
+check_call(f"'{script_path}'", cwd=cwd,
+   stderr=build_log_file,
+   stdout=build_log_file,
shell=True)
-except:
-Stderr.write("Error: Running %s failed. See %s for details.\n" % (
- ScriptPath, PBuildLogFile.name))
+
+except CalledProcessError:
+err.write(f"Error: Running {script_path} failed. "
+  f"See {build_log_file.name} for details.\n")
 sys.exit(-1)
 
 
-def isCommentCSVLine(Entries):
+def is_comment_csv_line(entries: List[str]) -> bool:
 """
 Treat CSV lines starting with a '#' as a comment.
 """
-return len(Entries) > 0 and Entries[0].startswith("#")
+return len(entries) > 0 and entries[0].startswith("#")
Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -60,8 +60,8 @@
 
 from queue import Queue
 from subprocess import CalledProcessError, check_call
-from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Tuple,
-TYPE_CHECKING)
+from typing import (cast, Dict, Iterable, IO, List, NamedTuple, Optional,
+Tuple, TYPE_CHECKING)
 
 
 ###
@@ -93,13 +93,15 @@
 
 # Find Clang for static analysis.
 if 'CC' in os.environ:
-CLANG = os.environ['CC']
+cc_candidate: Optional[str] = os.environ['CC']
 else:
-CLANG = SATestUtils.which("clang", os.environ['PATH'])
-if not CLANG:
+cc_candidate = SATestUtils.which("clang", os.environ['PATH'])
+if not cc_candidate:
 stderr("Error: cannot find 'clang' in PATH")
 sys.exit(1)
 
+CLANG = cc_candidate
+
 # Number of jobs.
 MAX_JOBS = int(math.ceil(multiprocessing.cpu_count() * 0.75))
 
@@ -204,8 +206,9 @@
 cwd = os.path.join(directory, PATCHED_SOURCE_DIR_NAME)
 script_path = os.path.join(directory, CLEANUP_SCRIPT)
 
-SATestUtils.runScript(script_path, build_log_file, cwd,
-  Stdout=LOCAL.stdout, Stderr=LOCAL.stderr)
+SATestUtils.run_script(script_path, build_log_file, cwd,
+   out=LOCAL.stdout, err=LOCAL.std

[PATCH] D80427: [analyzer] SumTimerInfo.py: Partially modernize

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG475d12028370: [analyzer] SumTimerInfo.py: Partially 
modernize (authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80427

Files:
  clang/utils/analyzer/SumTimerInfo.py

Index: clang/utils/analyzer/SumTimerInfo.py
===
--- clang/utils/analyzer/SumTimerInfo.py
+++ clang/utils/analyzer/SumTimerInfo.py
@@ -6,8 +6,6 @@
 Statistics are enabled by passing '-internal-stats' option to scan-build
 (or '-analyzer-stats' to the analyzer).
 """
-from __future__ import absolute_import, division, print_function
-
 import sys
 
 if __name__ == '__main__':
@@ -17,64 +15,65 @@
 sys.exit(-1)
 
 f = open(sys.argv[1], 'r')
-Time = 0.0
-TotalTime = 0.0
-MaxTime = 0.0
-Warnings = 0
-Count = 0
-FunctionsAnalyzed = 0
-ReachableBlocks = 0
-ReachedMaxSteps = 0
-NumSteps = 0
-NumInlinedCallSites = 0
-NumBifurcatedCallSites = 0
-MaxCFGSize = 0
+time = 0.0
+total_time = 0.0
+max_time = 0.0
+warnings = 0
+count = 0
+functions_analyzed = 0
+reachable_blocks = 0
+reached_max_steps = 0
+num_steps = 0
+num_inlined_call_sites = 0
+num_bifurcated_call_sites = 0
+max_cfg_size = 0
+
 for line in f:
-if ("Analyzer Total Time" in line):
+if "Analyzer total time" in line:
 s = line.split()
-Time = Time + float(s[6])
-Count = Count + 1
-if (float(s[6]) > MaxTime):
-MaxTime = float(s[6])
-if ("warning generated." in line) or ("warnings generated" in line):
+time = time + float(s[6])
+count = count + 1
+if float(s[6]) > max_time:
+max_time = float(s[6])
+if "warning generated." in line or "warnings generated" in line:
 s = line.split()
-Warnings = Warnings + int(s[0])
+warnings = warnings + int(s[0])
 if "The # of functions analysed (as top level)" in line:
 s = line.split()
-FunctionsAnalyzed = FunctionsAnalyzed + int(s[0])
+functions_analyzed = functions_analyzed + int(s[0])
 if "The % of reachable basic blocks" in line:
 s = line.split()
-ReachableBlocks = ReachableBlocks + int(s[0])
+reachable_blocks = reachable_blocks + int(s[0])
 if "The # of times we reached the max number of steps" in line:
 s = line.split()
-ReachedMaxSteps = ReachedMaxSteps + int(s[0])
+reached_max_steps = reached_max_steps + int(s[0])
 if "The maximum number of basic blocks in a function" in line:
 s = line.split()
-if MaxCFGSize < int(s[0]):
-MaxCFGSize = int(s[0])
+if max_cfg_size < int(s[0]):
+max_cfg_size = int(s[0])
 if "The # of steps executed" in line:
 s = line.split()
-NumSteps = NumSteps + int(s[0])
+num_steps = num_steps + int(s[0])
 if "The # of times we inlined a call" in line:
 s = line.split()
-NumInlinedCallSites = NumInlinedCallSites + int(s[0])
+num_inlined_call_sites = num_inlined_call_sites + int(s[0])
 if "The # of times we split the path due \
 to imprecise dynamic dispatch info" in line:
 s = line.split()
-NumBifurcatedCallSites = NumBifurcatedCallSites + int(s[0])
+num_bifurcated_call_sites = num_bifurcated_call_sites + int(s[0])
 if ")  Total" in line:
 s = line.split()
-TotalTime = TotalTime + float(s[6])
+total_time = total_time + float(s[6])
 
-print("TU Count %d" % (Count))
-print("Time %f" % (Time))
-print("Warnings %d" % (Warnings))
-print("Functions Analyzed %d" % (FunctionsAnalyzed))
-print("Reachable Blocks %d" % (ReachableBlocks))
-print("Reached Max Steps %d" % (ReachedMaxSteps))
-print("Number of Steps %d" % (NumSteps))
-print("Number of Inlined calls %d (bifurcated %d)" % (
-NumInlinedCallSites, NumBifurcatedCallSites))
-print("MaxTime %f" % (MaxTime))
-print("TotalTime %f" % (TotalTime))
-print("Max CFG Size %d" % (MaxCFGSize))
+print(f"TU count {count}")
+print(f"Time {time}")
+print(f"Warnings {warnings}")
+print(f"Functions analyzed {functions_analyzed}")
+print(f"Reachable blocks {reachable_blocks}")
+print(f"Reached max steps {reached_max_steps}")
+print(f"Number of steps {num_steps}")
+print(f"Number of inlined calls {num_inlined_call_sites} "
+  f"(bifurcated {num_bifurcated_call_sites})")
+print(f"Max time {max_time}")
+print(f"Total time {total_time}")
+print(f"Max CFG Size {max_cfg_s

[PATCH] D80428: [clang] Optimize getFileIDLocal

2020-05-22 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

- Avoid bit operations to compute Offset by removing bitfields. On 64-bit 
architectures, SLocEntry's size is unchanged.

- Provide branch-prediction hints to compiler to generate better code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80428

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D50078: clang-format: support aligned nested conditionals formatting

2020-05-22 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

In D50078#2050623 , @MyDeveloperDay 
wrote:

> I get the point about Opt In, and if we are going to add an option it needs 
> to go in ASAP otherwise too many people will then start complaining it was on 
> by default before.
>
> To be honest I think the question is do we consider this a bug or a feature, 
> because we DO NOT provide Opt In on bug fixes (and there is no Opt Out).
>
> If its a bug, there is no need for us to not have this on by default, its 
> better to drive the improvement than 10,000's of .clang-format files needing 
> to be updated just to get reasonable behavior.


I certainly a bit biased, but I think it is more a bug: it should have been 
there from the start :-)

And I also think it should be on by default instead of modifying many 
.clang-format files. So IMHO if we add an option, it should be opt-out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D50078



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


[PATCH] D80366: [Analyzer] Add `getReturnValueUnderConstruction()` to `CallEvent`

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp:112
 
+Optional ExprEngine::retrieveFromConstructionContext(
+ProgramStateRef State, const LocationContext *LCtx,

Please instead re-use the code that computes the object under construction. 
That'll save you ~50 lines of code and will be more future-proof (eg., 
standalone temporaries without destructor technically have a construction 
context with 0 items so when we implement them correctly your procedure will 
stop working).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80366



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


[PATCH] D80286: [Analyzer] Allow creation of stack frame for functions without definition

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

This looks straightforward, thanks!




Comment at: clang/test/Analysis/explain-svals.cpp:97
 void test_6() {
-  clang_analyzer_explain(conjure_S()); // expected-warning-re^lazily 
frozen compound value of temporary object constructed at statement 
'conjure_S\(\)'$
+  clang_analyzer_explain(conjure_S()); // expected-warning-re^lazily 
frozen compound value of parameter 0 of function 
'clang_analyzer_explain\(\)'$
   clang_analyzer_explain(conjure_S().z); // expected-warning-re^value 
derived from \(symbol of type 'int' conjured at statement 'conjure_S\(\)'\) for 
field 'z' of temporary object constructed at statement 'conjure_S\(\)'$

Wonderful!

I think "parameter 1" would make a bit more sense. Or, even better, "1st 
parameter" like in regular warnings.

(this probably needs to be fixed in an older patch)



Comment at: clang/test/Analysis/temporaries.cpp:893
 glob = 1;
-// FIXME: Why is destructor not inlined in C++17
 clang_analyzer_checkInlined(true);
 #ifdef TEMPORARY_DTORS

martong wrote:
> baloghadamsoftware wrote:
> > I wonder whether `clang_analyzer_checkInlined()` works correctly with this 
> > patch: it seems it only checks for stack frame which now any function with 
> > definition can have.
> So, why not try that in a test with a function that does not have a 
> definition?
> it seems it only checks for stack frame which now any function with 
> definition can have

Before that, it checks that `clang_analyzer_checkInlined()` was evaluated 
during analysis. You can't evaluate this line if you didn't analyze `~C()` 
either as top-level function or through inlining.



Comment at: clang/unittests/StaticAnalyzer/ParamRegionTest.cpp:87
   std::make_unique(),
+  "void foo(int n); "
+  "void bar(int l); "

martong wrote:
> I think a raw string literal with clang-formatted code in it would make the 
> test more valuable.
I also think it's going to be valuable to test what's going to happen if the 
forward-declaration is //after// the definition; that's where we were 
previously confused.


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

https://reviews.llvm.org/D80286



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


[PATCH] D80416: [RFC][OpenCL] Set fp contract flag on -cl-mad-enable

2020-05-22 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked an inline comment as done.
Anastasia added inline comments.



Comment at: clang/test/CodeGenOpenCL/relaxed-fpmath.cl:21
+float fused_mad(float a, float b, float c) {
+  // NORMAL: @llvm.fmuladd.f32
+  // FAST: fmul fast float

Anastasia wrote:
> I don't find this behavior "NORMAL". I don't believe we should contract 
> expressions by default in OpenCL...
I just found in table 38 of OpenCL C spec, last entry says:


> x * y + z
> Implemented either as a correctly rounded fma or as a multiply and an add 
> both of which are correctly rounded.

In table 8 for `fma` it states:

> Returns the correctly rounded floating-point representation of the sum of c 
> with the infinitely precise product of a and b. Rounding of intermediate 
> products shall not occur. 


When I check LLVM doecumentation for fmuladd it says:

> is equivalent to the expression a * b + c, except that it is unspecified 
> whether rounding will be performed between the multiplication and addition 
> steps. Fusion is not guaranteed, even if the target platform supports it. If 
> a fused multiply-add is required, the corresponding llvm.fma intrinsic 
> function should be used instead. This never sets errno, just as ‘llvm.fma.*’.

Does this mean that rounding of an intermediate product may occur and therefore 
it is not safe to use it for OpenCL mode by default?



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

https://reviews.llvm.org/D80416



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


[PATCH] D80416: [RFC][OpenCL] Set fp contract flag on -cl-mad-enable

2020-05-22 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked an inline comment as done.
Anastasia added inline comments.



Comment at: clang/test/CodeGenOpenCL/relaxed-fpmath.cl:21
+float fused_mad(float a, float b, float c) {
+  // NORMAL: @llvm.fmuladd.f32
+  // FAST: fmul fast float

Anastasia wrote:
> Anastasia wrote:
> > I don't find this behavior "NORMAL". I don't believe we should contract 
> > expressions by default in OpenCL...
> I just found in table 38 of OpenCL C spec, last entry says:
> 
> 
> > x * y + z
> > Implemented either as a correctly rounded fma or as a multiply and an add 
> > both of which are correctly rounded.
> 
> In table 8 for `fma` it states:
> 
> > Returns the correctly rounded floating-point representation of the sum of c 
> > with the infinitely precise product of a and b. Rounding of intermediate 
> > products shall not occur. 
> 
> 
> When I check LLVM doecumentation for fmuladd it says:
> 
> > is equivalent to the expression a * b + c, except that it is unspecified 
> > whether rounding will be performed between the multiplication and addition 
> > steps. Fusion is not guaranteed, even if the target platform supports it. 
> > If a fused multiply-add is required, the corresponding llvm.fma intrinsic 
> > function should be used instead. This never sets errno, just as 
> > ‘llvm.fma.*’.
> 
> Does this mean that rounding of an intermediate product may occur and 
> therefore it is not safe to use it for OpenCL mode by default?
> 
After more digging I conclude that the use of `fmuladd` for `x * y + z` should 
be ok as per table 38 of OpenCL C because it allows either fused or non-fused 
operation i.e. it is ok if either intermediate value is rounded or not.


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

https://reviews.llvm.org/D80416



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


[PATCH] D77474: [analyzer][MallocChecker] Make NewDeleteLeaks depend on DynamicMemoryModeling rather than NewDelete

2020-05-22 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 265709.
Szelethus marked 7 inline comments as done.
Szelethus added a comment.

Fix according to reviewer comments! Thanks!


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

https://reviews.llvm.org/D77474

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/test/Analysis/Malloc+NewDelete_intersections.cpp
  clang/test/Analysis/NewDelete-checker-test.cpp
  clang/test/Analysis/NewDelete-intersections.mm
  clang/test/Analysis/new.cpp

Index: clang/test/Analysis/new.cpp
===
--- clang/test/Analysis/new.cpp
+++ clang/test/Analysis/new.cpp
@@ -115,11 +115,6 @@
   delete c;
 }
 
-//
-// Check for intersection with other checkers from MallocChecker.cpp 
-// bounded with unix.Malloc
-//
-
 // new/delete oparators are subjects of cplusplus.NewDelete.
 void testNewDeleteNoWarn() {
   int i;
@@ -135,11 +130,11 @@
   int *p3 = new int; // no-warning
 }
 
-// unix.Malloc does not know about operators new/delete.
 void testDeleteMallocked() {
   int *x = (int *)malloc(sizeof(int));
-  delete x; // FIXME: Should detect pointer escape and keep silent after 'delete' is modeled properly.
-} // expected-warning{{Potential leak of memory pointed to by 'x'}}
+  // unix.MismatchedDeallocator would catch this, but we're not testing it here.
+  delete x;
+}
 
 void testDeleteOpAfterFree() {
   int *p = (int *)malloc(sizeof(int));
Index: clang/test/Analysis/NewDelete-intersections.mm
===
--- clang/test/Analysis/NewDelete-intersections.mm
+++ clang/test/Analysis/NewDelete-intersections.mm
@@ -1,7 +1,20 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks -std=c++11 -DLEAKS -fblocks -verify %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks -std=c++11 -DLEAKS -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -std=c++11 -fblocks %s \
+// RUN:  -verify=newdelete \
+// RUN:  -analyzer-checker=core \
+// RUN:  -analyzer-checker=cplusplus.NewDelete
+
+// RUN: %clang_analyze_cc1 -std=c++11 -DLEAKS -fblocks %s \
+// RUN:   -verify=leak \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=cplusplus.NewDeleteLeaks
+
+// leak-no-diagnostics
+
+// RUN: %clang_analyze_cc1 -std=c++11 -DLEAKS -fblocks %s \
+// RUN:   -verify=mismatch \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.MismatchedDeallocator
+
 #include "Inputs/system-header-simulator-cxx.h"
 #include "Inputs/system-header-simulator-objc.h"
 
@@ -10,12 +23,6 @@
 extern "C" void *alloca(size_t);
 extern "C" void free(void *);
 
-//
-// Check for intersections with unix.Malloc and unix.MallocWithAnnotations 
-// checkers bounded with cplusplus.NewDelete.
-//
-
-//- malloc()/free() are subjects of unix.Malloc and unix.MallocWithAnnotations
 void testMallocFreeNoWarn() {
   int i;
   free(&i); // no warn
@@ -39,7 +46,8 @@
 
 void testDeleteMalloced() {
   int *p1 = (int *)malloc(sizeof(int));
-  delete p1; // no warn
+  delete p1;
+  // mismatch-warning@-1{{Memory allocated by malloc() should be deallocated by free(), not 'delete'}}
 
   int *p2 = (int *)__builtin_alloca(sizeof(int));
   delete p2; // no warn
@@ -54,35 +62,30 @@
 void testFreeOpNew() {
   void *p = operator new(0);
   free(p);
+  // mismatch-warning@-1{{Memory allocated by operator new should be deallocated by 'delete', not free()}}
 }
-#ifdef LEAKS
-// expected-warning@-2 {{Potential leak of memory pointed to by 'p'}}
-#endif
 
 void testFreeNewExpr() {
   int *p = new int;
   free(p);
+  // mismatch-warning@-1{{Memory allocated by 'new' should be deallocated by 'delete', not free()}}
+  free(p);
 }
-#ifdef LEAKS
-// expected-warning@-2 {{Potential leak of memory pointed to by 'p'}}
-#endif
 
 void testObjcFreeNewed() {
   int *p = new int;
   NSData *nsdata = [NSData dataWithBytesNoCopy:p length:sizeof(int) freeWhenDone:1];
-#ifdef LEAKS
-  // expected-warning@-2 {{Potential leak of memory pointed to by 'p'}}
-#endif
+  // mismatch-warning@-1{{+dataWithBytesNoCopy:length:freeWhenDone: cannot take ownership of memory allocated by 'new'}}
 }
 
 void testFreeAfterDelete() {
   int *p = new int;  
   delete p;
-  free(p); // expected-warning{{Use of memory after it is freed}}
+  free(p); // newdelete-

[PATCH] D77474: [analyzer][MallocChecker] Make NewDeleteLeaks depend on DynamicMemoryModeling rather than NewDelete

2020-05-22 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:195
+// Say this 3 times fast.
+State = State ? State : getState();
+addTransition(State, generateSink(State, getPredecessor()));

martong wrote:
> balazske wrote:
> > ```
> > if (!State)
> >   State = getState();
> > ```
> > is better? (I put the same comment into some (other?) patch already but 
> > maybe it disappeared?)
> +1 for balazske's suggestion.
Landed this part of the change in D77866.



Comment at: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp:2024
+  if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) 
{
+C.addSink();
 return;

martong wrote:
> This seems to be inverse logic to me.
> I'd expect that in a function called `Report...` we do stuff that is related 
> to reporting only. That is why I think it would be better to have the 
> condition and addSink before calling `Report...`. That way reporting and 
> modeling would be even more separated.
Very good point, but I think the actual problem lies in the name of the method. 
`ReportBadFree` in particular is called from multiple places, and I like how 
this is the function that takes over once we find a bug, because a bad free 
(which in this context means the deallocation of a non-heap allocated object) 
can never be a non-fatal error, so it make sense that the sink is solved here.


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

https://reviews.llvm.org/D77474



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


[PATCH] D79754: [OpenMP][AMDGCN] Support OpenMP offloading for AMDGCN architecture - Part 1

2020-05-22 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 265716.
saiislam added a comment.
Herald added a subscriber: sstefan1.

Added test case to show treatment of specific functions as builtins or 
functions on the device


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79754

Files:
  clang/lib/AST/Decl.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/openmp-offload-gpu.c
  clang/test/OpenMP/amdgcn_device_function_call.cpp
  clang/test/OpenMP/target_parallel_no_exceptions.cpp
  llvm/include/llvm/ADT/Triple.h

Index: llvm/include/llvm/ADT/Triple.h
===
--- llvm/include/llvm/ADT/Triple.h
+++ llvm/include/llvm/ADT/Triple.h
@@ -692,6 +692,9 @@
 return getArch() == Triple::nvptx || getArch() == Triple::nvptx64;
   }
 
+  /// Tests whether the target is AMDGCN
+  bool isAMDGCN() const { return getArch() == Triple::amdgcn; }
+
   bool isAMDGPU() const {
 return getArch() == Triple::r600 || getArch() == Triple::amdgcn;
   }
Index: clang/test/OpenMP/target_parallel_no_exceptions.cpp
===
--- clang/test/OpenMP/target_parallel_no_exceptions.cpp
+++ clang/test/OpenMP/target_parallel_no_exceptions.cpp
@@ -1,6 +1,7 @@
 /// Make sure no exception messages are inclided in the llvm output.
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHK-EXCEPTION
+// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHK-EXCEPTION
 
 void test_increment() {
 #pragma omp target
Index: clang/test/OpenMP/amdgcn_device_function_call.cpp
===
--- /dev/null
+++ clang/test/OpenMP/amdgcn_device_function_call.cpp
@@ -0,0 +1,33 @@
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-ppc-host.bc
+// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple amdgcn-amd-amdhsa -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s
+// RUN: llvm-dis < %t-ppc-host.bc | FileCheck %s -check-prefix=HOST
+
+// device side declarations
+#pragma omp declare target
+float logf(float __x);
+extern "C" int printf(const char *format, ...);
+#pragma omp end declare target
+
+// host side declaration
+extern "C" float cosf(float __x);
+
+void test_amdgcn_openmp_device(float __x) {
+  // the default case where predefined library functions are treated as
+  // builtins on the host
+  // HOST: call float @llvm.cos.f32(float
+  __x = cosf(__x);
+
+#pragma omp target
+  {
+// logf should be treated as user defined device function and not as
+// builtin on device
+// CHECK: call float @_Z4logff(float
+__x = logf(__x);
+
+// printf should be treated as a builtin on the device
+// CHECK: call i32 (i8*, ...) @printf(
+printf("%f ", __x);
+  }
+}
Index: clang/test/Driver/openmp-offload-gpu.c
===
--- clang/test/Driver/openmp-offload-gpu.c
+++ clang/test/Driver/openmp-offload-gpu.c
@@ -6,6 +6,7 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: powerpc-registered-target
 // REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
 
 /// ###
 
@@ -254,7 +255,7 @@
 // RUN:   | FileCheck -check-prefix=CUDA_MODE %s
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -fno-openmp-cuda-mode -fopenmp-cuda-mode 2>&1 \
 // RUN:   | FileCheck -check-prefix=CUDA_MODE %s
-// CUDA_MODE: clang{{.*}}"-cc1"{{.*}}"-triple" "nvptx64-nvidia-cuda"
+// CUDA_MODE: clang{{.*}}"-cc1"{{.*}}"-triple" "{{nvptx64-nvidia-cuda|amdgcn-amd-amdhsa}}"
 // CUDA_MODE-SAME: "-fopenmp-cuda-mode"
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -fno-openmp-cuda-mode 2>&1 \
 // RUN:   | FileCheck -check-prefix=NO_CUDA_MODE %s
@@ -262,11 +263,20 @@
 // RUN:   | FileCheck -check-prefix=NO_CUDA_MODE %s
 // NO_CUDA_MODE-NOT: "-{{fno-|f}}openmp-cuda-mode"
 
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target -march=gfx906 %s -fopenmp-cuda-mode 2>&1 \
+// RUN:   | 

[PATCH] D80428: [clang] Optimize getFileIDLocal

2020-05-22 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 265717.
melver added a comment.

Extra unlikely hint.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80428

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
@@ -900,7 +900,7 @@
 // If the middle index contains the value, succeed and return.
 // FIXME: This could be made faster by using a function that's aware of
 // being in the local area.
-if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
+if (LLVM_UNLIKELY(isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset))) 
{
   FileID Res = FileID::get(MiddleIndex);
 
   // If this isn't a macro expansion, remember it.  We have good locality
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
@@ -900,7 +900,7 @@
 // If the middle index contains the value, succeed and return.
 // FIXME: This could be made faster by using a function that's aware of
 // being in the local area.
-if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
+if (LLVM_UNLIKELY(isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset))) {
   FileID Res = FileID::get(MiddleIndex);
 
   // If this isn't a macro expansion, remember it.  We have good locality
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80416: [RFC][OpenCL] Set fp contract flag on -cl-mad-enable

2020-05-22 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

I think the contract flag needs clarification. I would interpret an instruction 
with only a contract flag as meaning allow precision increasing FMA formation, 
and contract+afn to mean combining while reducing precision


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

https://reviews.llvm.org/D80416



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


[PATCH] D80366: [Analyzer] Add `getReturnValueUnderConstruction()` to `CallEvent`

2020-05-22 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/CallEvent.cpp:552
+
+  Index = StackFrame->getIndex();
+

baloghadamsoftware wrote:
> Szelethus wrote:
> > This mustn't be serious. `StackFrameContext::getIndex()` has **no 
> > comments** at all! So it is an index to the element within a `CFGBlock` to 
> > which it also stores a field for??? Ugh. Shouldn't we just have a 
> > `getCallSiteCFGElement` or something? Especially since we have 
> > `CFGElementRef`s now.
> > 
> > Would you be so nice to hunt this down please? :)
> Do you mean a new `StackFrameContext::getCFGElement()` member function? I 
> agree. I can do it, however this technology where we get the block and the 
> index separately is used at many places in the code, then it would be 
> appropriate to refactor all these places. Even wrose is the backward 
> direction, where we look for the CFG element of a statement: we find the 
> block from `CFGStmtMap` and then we search for the index **liearly**, instrad 
> of storing it in the map as well!!!
Nasty. Yeah, I mean not to burden you work refactoring any more then you feel 
like doing it, but simply adding a `StackFrameContext::getCFGElement()` method 
and using it in this patch would be nice enough, and some comments to 
`getIndex()`. But this obviously isn't a high prio issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80366



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


[clang] aede24e - [PowerPC] Treat 'Z' inline asm constraint as a true memory constraint

2020-05-22 Thread Nemanja Ivanovic via cfe-commits

Author: Nemanja Ivanovic
Date: 2020-05-22T07:59:21-05:00
New Revision: aede24ecaa08db806fb173faf2de9cff95df8cee

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

LOG: [PowerPC] Treat 'Z' inline asm constraint as a true memory constraint

We currently emit incorrect codegen for this constraint because we set it as a
constraint that allows registers. This will cause the value to be copied to the
stack and that address to be passed as the address. This is not what we want.

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

Differential revision: https://reviews.llvm.org/D77542

Added: 


Modified: 
clang/lib/Basic/Targets/PPC.h
clang/test/CodeGen/ppc64-inline-asm.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h
index 6261a49c4fde..7c19a96a99c7 100644
--- a/clang/lib/Basic/Targets/PPC.h
+++ b/clang/lib/Basic/Targets/PPC.h
@@ -276,11 +276,12 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
   break;
 case 'Q': // Memory operand that is an offset from a register (it is
   // usually better to use `m' or `es' in asm statements)
+  Info.setAllowsRegister();
+  LLVM_FALLTHROUGH;
 case 'Z': // Memory operand that is an indexed or indirect from a
   // register (it is usually better to use `m' or `es' in
   // asm statements)
   Info.setAllowsMemory();
-  Info.setAllowsRegister();
   break;
 case 'R': // AIX TOC entry
 case 'a': // Address operand that is an indexed or indirect from a

diff  --git a/clang/test/CodeGen/ppc64-inline-asm.c 
b/clang/test/CodeGen/ppc64-inline-asm.c
index 3e958c328f92..0b32d0bf4820 100644
--- a/clang/test/CodeGen/ppc64-inline-asm.c
+++ b/clang/test/CodeGen/ppc64-inline-asm.c
@@ -37,3 +37,16 @@ double test_fmax(double x, double y) {
 // CHECK-LABEL: double @test_fmax(double %x, double %y)
 // CHECK: call double asm "xsmaxdp ${0:x}, ${1:x}, ${2:x}", 
"=^ws,^ws,^ws"(double %x, double %y)
 }
+
+void testZ(void *addr) {
+  asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)addr) : "memory");
+// CHECK-LABEL: void @testZ(i8* %addr)
+// CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* %addr)
+}
+
+void testZwOff(void *addr, long long off) {
+  asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)(addr + off)) : 
"memory");
+// CHECK-LABEL: void @testZwOff(i8* %addr, i64 %off)
+// CHECK: %[[VAL:[^ ]+]] = getelementptr i8, i8* %addr, i64 %off
+// CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* 
%[[VAL]])
+}



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


[clang] 99b94f2 - [analyzer] LoopUnrolling: fix crash when a parameter is a loop counter.

2020-05-22 Thread Artem Dergachev via cfe-commits

Author: Artem Dergachev
Date: 2020-05-22T16:14:48+03:00
New Revision: 99b94f29ac5dbbce0585d16f631359a66f279ea4

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

LOG: [analyzer] LoopUnrolling: fix crash when a parameter is a loop counter.

When loop counter is a function parameter "isPossiblyEscaped" will not find
the variable declaration which lead to hitting "llvm_unreachable".
Parameters of reference type should be escaped like global variables;
otherwise treat them as unescaped.

Patch by Abbas Sabra!

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
clang/test/Analysis/loop-unrolling.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
index 6bc937567800..dc268e562237 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
@@ -164,6 +164,11 @@ static bool isPossiblyEscaped(const VarDecl *VD, 
ExplodedNode *N) {
   if (VD->hasGlobalStorage())
 return true;
 
+  const bool isParm = isa(VD);
+  // Reference parameters are assumed as escaped variables.
+  if (isParm && VD->getType()->isReferenceType())
+return true;
+
   while (!N->pred_empty()) {
 // FIXME: getStmtForDiagnostics() does nasty things in order to provide
 // a valid statement for body farms, do we need this behavior here?
@@ -193,6 +198,11 @@ static bool isPossiblyEscaped(const VarDecl *VD, 
ExplodedNode *N) {
 
 N = N->getFirstPred();
   }
+
+  // Parameter declaration will not be found.
+  if (isParm)
+return false;
+
   llvm_unreachable("Reached root without finding the declaration of VD");
 }
 

diff  --git a/clang/test/Analysis/loop-unrolling.cpp 
b/clang/test/Analysis/loop-unrolling.cpp
index 761bf5af6a8b..e8ba8b9476ae 100644
--- a/clang/test/Analysis/loop-unrolling.cpp
+++ b/clang/test/Analysis/loop-unrolling.cpp
@@ -499,3 +499,15 @@ void pr34943() {
 clang_analyzer_numTimesReached(); // expected-warning {{6}}
   }
 }
+
+void parm_by_value_as_loop_counter(int i) {
+  for (i = 0; i < 10; ++i) {
+clang_analyzer_numTimesReached(); // expected-warning {{10}}
+  }
+}
+
+void parm_by_ref_as_loop_counter(int &i) {
+  for (i = 0; i < 10; ++i) {
+clang_analyzer_numTimesReached(); // expected-warning {{4}}
+  }
+}



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


[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-22 Thread Tobias Hieta via Phabricator via cfe-commits
thieta marked 5 inline comments as done.
thieta added inline comments.



Comment at: clang/tools/libclang/CMakeLists.txt:71
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 

mstorsjo wrote:
> If you say this is the same way it's done elsewhere, then sure - although I 
> have no idea about what the issue is, why I haven't run into it, etc. 
> Normally you wouldn't have a `libdl` on mingw right? What's the concrete 
> issue you're running into, and in which conditions would one run into it?
The problem here is that on my system `find_library()` picks up libdl in 
`/usr/lib` and then tries to link to it and gives me an error about it. 
`HAVE_LIBDL` comes from `config-ix.cmake` where it's checked if we are on 
windows or not: 
https://github.com/llvm/llvm-project/blob/216833b32befd14079130a3b857906f4e301179c/llvm/cmake/config-ix.cmake#L101

So this is how other places uses `CMAKE_DL_LIBS` like here: 
https://github.com/llvm/llvm-project/blob/7aaff8fd2da2812a2b3cbc8a41af29774b10a7d6/llvm/lib/Support/CMakeLists.txt#L13



Comment at: llvm/cmake/modules/AddLLVM.cmake:1872
+if(CMAKE_HOST_UNIX AND NOT MINGW)
   set(dest_binary "$")
 endif()

mstorsjo wrote:
> Not entirely sure what this one does - is it just a condition that needs to 
> match the one for `create_symlink` below?
As the comment above:

```
# If you're not overriding the OUTPUT_DIR, we can make the link relative in
# the same directory.
```

so that means that it creates the symlink like `clang-10.exe -> clang.exe`

So this breaks when using the copy path below.



Comment at: llvm/cmake/modules/AddLLVM.cmake:1898
+  if(CMAKE_HOST_UNIX AND NOT MINGW)
 set(LLVM_LINK_OR_COPY create_symlink)
   else()

mstorsjo wrote:
> What's the practical issue you're trying to fix with this one here? If 
> `CMAKE_HOST_UNIX`, i.e. when cross compiling, it does work fine to create 
> symlinks (saving a bit of disk space and bandwidth). Then when transferring 
> the built products to an actual windows system, they're converted into copies 
> at some point (e.g. when zipping up the results).
The problem I tried to fix here was to avoid creating symlinks since the 
binaries under mingw is always going to be executed on windows - so yeah I 
could remove the symlinks and redo them as copies later - but I thought it 
might be better to just do it directly from the build system so that you can 
build on wsl and use it from the same dir from the windows host.

But yeah I am not married to this change - I think it's not to vital.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:957
+  #
+  # FIXME; mingw lld driver doesn't support any of the options below
   if(APPLE)

mstorsjo wrote:
> We could certainly add support for it in the mingw driver - ideally with the 
> same name as for ELF, which then would be remapped to the corresponding 
> lld-link option. This takes just a couple lines in lld/MinGW/Options.td, 
> lld/MinGW/Driver.cpp and lld/test/MinGW/driver.test.
TBH I was trying to avoid that bit of extra work :)

But yeah it would be nice to have it supported there as well - I could maintain 
this change as a patch locally if you don't think I should have this in there 
while waiting for doing the change in the lld driver.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:967
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"

mstorsjo wrote:
> Do you happen to know why `LINKER_IS_LLD_LINK` gets set in this case? 
> `ld.lld` (the ELF linker interface, which then the MinGW driver remaps onto 
> the COFF backend with the `lld-link` interface) certainly doesn't take 
> `lld-link` style options. I believe (without diving further into it) that we 
> shouldn't be setting this flag in this combination, but with the option 
> implemented, we should fit it into the case further above, `elseif((UNIX OR 
> MINGW) AND LLVM_USE_LINKER STREQUAL "lld")`
Yeah I bet that variable is set because I pass `LLVM_USE_LINKER=lld` but I 
haven't digged to deeply. I can rework the if statement here when we have the 
lld option in there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D79754: [OpenMP][AMDGCN] Support OpenMP offloading for AMDGCN architecture - Part 1

2020-05-22 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam marked 19 inline comments as done.
saiislam added inline comments.



Comment at: clang/lib/AST/Decl.cpp:3227
+  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
+return 0;
+

sameerds wrote:
> sameerds wrote:
> > This needs a test.
> This still needs a test. One that shows that specific builtins are allowed 
> and others are not.
Added test case to show difference in treatment of printf() and other 
predefined library functions, on the device.



Comment at: clang/lib/AST/Decl.cpp:3226
+  // the only special cases that are supported by device-side runtime.
+  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
+  Context.getLangOpts().OpenMPIsDevice &&

sameerds wrote:
> Why is the check for AMDGCN required here? Doesn't the language define the 
> set of supported builtins in a language-independent way? At least that seems 
> to be true for OpenCL and CUDA above.
AMDGCN check is required because this block deals with the openmp target when 
it is amdgcn. A future or existing target device might decide to deal with 
library calls in its own way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79754



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


[PATCH] D80436: [clang][docs] Document additional bits of libc that -ffreestanding envs must provide

2020-05-22 Thread Jon Roelofs via Phabricator via cfe-commits
jroelofs created this revision.
jroelofs added reviewers: jyknight, echristo.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

See also discussion following: 
http://lists.llvm.org/pipermail/llvm-dev/2012-May/050098.html


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80436

Files:
  clang/docs/CommandGuide/clang.rst


Index: clang/docs/CommandGuide/clang.rst
===
--- clang/docs/CommandGuide/clang.rst
+++ clang/docs/CommandGuide/clang.rst
@@ -246,7 +246,9 @@
 .. option:: -ffreestanding
 
  Indicate that the file should be compiled for a freestanding, not a hosted,
- environment.
+ environment. Note that it is assumed that a freestanding environment will
+ additionally provide `memcpy`, `memmove`, `memset` and `memcmp`
+ implementations, as these are needed for efficient codegen for many programs.
 
 .. option:: -fno-builtin
 


Index: clang/docs/CommandGuide/clang.rst
===
--- clang/docs/CommandGuide/clang.rst
+++ clang/docs/CommandGuide/clang.rst
@@ -246,7 +246,9 @@
 .. option:: -ffreestanding
 
  Indicate that the file should be compiled for a freestanding, not a hosted,
- environment.
+ environment. Note that it is assumed that a freestanding environment will
+ additionally provide `memcpy`, `memmove`, `memset` and `memcmp`
+ implementations, as these are needed for efficient codegen for many programs.
 
 .. option:: -fno-builtin
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80369: [DebugInfo][CallSites] Remove decl subprograms from 'retainedTypes:'

2020-05-22 Thread Djordje Todorovic via Phabricator via cfe-commits
djtodoro updated this revision to Diff 265722.
djtodoro retitled this revision from "WIP: [DebugInfo] Remove decl subprograms 
from 'retainedTypes:'" to "[DebugInfo][CallSites] Remove decl subprograms from 
'retainedTypes:'".
djtodoro added a comment.

-Remove the decls only in the case of call-site debug info


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

https://reviews.llvm.org/D80369

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-extern-call.c


Index: clang/test/CodeGen/debug-info-extern-call.c
===
--- clang/test/CodeGen/debug-info-extern-call.c
+++ clang/test/CodeGen/debug-info-extern-call.c
@@ -1,6 +1,10 @@
 // When entry values are emitted, expect a subprogram for extern decls so that
 // the dwarf generator can describe call site parameters at extern call sites.
 //
+// Initial implementation relied on the 'retainedTypes:' from the corresponding
+// DICompileUnit, so we also ensure that we do not store the extern declaration
+// subprogram into the 'retainedTypes:'.
+//
 // RUN: %clang -g -O2 -target x86_64-none-linux-gnu -S -emit-llvm %s -o - \
 // RUN:   | FileCheck %s -check-prefix=DECLS-FOR-EXTERN
 
@@ -17,6 +21,8 @@
 // RUN: %clang -g -O2 -target x86_64-none-linux-gnu -gsce -S -emit-llvm %s -o 
- \
 // RUN:   | FileCheck %s -check-prefix=NO-DECLS-FOR-EXTERN
 
+// DECLS-FOR-EXTERN-NOT: !DICompileUnit({{.*}}retainedTypes: 
![[RETTYPES:[0-9]+]]
+// DECLS-FOR-EXTERN-NOT: ![[RETTYPES]] = !{
 // DECLS-FOR-EXTERN: !DISubprogram(name: "fn1"
 // DECLS-FOR-EXTERN-NOT: !DISubprogram(name: "memcmp"
 // DECLS-FOR-EXTERN-NOT: !DISubprogram(name: "__some_reserved_name"
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3868,10 +3868,14 @@
   getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
   TParamsArray.get(), getFunctionDeclaration(D));
 
-  if (IsDeclForCallSite)
-Fn->setSubprogram(SP);
+  // ObjC expects declarations within retained types.
+  if (!IsDeclForCallSite) {
+DBuilder.retainType(SP);
+return;
+  }
 
-  DBuilder.retainType(SP);
+  Fn->setSubprogram(SP);
+  DBuilder.finalizeSubprogram(SP);
 }
 
 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,


Index: clang/test/CodeGen/debug-info-extern-call.c
===
--- clang/test/CodeGen/debug-info-extern-call.c
+++ clang/test/CodeGen/debug-info-extern-call.c
@@ -1,6 +1,10 @@
 // When entry values are emitted, expect a subprogram for extern decls so that
 // the dwarf generator can describe call site parameters at extern call sites.
 //
+// Initial implementation relied on the 'retainedTypes:' from the corresponding
+// DICompileUnit, so we also ensure that we do not store the extern declaration
+// subprogram into the 'retainedTypes:'.
+//
 // RUN: %clang -g -O2 -target x86_64-none-linux-gnu -S -emit-llvm %s -o - \
 // RUN:   | FileCheck %s -check-prefix=DECLS-FOR-EXTERN
 
@@ -17,6 +21,8 @@
 // RUN: %clang -g -O2 -target x86_64-none-linux-gnu -gsce -S -emit-llvm %s -o - \
 // RUN:   | FileCheck %s -check-prefix=NO-DECLS-FOR-EXTERN
 
+// DECLS-FOR-EXTERN-NOT: !DICompileUnit({{.*}}retainedTypes: ![[RETTYPES:[0-9]+]]
+// DECLS-FOR-EXTERN-NOT: ![[RETTYPES]] = !{
 // DECLS-FOR-EXTERN: !DISubprogram(name: "fn1"
 // DECLS-FOR-EXTERN-NOT: !DISubprogram(name: "memcmp"
 // DECLS-FOR-EXTERN-NOT: !DISubprogram(name: "__some_reserved_name"
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3868,10 +3868,14 @@
   getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
   TParamsArray.get(), getFunctionDeclaration(D));
 
-  if (IsDeclForCallSite)
-Fn->setSubprogram(SP);
+  // ObjC expects declarations within retained types.
+  if (!IsDeclForCallSite) {
+DBuilder.retainType(SP);
+return;
+  }
 
-  DBuilder.retainType(SP);
+  Fn->setSubprogram(SP);
+  DBuilder.finalizeSubprogram(SP);
 }
 
 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80369: [DebugInfo][CallSites] Remove decl subprograms from 'retainedTypes:'

2020-05-22 Thread Djordje Todorovic via Phabricator via cfe-commits
djtodoro added a comment.

In D80369#2050022 , @dblaikie wrote:

> In D80369#2048932 , @djtodoro wrote:
>
> > Still have test failing:
> >
> >   Clang :: Modules/DebugInfoTransitiveImport.m
> >   Clang :: Modules/ModuleDebugInfo.cpp
> >   Clang :: Modules/ModuleDebugInfo.m
> >   
> >
> > I haven't looked into the failures, but I guess something Objective-C++ 
> > related should be handled with some additional work here.
>
>
> These look like over-constrained/accidental tests. At least the 
> ModuleDEbugInfo.m test - the type being tested for won't be emitted, because 
> the type itself isn't in the retained types list nor is it reachable from any 
> other metadata that is going to be emitted.
>
> I think it'd probably be good to clean these tests up - and leave it to 
> @aprantl to look into if this has exposed other bugs - but the bugs are 
> already there, and this IR/debug info metadata isn't working around the bugs, 
> since the IR is going unused anyway.


Looks like ObjC expects the declarations within retained types  (based on some 
tests failures), so I left it as is (I think @aprantl can help us with that).
Therefore, this patch will remove the declarations only in the case of call 
site debug info for now.


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

https://reviews.llvm.org/D80369



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


[PATCH] D80079: [clang-format] [NFC] isCpp() is inconsistently used to mean both C++ and Objective C, add language specific isXXX() functions

2020-05-22 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

Just some thoughts.

I agree that `Style.isJavaScript()` is nicer than `Style.Language == 
FormatStyle::LK_JavaScript`, but overall the tradeoffs about adding convenience 
methods are not clear to me.

C++/ObjC/ObjC++ is special -- because ObjC++ exists I think it is useful for 
isCpp() by default to include LK_ObjC so C++ enhancements added to the 
formatter automatically also apply to ObjC++. This is also why the overall 
Clang language enum choice makes sense to me. I think we don't want to give an 
easy way for people to special case C++ excluding ObjC++. I agree that this 
makes `Style.isCpp()` confusing.

Proto/TextProto is another family that occurs frequently together (but much 
much less often than C/C++) (as the options format of .proto files is the text 
proto format).

I'd be inclined to only add convenience methods for the subsets of languages 
that we think are important together and where //improvements to one member of 
the subset are most likely to benefit or introduce regressions in other members 
of the subset//. I'd be confused if two such convenience methods shared a 
language in common.

Specifically, let's provide **exactly** these convenience methods:

  likeCpp { LK_Cpp || LK_ObjC }
  isCSharp { LK_CSharp }
  isJava { LK_Java }
  isJavaScript { LK_JavaScript }
  isTableGen { LK_TableGen }
  likeProto { LK_Proto || LK_TextProto }

and **intentionally not** provide: `isC`, `isCpp`, `isCppOrObjC`, `isObjC`, 
`isObjCpp`, `isProto` and `isTextProto`. In cases where those need to be 
distinguished, which I believe should be rare enough*, we can use 
`Style.Language` comparisons, somewhat documenting that what follows is 
non-standard, but also being very precise in each of those situations what 
exactly we mean by spelling out the comparisons in full. 
The guideline for usages would be: use the convenience methods unless you have 
a good reason not to.

//*I realize that probably the most comparisons left would be of the form 
`Style.Language == FormatStyle::LK_ObjC` (or `!=`), and that makes me sad, and 
maybe this is a good enough reason to add `isObjC` by itself, but then we would 
lose the orthogonality of the convenience methods, and we open the door for 
adding isXXX for every language kind, which will make it easier to add a 
feature for one language that ideally should automatically work by default also 
for another, so it sucks either way.//

Sidenote. For "proto" vs "protobuf" -- I don't know whether this language has 
an official name. "protobuf" could refer to "the whole ecosystem" vs. "the 
definition language (describing types)" vs "a message in binary or text 
format". But `.proto` is *the* file extension for the definition language, so I 
think that's good enough.


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

https://reviews.llvm.org/D80079



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


[PATCH] D80171: [analyzer] LoopUnrolling: fix crash when a parameter is a loop counter

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG99b94f29ac5d: [analyzer] LoopUnrolling: fix crash when a 
parameter is a loop counter. (authored by dergachev.a).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80171

Files:
  clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
  clang/test/Analysis/loop-unrolling.cpp


Index: clang/test/Analysis/loop-unrolling.cpp
===
--- clang/test/Analysis/loop-unrolling.cpp
+++ clang/test/Analysis/loop-unrolling.cpp
@@ -499,3 +499,15 @@
 clang_analyzer_numTimesReached(); // expected-warning {{6}}
   }
 }
+
+void parm_by_value_as_loop_counter(int i) {
+  for (i = 0; i < 10; ++i) {
+clang_analyzer_numTimesReached(); // expected-warning {{10}}
+  }
+}
+
+void parm_by_ref_as_loop_counter(int &i) {
+  for (i = 0; i < 10; ++i) {
+clang_analyzer_numTimesReached(); // expected-warning {{4}}
+  }
+}
Index: clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
===
--- clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
+++ clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
@@ -164,6 +164,11 @@
   if (VD->hasGlobalStorage())
 return true;
 
+  const bool isParm = isa(VD);
+  // Reference parameters are assumed as escaped variables.
+  if (isParm && VD->getType()->isReferenceType())
+return true;
+
   while (!N->pred_empty()) {
 // FIXME: getStmtForDiagnostics() does nasty things in order to provide
 // a valid statement for body farms, do we need this behavior here?
@@ -193,6 +198,11 @@
 
 N = N->getFirstPred();
   }
+
+  // Parameter declaration will not be found.
+  if (isParm)
+return false;
+
   llvm_unreachable("Reached root without finding the declaration of VD");
 }
 


Index: clang/test/Analysis/loop-unrolling.cpp
===
--- clang/test/Analysis/loop-unrolling.cpp
+++ clang/test/Analysis/loop-unrolling.cpp
@@ -499,3 +499,15 @@
 clang_analyzer_numTimesReached(); // expected-warning {{6}}
   }
 }
+
+void parm_by_value_as_loop_counter(int i) {
+  for (i = 0; i < 10; ++i) {
+clang_analyzer_numTimesReached(); // expected-warning {{10}}
+  }
+}
+
+void parm_by_ref_as_loop_counter(int &i) {
+  for (i = 0; i < 10; ++i) {
+clang_analyzer_numTimesReached(); // expected-warning {{4}}
+  }
+}
Index: clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
===
--- clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
+++ clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
@@ -164,6 +164,11 @@
   if (VD->hasGlobalStorage())
 return true;
 
+  const bool isParm = isa(VD);
+  // Reference parameters are assumed as escaped variables.
+  if (isParm && VD->getType()->isReferenceType())
+return true;
+
   while (!N->pred_empty()) {
 // FIXME: getStmtForDiagnostics() does nasty things in order to provide
 // a valid statement for body farms, do we need this behavior here?
@@ -193,6 +198,11 @@
 
 N = N->getFirstPred();
   }
+
+  // Parameter declaration will not be found.
+  if (isParm)
+return false;
+
   llvm_unreachable("Reached root without finding the declaration of VD");
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77542: [PowerPC] Treat 'Z' inline asm constraint as a true memory constraint

2020-05-22 Thread Nemanja Ivanovic via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGaede24ecaa08: [PowerPC] Treat 'Z' inline asm 
constraint as a true memory constraint (authored by nemanjai).

Changed prior to commit:
  https://reviews.llvm.org/D77542?vs=255291&id=265730#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77542

Files:
  clang/lib/Basic/Targets/PPC.h
  clang/test/CodeGen/ppc64-inline-asm.c


Index: clang/test/CodeGen/ppc64-inline-asm.c
===
--- clang/test/CodeGen/ppc64-inline-asm.c
+++ clang/test/CodeGen/ppc64-inline-asm.c
@@ -37,3 +37,16 @@
 // CHECK-LABEL: double @test_fmax(double %x, double %y)
 // CHECK: call double asm "xsmaxdp ${0:x}, ${1:x}, ${2:x}", 
"=^ws,^ws,^ws"(double %x, double %y)
 }
+
+void testZ(void *addr) {
+  asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)addr) : "memory");
+// CHECK-LABEL: void @testZ(i8* %addr)
+// CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* %addr)
+}
+
+void testZwOff(void *addr, long long off) {
+  asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)(addr + off)) : 
"memory");
+// CHECK-LABEL: void @testZwOff(i8* %addr, i64 %off)
+// CHECK: %[[VAL:[^ ]+]] = getelementptr i8, i8* %addr, i64 %off
+// CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* 
%[[VAL]])
+}
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -276,11 +276,12 @@
   break;
 case 'Q': // Memory operand that is an offset from a register (it is
   // usually better to use `m' or `es' in asm statements)
+  Info.setAllowsRegister();
+  LLVM_FALLTHROUGH;
 case 'Z': // Memory operand that is an indexed or indirect from a
   // register (it is usually better to use `m' or `es' in
   // asm statements)
   Info.setAllowsMemory();
-  Info.setAllowsRegister();
   break;
 case 'R': // AIX TOC entry
 case 'a': // Address operand that is an indexed or indirect from a


Index: clang/test/CodeGen/ppc64-inline-asm.c
===
--- clang/test/CodeGen/ppc64-inline-asm.c
+++ clang/test/CodeGen/ppc64-inline-asm.c
@@ -37,3 +37,16 @@
 // CHECK-LABEL: double @test_fmax(double %x, double %y)
 // CHECK: call double asm "xsmaxdp ${0:x}, ${1:x}, ${2:x}", "=^ws,^ws,^ws"(double %x, double %y)
 }
+
+void testZ(void *addr) {
+  asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)addr) : "memory");
+// CHECK-LABEL: void @testZ(i8* %addr)
+// CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* %addr)
+}
+
+void testZwOff(void *addr, long long off) {
+  asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)(addr + off)) : "memory");
+// CHECK-LABEL: void @testZwOff(i8* %addr, i64 %off)
+// CHECK: %[[VAL:[^ ]+]] = getelementptr i8, i8* %addr, i64 %off
+// CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(i8* %[[VAL]])
+}
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -276,11 +276,12 @@
   break;
 case 'Q': // Memory operand that is an offset from a register (it is
   // usually better to use `m' or `es' in asm statements)
+  Info.setAllowsRegister();
+  LLVM_FALLTHROUGH;
 case 'Z': // Memory operand that is an indexed or indirect from a
   // register (it is usually better to use `m' or `es' in
   // asm statements)
   Info.setAllowsMemory();
-  Info.setAllowsRegister();
   break;
 case 'R': // AIX TOC entry
 case 'a': // Address operand that is an indexed or indirect from a
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76791: [Matrix] Implement matrix index expressions ([][]).

2020-05-22 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 265728.
fhahn marked 4 inline comments as done.
fhahn added a comment.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

In D76791#2048387 , @rjmccall wrote:

> Sorry for the slow review; I'm getting crushed with review requests.


Thanks John! I've updated the patch and introduced a new MatrixSubscriptExpr. I 
think it simplifies the code in a few places and makes things clearer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76791

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/BuiltinTypes.def
  clang/include/clang/AST/ComputeDependence.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/Specifiers.h
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ComputeDependence.cpp
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprClassification.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/NSAPI.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/CodeGen/matrix-type-operators.c
  clang/test/CodeGenCXX/matrix-type-operators.cpp
  clang/test/Sema/matrix-type-operators.c
  clang/test/SemaCXX/matrix-type-operators.cpp
  clang/tools/libclang/CXCursor.cpp
  llvm/include/llvm/IR/MatrixBuilder.h

Index: llvm/include/llvm/IR/MatrixBuilder.h
===
--- llvm/include/llvm/IR/MatrixBuilder.h
+++ llvm/include/llvm/IR/MatrixBuilder.h
@@ -155,15 +155,19 @@
 return B.CreateMul(LHS, ScalarVector);
   }
 
-  /// Extracts the element at (\p Row, \p Column) from \p Matrix.
-  Value *CreateExtractMatrix(Value *Matrix, Value *Row, Value *Column,
- unsigned NumRows, Twine const &Name = "") {
-
+  /// Extracts the element at (\p RowIdx, \p ColumnIdx) from \p Matrix.
+  Value *CreateExtractElement(Value *Matrix, Value *RowIdx, Value *ColumnIdx,
+  unsigned NumRows, Twine const &Name = "") {
+
+unsigned MaxWidth = std::max(RowIdx->getType()->getScalarSizeInBits(),
+ ColumnIdx->getType()->getScalarSizeInBits());
+Type *IntTy = IntegerType::get(RowIdx->getType()->getContext(), MaxWidth);
+RowIdx = B.CreateZExt(RowIdx, IntTy);
+ColumnIdx = B.CreateZExt(ColumnIdx, IntTy);
+Value *NumRowsV = B.getIntN(MaxWidth, NumRows);
 return B.CreateExtractElement(
-Matrix,
-B.CreateAdd(
-B.CreateMul(Column, ConstantInt::get(Column->getType(), NumRows)),
-Row));
+Matrix, B.CreateAdd(B.CreateMul(ColumnIdx, NumRowsV), RowIdx),
+"matext");
   }
 };
 
Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -419,6 +419,11 @@
 K = CXCursor_ArraySubscriptExpr;
 break;
 
+  case Stmt::MatrixSubscriptExprClass:
+// TODO: add support for MatrixSubscriptExpr.
+K = CXCursor_UnexposedExpr;
+break;
+
   case Stmt::OMPArraySectionExprClass:
 K = CXCursor_OMPArraySectionExpr;
 break;
Index: clang/test/SemaCXX/matrix-type-operators.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/matrix-type-operators.cpp
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 %s -fenable-matrix -pedantic -std=c++11 -verify -triple=x86_64-apple-darwin9
+
+typedef float sx5x10_t __attribute__((matrix_type(5, 10)));
+
+sx5x10_t get_matrix();
+
+void insert(sx5x10_t a, float f) {
+  // Non integer indexes.
+  a[3][f] = 0;
+  // expected-error@-1 {{matrix column index is not an integer}}
+  a[f][9] = 0;
+  // expected-error@-1 {{matrix row index is not an integer}}
+  a[f][f] = 0;
+  // expected-error@-1 {{matrix row index is not an integer}}
+  a[0][f] = 0;
+  // expected-error@-1 {{matrix column index is not an integer}}
+
+  // Invalid element type.
+  a[3][4] = &f;
+  // expected-error@-1 {{assigning to 'float' from incompatible type 'float *'

[PATCH] D80222: Replace Clang's createRuntimeFunction with the definitions in OMPKinds.def

2020-05-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 marked an inline comment as done.
jhuber6 added inline comments.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def:244
 
-// TODO: Replace this with the real size_t type
-#define __OMP_SIZE_TYPE(NAME) OMP_TYPE(NAME, Type::getInt64Ty(Ctx))
+#define __OMP_SIZE_TYPE(NAME) OMP_TYPE(NAME, 
M.getDataLayout().getIntPtrType(Ctx))
 __OMP_SIZE_TYPE(SizeTy)

fghanim wrote:
> jdoerfert wrote:
> > jhuber6 wrote:
> > > I'm just directly getting the SizeTy from the Module, I'm not sure if 
> > > this is a permanent solution.
> > I actually think this is fine. Less burden on the frontends also. @fghanim 
> > looks good?
> Agreed. But to avoid conflict with patch D79675, let this change go in a 
> separate patch after that. This way, we can also do some clean ups related to 
> this, and add `Int8PtrPtr`, `Int8PtrPtrPtr`, and any other typing issues, 
> without delaying patch D79675 any further - I am done with that patch, and 
> made my final changes a couple of days ago.
> 
> Nit: Also, I saw below that some formatting was done. Wouldn't it be better 
> if formatting/comments related to changes in D79739, are handled as part of 
> that patch?
Doesn't this patch already support Int8PtrPtrPtr? It's the same thing as a 
VoidPtrPtrPtr which I have defined above here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80222



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


[PATCH] D80294: Add support for vmsumudm

2020-05-22 Thread Amy Kwan via Phabricator via cfe-commits
amyk accepted this revision.
amyk added a comment.

Thanks for explaining. This LGTM.


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

https://reviews.llvm.org/D80294



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


[PATCH] D80439: Replace separator in OpenMP variant name mangling.

2020-05-22 Thread Lukas Sommer via Phabricator via cfe-commits
LukasSommerTu created this revision.
LukasSommerTu added reviewers: jdoerfert, Hahnfeld.
LukasSommerTu added projects: OpenMP, clang.
Herald added subscribers: cfe-commits, sstefan1, guansong, yaxunl.

Nvidia PTX does not allow `.` to appear in identifiers, so OpenMP variant 
mangling now uses `$` to separate segments of the mangled name for variants of 
functions declared via `declare variant`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80439

Files:
  clang/include/clang/AST/Decl.h
  clang/lib/AST/OpenMPClause.cpp


Index: clang/lib/AST/OpenMPClause.cpp
===
--- clang/lib/AST/OpenMPClause.cpp
+++ clang/lib/AST/OpenMPClause.cpp
@@ -2109,22 +2109,21 @@
   std::string MangledName;
   llvm::raw_string_ostream OS(MangledName);
   for (const OMPTraitSet &Set : Sets) {
-OS << '.' << 'S' << unsigned(Set.Kind);
+OS << '$' << 'S' << unsigned(Set.Kind);
 for (const OMPTraitSelector &Selector : Set.Selectors) {
 
   bool AllowsTraitScore = false;
   bool RequiresProperty = false;
   isValidTraitSelectorForTraitSet(
   Selector.Kind, Set.Kind, AllowsTraitScore, RequiresProperty);
-  OS << '.' << 's' << unsigned(Selector.Kind);
+  OS << '$' << 's' << unsigned(Selector.Kind);
 
   if (!RequiresProperty ||
   Selector.Kind == TraitSelector::user_condition)
 continue;
 
   for (const OMPTraitProperty &Property : Selector.Properties)
-OS << '.' << 'P'
-   << getOpenMPContextTraitPropertyName(Property.Kind);
+OS << '$' << 'P' << getOpenMPContextTraitPropertyName(Property.Kind);
 }
   }
   return OS.str();
@@ -2133,7 +2132,7 @@
 OMPTraitInfo::OMPTraitInfo(StringRef MangledName) {
   unsigned long U;
   do {
-if (!MangledName.consume_front(".S"))
+if (!MangledName.consume_front("$S"))
   break;
 if (MangledName.consumeInteger(10, U))
   break;
@@ -2141,7 +2140,7 @@
 OMPTraitSet &Set = Sets.back();
 Set.Kind = TraitSet(U);
 do {
-  if (!MangledName.consume_front(".s"))
+  if (!MangledName.consume_front("$s"))
 break;
   if (MangledName.consumeInteger(10, U))
 break;
@@ -2149,11 +2148,11 @@
   OMPTraitSelector &Selector = Set.Selectors.back();
   Selector.Kind = TraitSelector(U);
   do {
-if (!MangledName.consume_front(".P"))
+if (!MangledName.consume_front("$P"))
   break;
 Selector.Properties.push_back(OMPTraitProperty());
 OMPTraitProperty &Property = Selector.Properties.back();
-std::pair PropRestPair = MangledName.split('.');
+std::pair PropRestPair = MangledName.split('$');
 Property.Kind =
 getOpenMPContextTraitPropertyKind(Set.Kind, PropRestPair.first);
 MangledName = PropRestPair.second;
Index: clang/include/clang/AST/Decl.h
===
--- clang/include/clang/AST/Decl.h
+++ clang/include/clang/AST/Decl.h
@@ -4554,7 +4554,7 @@
 /// The new name looks likes this:
 ///   + OpenMPVariantManglingSeparatorStr + 
 static constexpr StringRef getOpenMPVariantManglingSeparatorStr() {
-  return ".ompvariant";
+  return "$ompvariant";
 }
 
 } // namespace clang


Index: clang/lib/AST/OpenMPClause.cpp
===
--- clang/lib/AST/OpenMPClause.cpp
+++ clang/lib/AST/OpenMPClause.cpp
@@ -2109,22 +2109,21 @@
   std::string MangledName;
   llvm::raw_string_ostream OS(MangledName);
   for (const OMPTraitSet &Set : Sets) {
-OS << '.' << 'S' << unsigned(Set.Kind);
+OS << '$' << 'S' << unsigned(Set.Kind);
 for (const OMPTraitSelector &Selector : Set.Selectors) {
 
   bool AllowsTraitScore = false;
   bool RequiresProperty = false;
   isValidTraitSelectorForTraitSet(
   Selector.Kind, Set.Kind, AllowsTraitScore, RequiresProperty);
-  OS << '.' << 's' << unsigned(Selector.Kind);
+  OS << '$' << 's' << unsigned(Selector.Kind);
 
   if (!RequiresProperty ||
   Selector.Kind == TraitSelector::user_condition)
 continue;
 
   for (const OMPTraitProperty &Property : Selector.Properties)
-OS << '.' << 'P'
-   << getOpenMPContextTraitPropertyName(Property.Kind);
+OS << '$' << 'P' << getOpenMPContextTraitPropertyName(Property.Kind);
 }
   }
   return OS.str();
@@ -2133,7 +2132,7 @@
 OMPTraitInfo::OMPTraitInfo(StringRef MangledName) {
   unsigned long U;
   do {
-if (!MangledName.consume_front(".S"))
+if (!MangledName.consume_front("$S"))
   break;
 if (MangledName.consumeInteger(10, U))
   break;
@@ -2141,7 +2140,7 @@
 OMPTraitSet &Set = Sets.back();
 Set.Kind = TraitSet(U);
 do {
-  if (!MangledName.consume_front(".s"))
+  if (!MangledName.consume_front("$s"))
 break;
   if (MangledName.consumeInteger(10, U))
 break;
@@ -2149,11 +2148,11 @@
   OMPTraitSele

[PATCH] D80079: [clang-format] [NFC] isCpp() is inconsistently used to mean both C++ and Objective C, add language specific isXXX() functions

2020-05-22 Thread Jake Merdich via Phabricator via cfe-commits
JakeMerdichAMD added a comment.

I'm a fan of the 'like' helpers, but I'm not entirely convinced that having 
helpers for languages covered by the 'like' is a bad thing-- it just needs to 
be very explicit that you do mean only that language. For example, an 
'isObjCOnly()' would hint to reviewers that ObjC is sometimes used in 
combination with other languages and there may be a more appropriate helper (of 
course, this should be clearly documented as well).

Ultimately, I don't really care one way or the other about this, except maybe 
for the current misnomer of isCpp(), but that's my 2c.


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

https://reviews.llvm.org/D80079



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


[PATCH] D80371: [clang-tidy] Fix potential assert in use-noexcept check

2020-05-22 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Figured out the actual cause of this bug, `getExceptionSpecRange()` returns a 
null range if the function has an unknown return type

  undefined_type throws() throw();

This is the tidy output (where assertions are disabled)

  warning: dynamic exception specification '' is deprecated; consider using 
'noexcept' instead [modernize-use-noexcept]
  /home/ce/example.cpp:1:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]
  undefined_type throws() throw();
  ^
  1 warning and 1 error generated.
  Error while processing /home/ce/example.cpp.
  Found compiler error(s).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371



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


[PATCH] D79675: [OpenMP][OMPBuilder] Adding Privatization Requirements to OMPIRBuilder

2020-05-22 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D79675#2047154 , @fghanim wrote:

> In D79675#2045826 , @jdoerfert wrote:
>
> > In D79675#2045563 , @fghanim wrote:
> >
> > > So this whole thing was about moving Def.s out of `CGOMPRuntime`? Given 
> > > how low priority making the-soon-to-be-deprecated `CGOMPRuntime` use the 
> > > new Def.s is, and that I actually use these stuff as part of 
> > > the-soon-to-be-the-way-to-CG-OMP `OMPBuilder`, wouldn't it have been 
> > > better to postpone both patches until we are done with this one then add 
> > > anything I didn't have already as part of D79739 
> > >  ? It would have certainly saved 
> > > everyone a lot of time, and made more sense given that the earlier patch 
> > > came out 2 days after mine, and the other patch today? :)
> >
> >
> >
> >
> > 1. Soon is relative.
>
>
> "Soon" is indeed relative, and so is "later", and so is 99% of the words. 
> However, words have specific meanings, otherwise opposites would refer to the 
> same thing, and words become useless and meaningless. "Soon" means soon.
>
> > 2. In the meantime people work on clang and add runtime functions into the 
> > CGOMPRuntime but not into OMPKinds.def. We are playing catch up all the 
> > time, thus wasting time.
>
> Until the `OMPBuilder` becomes the way to CG OMP IR, we will always be 
> playing catch-up. All the `OMPKinds` def.s are very copy/paste-able one or 
> two-liners and very easy to move. However, the actual code to CG the IR is 
> not.


That is not true, with the other patch we require all new code gen 
functionality to list the runtime functions in OMPKinds.def.

> Therefore, I hereby declare, that henceforth, for as long as I am working on 
> the `OMPBuilder`, if people are willing to write the CG code of new things as 
> part of the `OMPBuilder`, I am happy to be the one to move the def.s for them 
> at anytime, including on my deathbed. :D
> 
>> 3. I said it before, please split them up in small pieces. It does really 
>> not help if we combine unrelated things in a single patch. It doesn't make 
>> it faster and it is not less work at the end of the day.
> 
> Johannes Comon .. This patch IS Small (~300 lines) and everything here is 
> related (with one exception below).

This is not about number of lines. Don't take my word for it, ask the community 
if you want. We want the smallest logical and testable patches possible, 
unrelated to the size. (FWIW, 300 lines is not nothing either.)

>   This patch adds 4 new  `create` calls to the `OMPBuilder` needed by the 
> privatization stuff in patches D79676 and D79677 . These calls require 
> certain runtime calls and typing def.s. It is how we have always done it for 
> any new `create` method starting with `CreateOMPParallel()`. The Def.s I 
> added are almost completely gone. The exception I mentioned earlier is the 
> pass-throughs to the `OMPBuilder`'s `IRBuilder` which were LGTM-ed early on 
> and nothing uses them yet, so it is really a non-issue.

The time spend arguing is more than splitting would have taken in the first 
place.

Conceptual parts:

- Target dependent types (which we can initialize w/o the frontend based on the 
datalayout)
- Insert point changes (which seem to be unsued in this patch)
- The create functions

With D80222  we don't need the first. If you 
think the way it's done in there is for some reason less good, please say so, 
otherwise I fail to see why we would not go ahead with that one and rebase this 
on top.
The insert point changes could probably go away, or be part of a change that 
actually replaces the `Builder.` uses with them.

> However, What wasted everyone's time my friend, is removing integral parts to 
> this patch which has two other feature patches depend on it, which meant I 
> needed to build and rebuild to make sure things still work. it would have 
> been way easier to make D79739  modify and 
> build on the typing in this one as I suggested there, and in retrospect, is 
> something I should've pushed harder for. Anyways, let's move on. :D

I don't think this is true, even if, this is not how this works. The only way 
to make fast progress is small patches. I give you almost instant feedback on 
you patches but the more is included in one, the more revision we have to go 
through. Unrelated problems stall parts we depend on.

Maybe your setup needs tweaking or you should bundle changes in smaller patch 
from the beginning to avoid this, either way, the guidelines are clear:
https://llvm.org/docs/CodeReview.html



My goal is to save us time, during development, review, maintenance, and future 
extensions. I hope you know that.




Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:62
+  /// return a copy of the current ins

[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC option -EHa)

2020-05-22 Thread Aaron Smith via Phabricator via cfe-commits
asmith added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:2003
 
+// : Under -EHa, Invoke llvm.eha.scope.begin() right after
+//  Ctor is emitted and EHStack.pushCleanup

Nit - remove name



Comment at: clang/lib/CodeGen/CGException.cpp:603
+
+  //  For IsEHa catch(...) must handle HW exception
+  //  Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions

nit - extra space after //



Comment at: clang/lib/CodeGen/CGException.cpp:1677
+  }
+} // end of for
+  }

nit -- comment about closing brace



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:600
 
+  if (LangOpts.EHAsynch) {
+getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);

nit - braces around single statement


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344



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


[PATCH] D80416: [RFC][OpenCL] Set fp contract flag on -cl-mad-enable

2020-05-22 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked an inline comment as done.
Anastasia added inline comments.



Comment at: clang/test/CodeGenOpenCL/relaxed-fpmath.cl:21
+float fused_mad(float a, float b, float c) {
+  // NORMAL: @llvm.fmuladd.f32
+  // FAST: fmul fast float

Anastasia wrote:
> Anastasia wrote:
> > Anastasia wrote:
> > > I don't find this behavior "NORMAL". I don't believe we should contract 
> > > expressions by default in OpenCL...
> > I just found in table 38 of OpenCL C spec, last entry says:
> > 
> > 
> > > x * y + z
> > > Implemented either as a correctly rounded fma or as a multiply and an add 
> > > both of which are correctly rounded.
> > 
> > In table 8 for `fma` it states:
> > 
> > > Returns the correctly rounded floating-point representation of the sum of 
> > > c with the infinitely precise product of a and b. Rounding of 
> > > intermediate products shall not occur. 
> > 
> > 
> > When I check LLVM doecumentation for fmuladd it says:
> > 
> > > is equivalent to the expression a * b + c, except that it is unspecified 
> > > whether rounding will be performed between the multiplication and 
> > > addition steps. Fusion is not guaranteed, even if the target platform 
> > > supports it. If a fused multiply-add is required, the corresponding 
> > > llvm.fma intrinsic function should be used instead. This never sets 
> > > errno, just as ‘llvm.fma.*’.
> > 
> > Does this mean that rounding of an intermediate product may occur and 
> > therefore it is not safe to use it for OpenCL mode by default?
> > 
> After more digging I conclude that the use of `fmuladd` for `x * y + z` 
> should be ok as per table 38 of OpenCL C because it allows either fused or 
> non-fused operation i.e. it is ok if either intermediate value is rounded or 
> not.
I changed my mind again. This is now covered by https://reviews.llvm.org/D80440.


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

https://reviews.llvm.org/D80416



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


[PATCH] D80440: [OpenCL] Prevent fused mul and add by default

2020-05-22 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia created this revision.
Anastasia added reviewers: rjmccall, arsenm.
Herald added subscribers: ebevhan, yaxunl, wdng.

Currently, clang will generate fused operation `fmuladd` for expressions like 
`a*b+c`. However, I can't find anything in the spec that explains this 
behavior. But clang was doing this for almost 10 years

I looked at:
**s6.13.2 **where it details fp conract pragma:

  // on-off-switch is one of ON, OFF, or DEFAULT.
  // The DEFAULT value is ON.
  #pragma OPENCL FP_CONTRACT on-off-switch

The default behavior here refers to the default value of the pragma when used 
in the source code.

**s7.4** table 38

  x * y + z
  Implemented either as a correctly rounded fma or as a multiply and an add 
both of which are correctly rounded.

This table described behavior when `-cl-unsafe-math-optimizations` flag is 
passed.

I can't find anything else that would justify allowing fused operations, 
therefore I assume this is not safe to do and can cause issues on some 
applications/targets


https://reviews.llvm.org/D80440

Files:
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGenOpenCL/relaxed-fpmath.cl
  clang/test/CodeGenOpenCL/single-precision-constant.cl


Index: clang/test/CodeGenOpenCL/single-precision-constant.cl
===
--- clang/test/CodeGenOpenCL/single-precision-constant.cl
+++ clang/test/CodeGenOpenCL/single-precision-constant.cl
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 %s -cl-single-precision-constant -emit-llvm -o - | 
FileCheck %s
 
 float fn(float f) {
-  // CHECK: tail call float @llvm.fmuladd.f32(float %f, float 2.00e+00, 
float 1.00e+00)
+  // CHECK: fmul float %f, 2.00e+00
+  // CHECK: fadd float %mul, 1.00e+00
   return f*2. + 1.;
 }
Index: clang/test/CodeGenOpenCL/relaxed-fpmath.cl
===
--- clang/test/CodeGenOpenCL/relaxed-fpmath.cl
+++ clang/test/CodeGenOpenCL/relaxed-fpmath.cl
@@ -17,7 +17,8 @@
 }
 
 float fused_mad(float a, float b, float c) {
-  // NORMAL: tail call float @llvm.fmuladd.f32(float %a, float %b, float %c)
+  // NORMAL: fmul float
+  // NORMAL: fadd float
   // FAST: fmul fast float
   // FAST: fadd fast float
   // MAD: fmul contract float
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2322,7 +2322,6 @@
 Opts.AltiVec = 0;
 Opts.ZVector = 0;
 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
-Opts.setDefaultFPContractMode(LangOptions::FPM_On);
 Opts.NativeHalfType = 1;
 Opts.NativeHalfArgsAndReturns = 1;
 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;


Index: clang/test/CodeGenOpenCL/single-precision-constant.cl
===
--- clang/test/CodeGenOpenCL/single-precision-constant.cl
+++ clang/test/CodeGenOpenCL/single-precision-constant.cl
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 %s -cl-single-precision-constant -emit-llvm -o - | FileCheck %s
 
 float fn(float f) {
-  // CHECK: tail call float @llvm.fmuladd.f32(float %f, float 2.00e+00, float 1.00e+00)
+  // CHECK: fmul float %f, 2.00e+00
+  // CHECK: fadd float %mul, 1.00e+00
   return f*2. + 1.;
 }
Index: clang/test/CodeGenOpenCL/relaxed-fpmath.cl
===
--- clang/test/CodeGenOpenCL/relaxed-fpmath.cl
+++ clang/test/CodeGenOpenCL/relaxed-fpmath.cl
@@ -17,7 +17,8 @@
 }
 
 float fused_mad(float a, float b, float c) {
-  // NORMAL: tail call float @llvm.fmuladd.f32(float %a, float %b, float %c)
+  // NORMAL: fmul float
+  // NORMAL: fadd float
   // FAST: fmul fast float
   // FAST: fadd fast float
   // MAD: fmul contract float
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2322,7 +2322,6 @@
 Opts.AltiVec = 0;
 Opts.ZVector = 0;
 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
-Opts.setDefaultFPContractMode(LangOptions::FPM_On);
 Opts.NativeHalfType = 1;
 Opts.NativeHalfArgsAndReturns = 1;
 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80415: [AIX] Add '-bcdtors:all:0:s' to linker to gather static init functions

2020-05-22 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA added inline comments.



Comment at: clang/test/Driver/aix-ld.cpp:1
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. 'bcdtors' and Arguemnt order.
+// // RUN: %clang++ -no-canonical-prefixes %s -### -o %t.o 2>&1 \

s/Arguemnt/Argument/



Comment at: clang/test/Driver/aix-ld.cpp:7
+// // RUN:   | FileCheck --check-prefix=CHECK-LD32-ARG-ORDER %s
+// // CHECK-LD32-ARG-ORDER-NOT: warning:
+// // CHECK-LD32-ARG-ORDER: {{.*}}clang++" "-cc1" "-triple" 
"powerpc-ibm-aix7.1.0.0"

Add a line between the run steps and check, and can you align things 
vertically. 

Eg. 

```
CHECK-LD32-ARG-ORDER-NOT: warning:
CHECK-LD32-ARG-ORDER: {{.*}}clang++" "-cc1" "-triple" 
"powerpc-ibm-aix7.1.0.0"
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80415



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


[PATCH] D80415: [AIX] Add '-bcdtors:all:0:s' to linker to gather static init functions

2020-05-22 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA added inline comments.



Comment at: clang/test/Driver/aix-ld.cpp:3
+// // RUN: %clang++ -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// // RUN: -Wl,-bnocdtors \
+// // RUN: -target powerpc-ibm-aix7.1.0.0 \

formatting, align with the line above


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80415



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


[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC option -EHa)

2020-05-22 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

This should likely be at least 3 patches: llvm middle-end, llvm codegen, clang.
Langref changes missing for new intrinsics.
Please post all patches with full context (`-U9`)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344



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


[PATCH] D80251: [X86] Update some av512 shift intrinsics to use "unsigned int" parameter instead of int to match Intel documentaiton

2020-05-22 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon accepted this revision.
RKSimon added a comment.
This revision is now accepted and ready to land.

In D80251#2049975 , @craig.topper 
wrote:

> In D80251#2049418 , @RKSimon wrote:
>
> > Can we add -Wsign-conversion checks to the tests? That was mentioned on 
> > PR45931
>
>
> I can. Will that do anything other than show that my test_* functions were 
> updated to match the new type?


not much other than check for regressions again tbh.

otherwise, lgtm


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

https://reviews.llvm.org/D80251



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


[PATCH] D80425: Fix LLVM/Clang builds with mingw toolchain

2020-05-22 Thread Mateusz Mikuła via Phabricator via cfe-commits
mati865 added inline comments.



Comment at: clang/tools/libclang/CMakeLists.txt:71
+  list(APPEND LIBS ${CMAKE_DL_LIBS})
 endif()
 

thieta wrote:
> mstorsjo wrote:
> > If you say this is the same way it's done elsewhere, then sure - although I 
> > have no idea about what the issue is, why I haven't run into it, etc. 
> > Normally you wouldn't have a `libdl` on mingw right? What's the concrete 
> > issue you're running into, and in which conditions would one run into it?
> The problem here is that on my system `find_library()` picks up libdl in 
> `/usr/lib` and then tries to link to it and gives me an error about it. 
> `HAVE_LIBDL` comes from `config-ix.cmake` where it's checked if we are on 
> windows or not: 
> https://github.com/llvm/llvm-project/blob/216833b32befd14079130a3b857906f4e301179c/llvm/cmake/config-ix.cmake#L101
> 
> So this is how other places uses `CMAKE_DL_LIBS` like here: 
> https://github.com/llvm/llvm-project/blob/7aaff8fd2da2812a2b3cbc8a41af29774b10a7d6/llvm/lib/Support/CMakeLists.txt#L13
I also had this issue in MSYS2 but used `-DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib` 
to get around it.
MSYS2 has Cygwin like (so UNIX like) environment in `/usr/` and `/mingw{32,64}` 
for Mingw-w64.



Comment at: llvm/cmake/modules/HandleLLVMOptions.cmake:967
CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
-  elseif(LINKER_IS_LLD_LINK)
+  elseif(LINKER_IS_LLD_LINK AND NOT MINGW)
 append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"

thieta wrote:
> mstorsjo wrote:
> > Do you happen to know why `LINKER_IS_LLD_LINK` gets set in this case? 
> > `ld.lld` (the ELF linker interface, which then the MinGW driver remaps onto 
> > the COFF backend with the `lld-link` interface) certainly doesn't take 
> > `lld-link` style options. I believe (without diving further into it) that 
> > we shouldn't be setting this flag in this combination, but with the option 
> > implemented, we should fit it into the case further above, `elseif((UNIX OR 
> > MINGW) AND LLVM_USE_LINKER STREQUAL "lld")`
> Yeah I bet that variable is set because I pass `LLVM_USE_LINKER=lld` but I 
> haven't digged to deeply. I can rework the if statement here when we have the 
> lld option in there.
> Yeah I bet that variable is set because I pass LLVM_USE_LINKER=lld but I 
> haven't digged to deeply. 

It does use `lld-link` when you use `LLVM_USE_LINKER=lld`.

The problem lies in this line:
```
append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
```
For MinGW that should read:
```
append("-Wl,/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
```
That's because you are passing this flag to GCC/Clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80425



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


[PATCH] D80415: [AIX] Add '-bcdtors:all:0:s' to linker to gather static init functions

2020-05-22 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/test/Driver/aix-ld.cpp:1
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. 'bcdtors' and Arguemnt order.
+// // RUN: %clang++ -no-canonical-prefixes %s -### -o %t.o 2>&1 \

ZarkoCA wrote:
> s/Arguemnt/Argument/
Lowercase "argument".



Comment at: clang/test/Driver/aix-ld.cpp:2
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. 'bcdtors' and Arguemnt order.
+// // RUN: %clang++ -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// // RUN: -Wl,-bnocdtors \

Let's not use a `.o` suffix for the link step output. It seems using no `-o` is 
fine for tests with `-###`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80415



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


[PATCH] D76791: [Matrix] Implement matrix index expressions ([][]).

2020-05-22 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked an inline comment as done.
fhahn added inline comments.



Comment at: clang/lib/AST/Expr.cpp:3859
+
+  auto *SubscriptE = dyn_cast(this);
+  return SubscriptE

rjmccall wrote:
> You need to `IgnoreParens()` here.
This code is now gone.



Comment at: clang/lib/AST/ExprConstant.cpp:7768
+  if (E->getBase()->getMatrixFromIndexExpr(Info.getLangOpts().MatrixTypes))
+return false;
+

rjmccall wrote:
> This can also occur in the other evaluators due to indexing into an r-value.
This code is not required any longer.



Comment at: clang/lib/Sema/SemaExpr.cpp:5326
+VK = VK_LValue;
+OK = OK_VectorComponent;
   } else if (RHSTy->isArrayType()) {

rjmccall wrote:
> It should have the value kind of its base.  `get_matrix_rvalue()[0][0]` is 
> still an r-value, so you shouldn't allow it to be assigned to.  Needs tests.
> 
> I'm fine with re-using `OK_VectorComponent` here, but you should (1) rename 
> it to `OK_VectorOrMatrixComponent` and (2) take the opportunity to audit the 
> places that use it to make sure they do something sensible.  I expect you'll 
> need to at least update some diagnostics about e.g. disallowing taking the 
> address of the expression.
> 
> I think you should build a new expression node instead of reusing 
> `ArraySubscriptExpr`, since basically none of the code that looks for an 
> `ArraySubscriptExpr` will do the right thing for your operation.  That will 
> also allow you to avoid the "is this actually enabled" check, since you'll 
> only see this node when your feature is enabled.  If you're feeling generous, 
> you could move vector subscripting to this new node as well and leave 
> `ArraySubscriptExpr` exclusively for the standard (or dependent) cases.
> It should have the value kind of its base.  get_matrix_rvalue()[0][0] is 
> still an r-value, so you shouldn't allow it to be assigned to. Needs tests.

added tests to Sema/matrix-type-operators.s and 
SemaCXX/matrix-type-operators.cpp.

> I'm fine with re-using OK_VectorComponent here, but you should (1) rename it 
> to OK_VectorOrMatrixComponent and (2) take the opportunity to audit the 
> places that use it to make sure they do something sensible. I expect you'll 
> need to at least update some diagnostics about e.g. disallowing taking the 
> address of the expression.

I've introduced a new OK_MatrixElement, because I don't think there is enough 
information to distinguish between vectors/matrixes where it is used. Also 
added a reinterpret_cast test.

> I think you should build a new expression node instead of reusing 
> ArraySubscriptExpr, since basically none of the code that looks for an 
> ArraySubscriptExpr will do the right thing for your operation. That will also 
> allow you to avoid the "is this actually enabled" check, since you'll only 
> see this node when your feature is enabled. If you're feeling generous, you 
> could move vector subscripting to this new node as well and leave 
> ArraySubscriptExpr exclusively for the standard (or dependent) cases.

I've added a new MatrixSubscriptExpr. That helps to simplify the code in a 
couple of places. ActOnArraySubscriptExpr calls ActOnMatrixSubscriptExpr if we 
can identify the base as matrix type or MatrixSubscriptExpr. I initially tried 
to move the ActOnMatrixSubscriptExpr call to the parse step, but that does not 
work in the presence of dependent base types I think. Until we instantiate the 
dependent types, there's no way to distinguish between 
ArraySubscriptExpr/MatrixSubscriptExpr I think and it is best to treat them as 
unanalyzed ArraySubscriptExpr until then.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76791



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


[PATCH] D80412: Summary: [Lexer] Fix invalid suffix diagnostic for fixed-point literals

2020-05-22 Thread Arthi via Phabricator via cfe-commits
nagart updated this revision to Diff 265748.
nagart added a comment.

fixing lint issues


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80412

Files:
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/test/Frontend/fixed_point_errors.c


Index: clang/test/Frontend/fixed_point_errors.c
===
--- clang/test/Frontend/fixed_point_errors.c
+++ clang/test/Frontend/fixed_point_errors.c
@@ -137,15 +137,15 @@
 _Sat longaccum_t td_sat_long_accum; // expected-error{{'_Sat' 
specifier is only valid on '_Fract' or '_Accum', not 'type-name'}}
 
 /* Bad suffixes  */
-_Accum fk = 1.0fk;// expected-error{{invalid suffix 'fk' on integer 
constant}}
-_Accum kk = 1.0kk;// expected-error{{invalid suffix 'kk' on integer 
constant}}
-_Accum rk = 1.0rk;// expected-error{{invalid suffix 'rk' on integer 
constant}}
-_Accum rk = 1.0rr;// expected-error{{invalid suffix 'rr' on integer 
constant}}
-_Accum qk = 1.0qr;// expected-error{{invalid suffix 'qr' on integer 
constant}}
+_Accum fk = 1.0fk; // expected-error{{invalid suffix 'fk' on fixed-point 
constant}}
+_Accum kk = 1.0kk; // expected-error{{invalid suffix 'kk' on fixed-point 
constant}}
+_Accum rk = 1.0rk; // expected-error{{invalid suffix 'rk' on fixed-point 
constant}}
+_Accum rk = 1.0rr; // expected-error{{invalid suffix 'rr' on fixed-point 
constant}}
+_Accum qk = 1.0qr; // expected-error{{invalid suffix 'qr' on fixed-point 
constant}}
 
 /* Using wrong exponent notation */
-_Accum dec_with_hex_exp1 = 0.1p10k;// expected-error{{invalid suffix 
'p10k' on integer constant}}
-_Accum dec_with_hex_exp2 = 0.1P10k;// expected-error{{invalid suffix 
'P10k' on integer constant}}
+_Accum dec_with_hex_exp1 = 0.1p10k;// expected-error{{invalid suffix 
'p10k' on fixed-point constant}}
+_Accum dec_with_hex_exp2 = 0.1P10k;// expected-error{{invalid suffix 
'P10k' on fixed-point constant}}
 _Accum hex_with_dex_exp1 = 0x0.1e10k;  // expected-error{{hexadecimal floating 
constant requires an exponent}}
 _Accum hex_with_dex_exp2 = 0x0.1E10k;  // expected-error{{hexadecimal floating 
constant requires an exponent}}
 
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -583,6 +583,7 @@
 
   // Parse the suffix.  At this point we can classify whether we have an FP or
   // integer constant.
+  bool isFixedPointConstant = isFixedPointLiteral();
   bool isFPConstant = isFloatingLiteral();
 
   // Loop over all of the characters of the suffix.  If we see something bad,
@@ -737,7 +738,8 @@
   // Report an error if there are any.
   PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
   diag::err_invalid_suffix_constant)
-  << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant;
+  << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)
+  << (isFixedPointConstant ? 2 : isFPConstant);
   hadError = true;
 }
   }
Index: clang/include/clang/Lex/LiteralSupport.h
===
--- clang/include/clang/Lex/LiteralSupport.h
+++ clang/include/clang/Lex/LiteralSupport.h
@@ -71,7 +71,9 @@
   bool isFract : 1; // 1.0hr/r/lr/uhr/ur/ulr
   bool isAccum : 1; // 1.0hk/k/lk/uhk/uk/ulk
 
-  bool isFixedPointLiteral() const { return saw_fixed_point_suffix; }
+  bool isFixedPointLiteral() const {
+return (saw_period || saw_exponent) && saw_fixed_point_suffix;
+  }
 
   bool isIntegerLiteral() const {
 return !saw_period && !saw_exponent && !isFixedPointLiteral();
Index: clang/include/clang/Basic/DiagnosticLexKinds.td
===
--- clang/include/clang/Basic/DiagnosticLexKinds.td
+++ clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -175,7 +175,7 @@
 def err_invalid_digit : Error<
   "invalid digit '%0' in %select{decimal|octal|binary}1 constant">;
 def err_invalid_suffix_constant : Error<
-  "invalid suffix '%0' on %select{integer|floating}1 constant">;
+  "invalid suffix '%0' on %select{integer|floating|fixed-point}1 constant">;
 def warn_cxx11_compat_digit_separator : Warning<
   "digit separators are incompatible with C++ standards before C++14">,
   InGroup, DefaultIgnore;


Index: clang/test/Frontend/fixed_point_errors.c
===
--- clang/test/Frontend/fixed_point_errors.c
+++ clang/test/Frontend/fixed_point_errors.c
@@ -137,15 +137,15 @@
 _Sat longaccum_t td_sat_long_accum; // expected-error{{'_Sat' specifier is only valid on '_Fract' or '_Accum', not 'type-name'}}
 
 /* Bad suffixes  */
-_Accum fk = 1.0fk;// expected-error{{

[PATCH] D76791: [Matrix] Implement matrix index expressions ([][]).

2020-05-22 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 265750.
fhahn added a comment.

Add clarifying comment to ActOnMatrixSubscriptExpr calls in 
ActOnArraySubscriptExpr.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76791

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/BuiltinTypes.def
  clang/include/clang/AST/ComputeDependence.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/Specifiers.h
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ComputeDependence.cpp
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprClassification.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/NSAPI.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/CodeGen/matrix-type-operators.c
  clang/test/CodeGenCXX/matrix-type-operators.cpp
  clang/test/Sema/matrix-type-operators.c
  clang/test/SemaCXX/matrix-type-operators.cpp
  clang/tools/libclang/CXCursor.cpp
  llvm/include/llvm/IR/MatrixBuilder.h

Index: llvm/include/llvm/IR/MatrixBuilder.h
===
--- llvm/include/llvm/IR/MatrixBuilder.h
+++ llvm/include/llvm/IR/MatrixBuilder.h
@@ -155,15 +155,19 @@
 return B.CreateMul(LHS, ScalarVector);
   }
 
-  /// Extracts the element at (\p Row, \p Column) from \p Matrix.
-  Value *CreateExtractMatrix(Value *Matrix, Value *Row, Value *Column,
- unsigned NumRows, Twine const &Name = "") {
-
+  /// Extracts the element at (\p RowIdx, \p ColumnIdx) from \p Matrix.
+  Value *CreateExtractElement(Value *Matrix, Value *RowIdx, Value *ColumnIdx,
+  unsigned NumRows, Twine const &Name = "") {
+
+unsigned MaxWidth = std::max(RowIdx->getType()->getScalarSizeInBits(),
+ ColumnIdx->getType()->getScalarSizeInBits());
+Type *IntTy = IntegerType::get(RowIdx->getType()->getContext(), MaxWidth);
+RowIdx = B.CreateZExt(RowIdx, IntTy);
+ColumnIdx = B.CreateZExt(ColumnIdx, IntTy);
+Value *NumRowsV = B.getIntN(MaxWidth, NumRows);
 return B.CreateExtractElement(
-Matrix,
-B.CreateAdd(
-B.CreateMul(Column, ConstantInt::get(Column->getType(), NumRows)),
-Row));
+Matrix, B.CreateAdd(B.CreateMul(ColumnIdx, NumRowsV), RowIdx),
+"matext");
   }
 };
 
Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -419,6 +419,11 @@
 K = CXCursor_ArraySubscriptExpr;
 break;
 
+  case Stmt::MatrixSubscriptExprClass:
+// TODO: add support for MatrixSubscriptExpr.
+K = CXCursor_UnexposedExpr;
+break;
+
   case Stmt::OMPArraySectionExprClass:
 K = CXCursor_OMPArraySectionExpr;
 break;
Index: clang/test/SemaCXX/matrix-type-operators.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/matrix-type-operators.cpp
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 %s -fenable-matrix -pedantic -std=c++11 -verify -triple=x86_64-apple-darwin9
+
+typedef float sx5x10_t __attribute__((matrix_type(5, 10)));
+
+sx5x10_t get_matrix();
+
+void insert(sx5x10_t a, float f) {
+  // Non integer indexes.
+  a[3][f] = 0;
+  // expected-error@-1 {{matrix column index is not an integer}}
+  a[f][9] = 0;
+  // expected-error@-1 {{matrix row index is not an integer}}
+  a[f][f] = 0;
+  // expected-error@-1 {{matrix row index is not an integer}}
+  a[0][f] = 0;
+  // expected-error@-1 {{matrix column index is not an integer}}
+
+  // Invalid element type.
+  a[3][4] = &f;
+  // expected-error@-1 {{assigning to 'float' from incompatible type 'float *'; remove &}}
+
+  // Indexes outside allowed dimensions.
+  a[-1][3] = 10.0;
+  // expected-error@-1 {{matrix row index is outside the allowed range [0, 5)}}
+  a[3][-1] = 10.0;
+  // expected-error@-1 {{matrix column index is outside the allowed range [0, 10)}}
+  a[3][-1u] = 10.0;
+  // expected-error@-1 {{matrix column index

[PATCH] D80443: [analyzer] SATestBuild.py: Fix hang when one of the tasks fails

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added a reviewer: NoQ.
Herald added subscribers: cfe-commits, ASDenysPetrov, Charusso, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: clang.

Tasks can crash with many different exceptions including SystemExit.
Bare except still causes a warning, so let's use BaseException instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80443

Files:
  clang/utils/analyzer/SATestBuild.py


Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -633,7 +633,7 @@
 
 self.tasks_queue.task_done()
 
-except CalledProcessError:
+except BaseException:
 self.failure_flag.set()
 raise
 


Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -633,7 +633,7 @@
 
 self.tasks_queue.task_done()
 
-except CalledProcessError:
+except BaseException:
 self.failure_flag.set()
 raise
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80222: Replace Clang's createRuntimeFunction with the definitions in OMPKinds.def

2020-05-22 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim added inline comments.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def:244
 
-// TODO: Replace this with the real size_t type
-#define __OMP_SIZE_TYPE(NAME) OMP_TYPE(NAME, Type::getInt64Ty(Ctx))
+#define __OMP_SIZE_TYPE(NAME) OMP_TYPE(NAME, 
M.getDataLayout().getIntPtrType(Ctx))
 __OMP_SIZE_TYPE(SizeTy)

jhuber6 wrote:
> fghanim wrote:
> > jdoerfert wrote:
> > > jhuber6 wrote:
> > > > I'm just directly getting the SizeTy from the Module, I'm not sure if 
> > > > this is a permanent solution.
> > > I actually think this is fine. Less burden on the frontends also. 
> > > @fghanim looks good?
> > Agreed. But to avoid conflict with patch D79675, let this change go in a 
> > separate patch after that. This way, we can also do some clean ups related 
> > to this, and add `Int8PtrPtr`, `Int8PtrPtrPtr`, and any other typing 
> > issues, without delaying patch D79675 any further - I am done with that 
> > patch, and made my final changes a couple of days ago.
> > 
> > Nit: Also, I saw below that some formatting was done. Wouldn't it be better 
> > if formatting/comments related to changes in D79739, are handled as part of 
> > that patch?
> Doesn't this patch already support Int8PtrPtrPtr? It's the same thing as a 
> VoidPtrPtrPtr which I have defined above here.
You are correct. But think of it in the same way we have voidptr and int8ptr, 
even though they are the same.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80222



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


[PATCH] D76077: [ARM] Add __bf16 as new Bfloat16 C Type

2020-05-22 Thread Ties Stuij via Phabricator via cfe-commits
stuij updated this revision to Diff 265753.
stuij marked an inline comment as done.
stuij added a comment.

no explicit float-abi cmdline arg should default to softfp


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76077

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang-c/Index.h
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/BuiltinTypes.def
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/Specifiers.h
  clang/include/clang/Basic/TargetBuiltins.h
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Sema/DeclSpec.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/AST/NSAPI.cpp
  clang/lib/AST/PrintfFormatString.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/ARM.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenTypeCache.h
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/Format/FormatToken.cpp
  clang/lib/Index/USRGeneration.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseTentative.cpp
  clang/lib/Sema/DeclSpec.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplateVariadic.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/CodeGen/arm-bf16-params-returns.c
  clang/test/CodeGen/arm-mangle-16bit-float.cpp
  clang/test/Sema/arm-bf16-forbidden-ops.c
  clang/test/Sema/arm-bf16-forbidden-ops.cpp
  clang/test/Sema/arm-bfloat.cpp
  clang/tools/libclang/CXType.cpp

Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -608,6 +608,7 @@
 TKIND(Elaborated);
 TKIND(Pipe);
 TKIND(Attributed);
+TKIND(BFloat16);
 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) TKIND(Id);
 #include "clang/Basic/OpenCLImageTypes.def"
 #undef IMAGE_TYPE
Index: clang/test/Sema/arm-bfloat.cpp
===
--- /dev/null
+++ clang/test/Sema/arm-bfloat.cpp
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 \
+// RUN: -triple aarch64-arm-none-eabi -target-cpu cortex-a75 \
+// RUN: -target-feature +bf16 -target-feature +neon %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 \
+// RUN: -triple arm-arm-none-eabi -target-cpu cortex-a53 \
+// RUN: -target-feature +bf16 -target-feature +neon %s
+
+void test(bool b) {
+  __bf16 bf16;
+
+  bf16 + bf16; // expected-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
+  bf16 - bf16; // expected-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
+  bf16 * bf16; // expected-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
+  bf16 / bf16; // expected-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
+
+  __fp16 fp16;
+
+  bf16 + fp16; // expected-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
+  fp16 + bf16; // expected-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
+  bf16 - fp16; // expected-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
+  fp16 - bf16; // expected-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
+  bf16 * fp16; // expected-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
+  fp16 * bf16; // expected-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
+  bf16 / fp16; // expected-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
+  fp16 / bf16; // expected-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
+  bf16 = fp16; // expected-error {{assigning to '__bf16' from incompatible type '__fp16'}}
+  fp16 = bf16; // expected-error {{assigning to '__fp16' from incompatible type '__bf16'}}
+  bf16 + (b ? fp16 : bf16); // expected-error {{incompatible operand types ('__fp16' and '__bf16')}}
+}
Index: clang/test/Sema/arm-bf16-forbidden-ops.cpp
===
--- /dev/null
+++ clang/test/Sema/arm-bf16-forbidden-ops.cpp
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -triple aarch64 

[clang] a5b2503 - [analyzer] SATestBuild.py: Fix hang when one of the tasks fails

2020-05-22 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2020-05-22T19:15:00+03:00
New Revision: a5b2503a8ab4fb21345fa9e2316530cdfaec1a60

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

LOG: [analyzer] SATestBuild.py: Fix hang when one of the tasks fails

Summary:
Tasks can crash with many different exceptions including SystemExit.
Bare except still causes a warning, so let's use BaseException instead.

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

Added: 


Modified: 
clang/utils/analyzer/SATestBuild.py

Removed: 




diff  --git a/clang/utils/analyzer/SATestBuild.py 
b/clang/utils/analyzer/SATestBuild.py
index 39fa7ece4362..e2fe6a95138b 100755
--- a/clang/utils/analyzer/SATestBuild.py
+++ b/clang/utils/analyzer/SATestBuild.py
@@ -633,7 +633,7 @@ def run(self):
 
 self.tasks_queue.task_done()
 
-except CalledProcessError:
+except BaseException:
 self.failure_flag.set()
 raise
 



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


[PATCH] D80443: [analyzer] SATestBuild.py: Fix hang when one of the tasks fails

2020-05-22 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Not unreasonable!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80443



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


[PATCH] D80443: [analyzer] SATestBuild.py: Fix hang when one of the tasks fails

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5b2503a8ab4: [analyzer] SATestBuild.py: Fix hang when one 
of the tasks fails (authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80443

Files:
  clang/utils/analyzer/SATestBuild.py


Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -633,7 +633,7 @@
 
 self.tasks_queue.task_done()
 
-except CalledProcessError:
+except BaseException:
 self.failure_flag.set()
 raise
 


Index: clang/utils/analyzer/SATestBuild.py
===
--- clang/utils/analyzer/SATestBuild.py
+++ clang/utils/analyzer/SATestBuild.py
@@ -633,7 +633,7 @@
 
 self.tasks_queue.task_done()
 
-except CalledProcessError:
+except BaseException:
 self.failure_flag.set()
 raise
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] e4bb3e2 - [clang-tidy] Expand the list of functions in bugprone-unused-return-value

2020-05-22 Thread Joe Ranieri via cfe-commits

Author: Joe Ranieri
Date: 2020-05-22T12:57:58-04:00
New Revision: e4bb3e25e4400151133fd3737f4842f2aeda1c1b

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

LOG: [clang-tidy] Expand the list of functions in bugprone-unused-return-value

This change adds common C, C++, and POSIX functions to the clang-tidy unused 
return value checker.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index c3efb08d4213..d49fd63f005d 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -43,7 +43,90 @@ 
UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
"::std::unique;"
"::std::unique_ptr::release;"
"::std::basic_string::empty;"
-   "::std::vector::empty")) {}
+   "::std::vector::empty;"
+   "::std::back_inserter;"
+   "::std::distance;"
+   "::std::find;"
+   "::std::find_if;"
+   "::std::inserter;"
+   "::std::lower_bound;"
+   "::std::make_pair;"
+   "::std::map::count;"
+   "::std::map::find;"
+   "::std::map::lower_bound;"
+   "::std::multimap::equal_range;"
+   "::std::multimap::upper_bound;"
+   "::std::set::count;"
+   "::std::set::find;"
+   "::std::setfill;"
+   "::std::setprecision;"
+   "::std::setw;"
+   "::std::upper_bound;"
+   "::std::vector::at;"
+   // C standard library
+   "::bsearch;"
+   "::ferror;"
+   "::feof;"
+   "::isalnum;"
+   "::isalpha;"
+   "::isblank;"
+   "::iscntrl;"
+   "::isdigit;"
+   "::isgraph;"
+   "::islower;"
+   "::isprint;"
+   "::ispunct;"
+   "::isspace;"
+   "::isupper;"
+   "::iswalnum;"
+   "::iswprint;"
+   "::iswspace;"
+   "::isxdigit;"
+   "::memchr;"
+   "::memcmp;"
+   "::strcmp;"
+   "::strcoll;"
+   "::strncmp;"
+   "::strpbrk;"
+   "::strrchr;"
+   "::strspn;"
+   "::strstr;"
+   "::wcscmp;"
+   // POSIX
+   "::access;"
+   "::bind;"
+   "::connect;"
+   "::
diff time;"
+   "::dlsym;"
+   "::fnmatch;"
+   "::getaddrinfo;"
+   "::getopt;"
+   "::htonl;"
+   "::htons;"
+   "::iconv_open;"
+   "::inet_addr;"
+   "::isascii;"
+   "::isatty;"
+   "::mmap;"
+   "::newlocale;"
+   "::openat;"
+   "::pathconf;"
+   "::pthread_equal;"
+   "::pthread

[PATCH] D80369: [DebugInfo][CallSites] Remove decl subprograms from 'retainedTypes:'

2020-05-22 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D80369#2050962 , @djtodoro wrote:

> In D80369#2050022 , @dblaikie wrote:
>
> > In D80369#2048932 , @djtodoro 
> > wrote:
> >
> > > Still have test failing:
> > >
> > >   Clang :: Modules/DebugInfoTransitiveImport.m
> > >   Clang :: Modules/ModuleDebugInfo.cpp
> > >   Clang :: Modules/ModuleDebugInfo.m
> > >   
> > >
> > > I haven't looked into the failures, but I guess something Objective-C++ 
> > > related should be handled with some additional work here.
> >
> >
> > These look like over-constrained/accidental tests. At least the 
> > ModuleDEbugInfo.m test - the type being tested for won't be emitted, 
> > because the type itself isn't in the retained types list nor is it 
> > reachable from any other metadata that is going to be emitted.
> >
> > I think it'd probably be good to clean these tests up - and leave it to 
> > @aprantl to look into if this has exposed other bugs - but the bugs are 
> > already there, and this IR/debug info metadata isn't working around the 
> > bugs, since the IR is going unused anyway.
>
>
> Looks like ObjC expects the declarations within retained types  (based on 
> some tests failures), so I left it as is (I think @aprantl can help us with 
> that).
>  Therefore, this patch will remove the declarations only in the case of call 
> site debug info for now.


Yeah, that's what I was trying to say - I think the tests expect that, but I 
don't see any code path that uses that debug info metadata - I think the test 
is overconstrained/accidentally testing for this behavior.

I think the right thing to do is to change these tests to test the new behavior 
(the behavior of the first version of this patch) - and if some use 
arises/someone can demonstrate a codepath that's using this data, it can be 
added back in.

@aprantl can you check here? I've attached two IR files for the 
ModuleDebugInfo.m test, before/after ('x' is before), stripped of the metadata 
numbers to make diffing easier - but I think you can still follow what's 
connected to what with reasonable guesswork. The point is these two function 
declarations end up in the retainedTypes list, and since the function 
declarations are emitted, so are the types used in their parameters, etc - but 
those types aren't reachable from anywhere else in the debug info metadata, so 
they won't be emitted into the final object file so far as I can see (because 
nothing looks at the function declarations in retainedTypes - only types).

F11980002: x.ll 

F11980001: y.ll 


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

https://reviews.llvm.org/D80369



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


[PATCH] D79710: [clang][BFloat] add create/set/get/dup intrinsics

2020-05-22 Thread Ties Stuij via Phabricator via cfe-commits
stuij updated this revision to Diff 265764.
stuij added a comment.

moving 'CartesianProductWith' to more apt patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79710

Files:
  clang/include/clang/Basic/arm_neon.td
  clang/include/clang/Basic/arm_neon_incl.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/aarch64-bf16-getset-intrinsics.c

Index: clang/test/CodeGen/aarch64-bf16-getset-intrinsics.c
===
--- /dev/null
+++ clang/test/CodeGen/aarch64-bf16-getset-intrinsics.c
@@ -0,0 +1,120 @@
+// RUN: %clang_cc1 -triple aarch64-arm-none-eabi -target-feature +neon -target-feature +bf16 \
+// RUN:  -O2 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK64
+// RUN: %clang_cc1 -triple armv8.6a-arm-none-eabi -target-feature +neon -target-feature +bf16 -mfloat-abi hard \
+// RUN:  -O2 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK32
+
+#include 
+
+bfloat16x4_t test_vcreate_bf16(uint64_t a) {
+  return vcreate_bf16(a);
+}
+// CHECK-LABEL: test_vcreate_bf16
+// CHECK64: %0 = bitcast i64 %a to <4 x bfloat>
+// CHECK32: %0 = bitcast i64 %a to <4 x bfloat>
+
+bfloat16x4_t test_vdup_n_bf16(bfloat16_t v) {
+  return vdup_n_bf16(v);
+}
+// CHECK-LABEL: test_vdup_n_bf16
+// CHECK64: %vecinit.i = insertelement <4 x bfloat> undef, bfloat %v, i32 0
+// CHECK32: %vecinit.i = insertelement <4 x bfloat> undef, bfloat %v, i32 0
+// CHECK: %vecinit{{.*}} = shufflevector <4 x bfloat> %vecinit.i, <4 x bfloat> undef, <4 x i32> zeroinitializer
+
+bfloat16x8_t test_vdupq_n_bf16(bfloat16_t v) {
+  return vdupq_n_bf16(v);
+}
+// CHECK-LABEL: test_vdupq_n_bf16
+// CHECK64: %vecinit.i = insertelement <8 x bfloat> undef, bfloat %v, i32 0
+// CHECK32: %vecinit.i = insertelement <8 x bfloat> undef, bfloat %v, i32 0
+// CHECK:   %vecinit{{.*}} = shufflevector <8 x bfloat> %vecinit.i, <8 x bfloat> undef, <8 x i32> zeroinitializer
+
+bfloat16x4_t test_vdup_lane_bf16(bfloat16x4_t v) {
+  return vdup_lane_bf16(v, 1);
+}
+// CHECK-LABEL: test_vdup_lane_bf16
+// CHECK64: %lane = shufflevector <4 x bfloat> %v, <4 x bfloat> undef, <4 x i32> 
+// CHECK32: %lane = shufflevector <4 x bfloat> %v, <4 x bfloat> undef, <4 x i32> 
+
+bfloat16x8_t test_vdupq_lane_bf16(bfloat16x4_t v) {
+  return vdupq_lane_bf16(v, 1);
+}
+// CHECK-LABEL: test_vdupq_lane_bf16
+// CHECK64: %lane = shufflevector <4 x bfloat> %v, <4 x bfloat> undef, <8 x i32> 
+// CHECK32: %lane = shufflevector <4 x bfloat> %v, <4 x bfloat> undef, <8 x i32> 
+
+bfloat16x4_t test_vdup_laneq_bf16(bfloat16x8_t v) {
+  return vdup_laneq_bf16(v, 7);
+}
+// CHECK-LABEL: test_vdup_laneq_bf16
+// CHECK64: %lane = shufflevector <8 x bfloat> %v, <8 x bfloat> undef, <4 x i32> 
+// CHECK32: %lane = shufflevector <8 x bfloat> %v, <8 x bfloat> undef, <4 x i32> 
+
+bfloat16x8_t test_vdupq_laneq_bf16(bfloat16x8_t v) {
+  return vdupq_laneq_bf16(v, 7);
+}
+// CHECK-LABEL: test_vdupq_laneq_bf16
+// CHECK64: %lane = shufflevector <8 x bfloat> %v, <8 x bfloat> undef, <8 x i32> 
+// CHECK32: %lane = shufflevector <8 x bfloat> %v, <8 x bfloat> undef, <8 x i32> 
+
+bfloat16x8_t test_vcombine_bf16(bfloat16x4_t low, bfloat16x4_t high) {
+  return vcombine_bf16(low, high);
+}
+// CHECK-LABEL: test_vcombine_bf16
+// CHECK64: %shuffle.i = shufflevector <4 x bfloat> %low, <4 x bfloat> %high, <8 x i32> 
+// CHECK32: %shuffle.i = shufflevector <4 x bfloat> %low, <4 x bfloat> %high, <8 x i32> 
+
+bfloat16x4_t test_vget_high_bf16(bfloat16x8_t a) {
+  return vget_high_bf16(a);
+}
+// CHECK-LABEL: test_vget_high_bf16
+// CHECK64: %shuffle.i = shufflevector <8 x bfloat> %a, <8 x bfloat> undef, <4 x i32> 
+// CHECK32: %shuffle.i = shufflevector <8 x bfloat> %a, <8 x bfloat> undef, <4 x i32> 
+
+bfloat16x4_t test_vget_low_bf16(bfloat16x8_t a) {
+  return vget_low_bf16(a);
+}
+// CHECK-LABEL: test_vget_low_bf16
+// CHECK64: %shuffle.i = shufflevector <8 x bfloat> %a, <8 x bfloat> undef, <4 x i32> 
+// CHECK32: %shuffle.i = shufflevector <8 x bfloat> %a, <8 x bfloat> undef, <4 x i32> 
+
+bfloat16_t test_vget_lane_bf16(bfloat16x4_t v) {
+  return vget_lane_bf16(v, 1);
+}
+// CHECK-LABEL: test_vget_lane_bf16
+// CHECK64: %vget_lane = extractelement <4 x bfloat> %v, i32 1
+// CHECK32: %vget_lane = extractelement <4 x bfloat> %v, i32 1
+
+bfloat16_t test_vgetq_lane_bf16(bfloat16x8_t v) {
+  return vgetq_lane_bf16(v, 7);
+}
+// CHECK-LABEL: test_vgetq_lane_bf16
+// CHECK64: %vgetq_lane = extractelement <8 x bfloat> %v, i32 7
+// CHECK32: %vget_lane = extractelement <8 x bfloat> %v, i32 7
+
+bfloat16x4_t test_vset_lane_bf16(bfloat16_t a, bfloat16x4_t v) {
+  return vset_lane_bf16(a, v, 1);
+}
+// CHECK-LABEL: test_vset_lane_bf16
+// CHECK64: %vset_lane = insertelement <4 x bfloat> %v, bfloat %a, i32 1
+// CHECK32: %vset_lane = insertelement <4 x bfloat> %v, bfloat %a, i32 1
+
+bfloat16x8_t test_vsetq_lane_bf16(bfloat16_t a, bfloat16x8_t v) {
+  return vsetq_lane

[PATCH] D76510: [analyzer] Change the default output type to PD_TEXT_MINIMAL in the frontend, error if an output loc is missing for PathDiagConsumers that need it

2020-05-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

Hi @Szelethus , it looks like I am a bearer of bad news again :(
This patch seems to crash `scan-build` on pretty much every project that I 
tested.

One way to reproduce:

  git clone https://github.com/postgres/postgres.git
  cd postgres/
  scan-build -plist-html -o ./out ./configure 

Output:

  scan-build: Using 
'/Users/vsavchenko/source/llvm-project/build/Release/bin/clang-11' for static 
analysis
  checking build system type... x86_64-apple-darwin19.4.0
  checking host system type... x86_64-apple-darwin19.4.0
  checking which template to use... darwin
  checking whether NLS is wanted... no
  checking for default port number... 5432
  checking for block size... 8kB
  checking for segment size... 1GB
  checking for WAL block size... 8kB
  checking whether the C compiler works... no
  configure: error: in `/Users/vsavchenko/source/postgres':
  configure: error: C compiler cannot create executables
  See `config.log' for more details
  scan-build: Analysis run complete.
  scan-build: Analysis results (plist files) deposited in 
'/Users/vsavchenko/source/postgres/out/2020-05-22-194935-27687-1'
  scan-build: Removing directory 
'/Users/vsavchenko/source/postgres/out/2020-05-22-194935-27687-1' because it 
contains no reports.
  scan-build: No bugs found.

config.log will contain something similar to this:

  configure:3987: checking whether the C compiler works
  configure:4009: 
/Users/vsavchenko/source/llvm-project/build/Release/bin/../libexec/ccc-analyzer 
   conftest.c  >&5
  error: analyzer output type 'html' requires an output directory to be 
specified with -o 
  1 error generated.
  Use of uninitialized value $HtmlDir in concatenation (.) or string at 
/Users/vsavchenko/source/llvm-project/build/Release/bin/../libexec/ccc-analyzer 
line 149, <$fh> line 2.
  mkdir /failures: Read-only file system at 
/Users/vsavchenko/source/llvm-project/build/Release/bin/../libexec/ccc-analyzer 
line 150.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76510



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


[PATCH] D76083: [clang-tidy] Expand the list of functions in bugprone-unused-return-value

2020-05-22 Thread Joe Ranieri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe4bb3e25e440: [clang-tidy] Expand the list of functions in 
bugprone-unused-return-value (authored by jranieri-grammatech).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76083

Files:
  clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp


Index: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -43,7 +43,90 @@
"::std::unique;"
"::std::unique_ptr::release;"
"::std::basic_string::empty;"
-   "::std::vector::empty")) {}
+   "::std::vector::empty;"
+   "::std::back_inserter;"
+   "::std::distance;"
+   "::std::find;"
+   "::std::find_if;"
+   "::std::inserter;"
+   "::std::lower_bound;"
+   "::std::make_pair;"
+   "::std::map::count;"
+   "::std::map::find;"
+   "::std::map::lower_bound;"
+   "::std::multimap::equal_range;"
+   "::std::multimap::upper_bound;"
+   "::std::set::count;"
+   "::std::set::find;"
+   "::std::setfill;"
+   "::std::setprecision;"
+   "::std::setw;"
+   "::std::upper_bound;"
+   "::std::vector::at;"
+   // C standard library
+   "::bsearch;"
+   "::ferror;"
+   "::feof;"
+   "::isalnum;"
+   "::isalpha;"
+   "::isblank;"
+   "::iscntrl;"
+   "::isdigit;"
+   "::isgraph;"
+   "::islower;"
+   "::isprint;"
+   "::ispunct;"
+   "::isspace;"
+   "::isupper;"
+   "::iswalnum;"
+   "::iswprint;"
+   "::iswspace;"
+   "::isxdigit;"
+   "::memchr;"
+   "::memcmp;"
+   "::strcmp;"
+   "::strcoll;"
+   "::strncmp;"
+   "::strpbrk;"
+   "::strrchr;"
+   "::strspn;"
+   "::strstr;"
+   "::wcscmp;"
+   // POSIX
+   "::access;"
+   "::bind;"
+   "::connect;"
+   "::difftime;"
+   "::dlsym;"
+   "::fnmatch;"
+   "::getaddrinfo;"
+   "::getopt;"
+   "::htonl;"
+   "::htons;"
+   "::iconv_open;"
+   "::inet_addr;"
+   "::isascii;"
+   "::isatty;"
+   "::mmap;"
+   "::newlocale;"
+   "::openat;"
+   "::pathconf;"
+   "::pthread_equal;"
+   "::pthread_getspecific;"
+   "::pthread_mutex_trylock;"
+   "::readdir;"
+   "::readlink;"
+   "::recvmsg;"
+   "::regexec;"
+   "::scandir;"
+   "::semget;"
+   "::setjmp;"

[PATCH] D80415: [AIX] Add '-bcdtors:all:0:s' to linker to gather static init functions

2020-05-22 Thread Steven Wan via Phabricator via cfe-commits
stevewan updated this revision to Diff 265765.
stevewan added a comment.

Address comments and fix windows compatibility issues with the test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80415

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-ld.cpp


Index: clang/test/Driver/aix-ld.cpp
===
--- /dev/null
+++ clang/test/Driver/aix-ld.cpp
@@ -0,0 +1,19 @@
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. 'bcdtors' and argument order.
+// RUN: %clangxx -no-canonical-prefixes %s 2>&1 -### \
+// RUN:  -Wl,-bnocdtors \
+// RUN:  -target powerpc-ibm-aix7.1.0.0 \
+// RUN:  --sysroot %S/Inputs/aix_ppc_tree \
+// RUN: | FileCheck --check-prefix=CHECK-LD32-ARG-ORDER %s
+
+// CHECK-LD32-ARG-ORDER-NOT: warning:
+// CHECK-LD32-ARG-ORDER: {{.*}}clang{{(.exe)?}}" "-cc1" "-triple" 
"powerpc-ibm-aix7.1.0.0"
+// CHECK-LD32-ARG-ORDER: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-LD32-ARG-ORDER: "{{.*}}ld{{(.exe)?}}"
+// CHECK-LD32-ARG-ORDER-NOT: "-bnso"
+// CHECK-LD32-ARG-ORDER: "-b32"
+// CHECK-LD32-ARG-ORDER: "-bpT:0x1000" "-bpD:0x2000"
+// CHECK-LD32-ARG-ORDER: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
+// CHECK-LD32-ARG-ORDER: "-bcdtors:all:0:s"
+// CHECK-LD32-ARG-ORDER: "-bnocdtors"
+// CHECK-LD32-ARG-ORDER: "-L[[SYSROOT]]/usr/lib"
+// CHECK-LD32-ARG-ORDER: "-lc"
Index: clang/lib/Driver/ToolChains/AIX.cpp
===
--- clang/lib/Driver/ToolChains/AIX.cpp
+++ clang/lib/Driver/ToolChains/AIX.cpp
@@ -81,6 +81,7 @@
const InputInfoList &Inputs, const ArgList 
&Args,
const char *LinkingOutput) const {
   const AIX &ToolChain = static_cast(getToolChain());
+  const Driver &D = ToolChain.getDriver();
   ArgStringList CmdArgs;
 
   const bool IsArch32Bit = ToolChain.getTriple().isArch32Bit();
@@ -129,6 +130,12 @@
 Args.MakeArgString(ToolChain.GetFilePath(getCrt0Basename(;
   }
 
+  // Collect all static constructor and destructor functions in CXX mode. This
+  // has to come before AddLinkerInputs as the implied option needs to precede
+  // any other '-bcdtors' settings or '-bnocdtors' that '-Wl' might forward.
+  if (D.CCCIsCXX())
+CmdArgs.push_back("-bcdtors:all:0:s");
+
   // Specify linker input file(s).
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 


Index: clang/test/Driver/aix-ld.cpp
===
--- /dev/null
+++ clang/test/Driver/aix-ld.cpp
@@ -0,0 +1,19 @@
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. 'bcdtors' and argument order.
+// RUN: %clangxx -no-canonical-prefixes %s 2>&1 -### \
+// RUN:  -Wl,-bnocdtors \
+// RUN:  -target powerpc-ibm-aix7.1.0.0 \
+// RUN:  --sysroot %S/Inputs/aix_ppc_tree \
+// RUN: | FileCheck --check-prefix=CHECK-LD32-ARG-ORDER %s
+
+// CHECK-LD32-ARG-ORDER-NOT: warning:
+// CHECK-LD32-ARG-ORDER: {{.*}}clang{{(.exe)?}}" "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0"
+// CHECK-LD32-ARG-ORDER: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-LD32-ARG-ORDER: "{{.*}}ld{{(.exe)?}}"
+// CHECK-LD32-ARG-ORDER-NOT: "-bnso"
+// CHECK-LD32-ARG-ORDER: "-b32"
+// CHECK-LD32-ARG-ORDER: "-bpT:0x1000" "-bpD:0x2000"
+// CHECK-LD32-ARG-ORDER: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
+// CHECK-LD32-ARG-ORDER: "-bcdtors:all:0:s"
+// CHECK-LD32-ARG-ORDER: "-bnocdtors"
+// CHECK-LD32-ARG-ORDER: "-L[[SYSROOT]]/usr/lib"
+// CHECK-LD32-ARG-ORDER: "-lc"
Index: clang/lib/Driver/ToolChains/AIX.cpp
===
--- clang/lib/Driver/ToolChains/AIX.cpp
+++ clang/lib/Driver/ToolChains/AIX.cpp
@@ -81,6 +81,7 @@
const InputInfoList &Inputs, const ArgList &Args,
const char *LinkingOutput) const {
   const AIX &ToolChain = static_cast(getToolChain());
+  const Driver &D = ToolChain.getDriver();
   ArgStringList CmdArgs;
 
   const bool IsArch32Bit = ToolChain.getTriple().isArch32Bit();
@@ -129,6 +130,12 @@
 Args.MakeArgString(ToolChain.GetFilePath(getCrt0Basename(;
   }
 
+  // Collect all static constructor and destructor functions in CXX mode. This
+  // has to come before AddLinkerInputs as the implied option needs to precede
+  // any other '-bcdtors' settings or '-bnocdtors' that '-Wl' might forward.
+  if (D.CCCIsCXX())
+CmdArgs.push_back("-bcdtors:all:0:s");
+
   // Specify linker input file(s).
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D71739: [AssumeBundles] Use operand bundles to encode alignment assumptions

2020-05-22 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

> there is any IR legality restriction about what combination or number of 
> bundles can be present in an assume. however there is restrictions about 
> argument of a given bundle.
>  having a single "align" bundle is just how the front-end used assume bundles 
> for its alignment assumptions.

Hmm.  It does seem to be true that operand bundles don't inherently enforce 
that the names are unique on a callsite; the verifier just has an ever-growing 
list of bundles that it does that for specially.  That feels weird to me, but 
alright.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71739



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


[PATCH] D80126: Add documentation URL records to the .dia format and expose them via libclang

2020-05-22 Thread Jan Korous via Phabricator via cfe-commits
jkorous added inline comments.



Comment at: clang/lib/Frontend/SerializedDiagnosticReader.cpp:323
+  // A documentation URL has an ID and path size.
+  if (Record.size() != 2)
+return SDError::MalformedDiagnosticRecord;

owenv wrote:
> owenv wrote:
> > jkorous wrote:
> > > I am just wondering what happens with the ID. Shouldn't we pass it too?
> > I think the ID should be `Record[0]` in the call t 
> > visitDocumentationURLRecord below. I based this on the handling of category 
> > records.
> Sorry, I don't know how to reply without marking this as done
Got it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80126



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


[PATCH] D79526: [CUDA][HIP] Workaround for resolving host device function against wrong-sided function

2020-05-22 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D79526#2042680 , @tra wrote:

> Reduced test case:
>
>   struct a {
> __attribute__((device)) a(short);
> __attribute__((device)) operator unsigned() const;
> __attribute__((device)) operator int() const;
>   };
>   struct b {
> a d;
>   };
>   void f(b g) { b e = g; }
>
>
> Failure:
>
>   $ bin/clang++ -x cuda aten.cc -fsyntax-only  
> --cuda-path=$HOME/local/cuda-10.1 --cuda-device-only --cuda-gpu-arch=sm_60 
> -stdlib=libc++ -std=c++17 -ferror-limit=1
>  
>   aten.cc:6:8: error: conversion from 'const a' to 'short' is ambiguous
>   struct b {
>  ^
>   aten.cc:9:21: note: in implicit copy constructor for 'b' first required here
>   void f(b g) { b e = g; }
>   ^
>   aten.cc:3:27: note: candidate function
> __attribute__((device)) operator unsigned() const;
> ^
>   aten.cc:4:27: note: candidate function
> __attribute__((device)) operator int() const;
> ^
>   aten.cc:2:34: note: passing argument to parameter here
> __attribute__((device)) a(short);
>^
>   1 error generated when compiling for sm_60.
>
>
> The same code compiles fine in C++ and I would expect it to work on device 
> side the same way.


a and b both have an implicit HD copy ctor. In device compilation, copy ctor of 
b is calling copy ctor of a. There are two candidates: implicit HD copy ctor of 
a, and device ctor a(short).

In my previous fix, I made H and implicit HD candidate equal, however I forgot 
about the relation between D candidate and HD candidate. I incorrectly made D 
favored over HD and H. This caused inferior device candidate a(short) chosen 
over copy ctor of a.

I have a fix for this https://reviews.llvm.org/D80450


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79526



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


[PATCH] D80450: [CUDA][HIP] Fix implicit HD function resolution

2020-05-22 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added a reviewer: tra.

When implicit HD function calls a function in device compilation,
if one candidate is an implicit HD function, current solution rule is:

D wins over HD and H
HD and H are equal

this caused regression when there is an otherwise worse D candidate

This patch changes that to

D, HD and H are all equal

The rationale is that we already know for host compilation there is already
a valid candidate in HD and H candidates that will not cause error. Allowing
HD and H gives us a fall back candidate that will not cause error. If D wins,
that means D has to be a better match otherwise, therefore D should also
be a valid candidate that will not cause error. In this way, we can guarantee
no regression.


https://reviews.llvm.org/D80450

Files:
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaCUDA/function-overload.cu


Index: clang/test/SemaCUDA/function-overload.cu
===
--- clang/test/SemaCUDA/function-overload.cu
+++ clang/test/SemaCUDA/function-overload.cu
@@ -541,3 +541,51 @@
   }
 };
 }
+
+// Implicit HD candidate competes with device candidate.
+// a and b have implicit HD copy ctor. In copy ctor of b, ctor of a is 
resolved.
+// copy ctor of a should win over a(short), otherwise there will be ambiguity
+// due to conversion operator.
+namespace TestImplicitHDWithD {
+  struct a {
+__attribute__((device)) a(short);
+__attribute__((device)) operator unsigned() const;
+__attribute__((device)) operator int() const;
+  };
+  struct b {
+a d;
+  };
+  void f(b g) { b e = g; }
+}
+
+// Implicit HD candidate competes with host candidate.
+// a and b have implicit HD copy ctor. In copy ctor of b, ctor of a is 
resolved.
+// copy ctor of a should win over a(short), otherwise there will be ambiguity
+// due to conversion operator.
+namespace TestImplicitHDWithH {
+  struct a {
+a(short);
+__attribute__((device)) operator unsigned() const;
+__attribute__((device)) operator int() const;
+  };
+  struct b {
+a d;
+  };
+  void f(b g) { b e = g; }
+}
+
+// Implicit HD candidate comptes with HD candidate.
+// a and b have implicit HD copy ctor. In copy ctor of b, ctor of a is 
resolved.
+// copy ctor of a should win over a(short), otherwise there will be ambiguity
+// due to conversion operator.
+namespace TestImplicitHDWithHD {
+  struct a {
+__attribute__((host,device)) a(short);
+__attribute__((device)) operator unsigned() const;
+__attribute__((device)) operator int() const;
+  };
+  struct b {
+a d;
+  };
+  void f(b g) { b e = g; }
+}
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -9534,7 +9534,7 @@
   auto EmitThreshold =
   (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
(IsCand1ImplicitHD || IsCand2ImplicitHD))
-  ? Sema::CFP_HostDevice
+  ? Sema::CFP_Never
   : Sema::CFP_WrongSide;
   auto Cand1Emittable = P1 > EmitThreshold;
   auto Cand2Emittable = P2 > EmitThreshold;


Index: clang/test/SemaCUDA/function-overload.cu
===
--- clang/test/SemaCUDA/function-overload.cu
+++ clang/test/SemaCUDA/function-overload.cu
@@ -541,3 +541,51 @@
   }
 };
 }
+
+// Implicit HD candidate competes with device candidate.
+// a and b have implicit HD copy ctor. In copy ctor of b, ctor of a is resolved.
+// copy ctor of a should win over a(short), otherwise there will be ambiguity
+// due to conversion operator.
+namespace TestImplicitHDWithD {
+  struct a {
+__attribute__((device)) a(short);
+__attribute__((device)) operator unsigned() const;
+__attribute__((device)) operator int() const;
+  };
+  struct b {
+a d;
+  };
+  void f(b g) { b e = g; }
+}
+
+// Implicit HD candidate competes with host candidate.
+// a and b have implicit HD copy ctor. In copy ctor of b, ctor of a is resolved.
+// copy ctor of a should win over a(short), otherwise there will be ambiguity
+// due to conversion operator.
+namespace TestImplicitHDWithH {
+  struct a {
+a(short);
+__attribute__((device)) operator unsigned() const;
+__attribute__((device)) operator int() const;
+  };
+  struct b {
+a d;
+  };
+  void f(b g) { b e = g; }
+}
+
+// Implicit HD candidate comptes with HD candidate.
+// a and b have implicit HD copy ctor. In copy ctor of b, ctor of a is resolved.
+// copy ctor of a should win over a(short), otherwise there will be ambiguity
+// due to conversion operator.
+namespace TestImplicitHDWithHD {
+  struct a {
+__attribute__((host,device)) a(short);
+__attribute__((device)) operator unsigned() const;
+__attribute__((device)) operator int() const;
+  };
+  struct b {
+a d;
+  };
+  void f(b g) { b e = g; }
+}
Index: clang/lib/Sema/SemaOverload.cpp
===

[PATCH] D76510: [analyzer] Change the default output type to PD_TEXT_MINIMAL in the frontend, error if an output loc is missing for PathDiagConsumers that need it

2020-05-22 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

This isn't so bad as far as news go, considering you saved a lot of work for me 
in terms of reproducing this! I'll look into it, thanks! I admit to not use 
`scan-build` much. :^)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76510



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


[PATCH] D80415: [AIX] Add '-bcdtors:all:0:s' to linker to gather static init functions

2020-05-22 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/test/Driver/aix-ld.cpp:9
+// CHECK-LD32-ARG-ORDER-NOT: warning:
+// CHECK-LD32-ARG-ORDER: {{.*}}clang{{(.exe)?}}" "-cc1" "-triple" 
"powerpc-ibm-aix7.1.0.0"
+// CHECK-LD32-ARG-ORDER: "-isysroot" "[[SYSROOT:[^"]+]]"

I am not sure I've seen this used in conjunction with `%clangxx`.
`"{{.*}}clang{{.*}}"` seems appropriate based on existing usage.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80415



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


[clang] 429f030 - Revert "[analyzer] Change the default output type to PD_TEXT_MINIMAL in the frontend, error if an output loc is missing for PathDiagConsumers that need it"

2020-05-22 Thread Kirstóf Umann via cfe-commits

Author: Kirstóf Umann
Date: 2020-05-22T20:18:16+02:00
New Revision: 429f03089951d62fb370026905c87f1f25cf220f

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

LOG: Revert "[analyzer] Change the default output type to PD_TEXT_MINIMAL in 
the frontend, error if an output loc is missing for PathDiagConsumers that need 
it"

This reverts commit fe1a3a7e8c8be33968b9a768666489823dabab10.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Removed: 
clang/test/Analysis/output_types.cpp



diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index fdca8532ab53..d010a7dfb2de 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -358,9 +358,6 @@ def err_analyzer_checker_option_invalid_input : Error<
   "invalid input for checker option '%0', that expects %1">;
 def err_analyzer_checker_incompatible_analyzer_option : Error<
   "checker cannot be enabled with analyzer option '%0' == %1">;
-def err_analyzer_missing_output_loc : Error<
-  "analyzer output type '%0' requires an output %1 to be specified with "
-  "-o ">;
 
 def err_drv_invalid_hvx_length : Error<
   "-mhvx-length is not supported without a -mhvx/-mhvx= flag">;

diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
index 373caa30bbc9..d2df24a6e21b 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
@@ -206,7 +206,7 @@ class AnalyzerOptions : public 
RefCountedBase {
   ConfigTable Config;
   AnalysisStores AnalysisStoreOpt = RegionStoreModel;
   AnalysisConstraints AnalysisConstraintsOpt = RangeConstraintsModel;
-  AnalysisDiagClients AnalysisDiagOpt = PD_TEXT_MINIMAL;
+  AnalysisDiagClients AnalysisDiagOpt = PD_HTML;
   AnalysisPurgeMode AnalysisPurgeOpt = PurgeStmt;
 
   std::string AnalyzeSpecificFunction;

diff  --git a/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp 
b/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
index 8ce3aa2e081e..184fdcfb3d4b 100644
--- a/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
@@ -21,7 +21,6 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/Token.h"
-#include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Rewrite/Core/HTMLRewrite.h"
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
@@ -138,14 +137,18 @@ void ento::createHTMLDiagnosticConsumer(
 const std::string &OutputDir, const Preprocessor &PP,
 const cross_tu::CrossTranslationUnitContext &CTU) {
 
-  if (OutputDir.empty()) {
-PP.getDiagnostics().Report(diag::err_analyzer_missing_output_loc)
-  << "html" << "directory";
+  // FIXME: HTML is currently our default output type, but if the output
+  // directory isn't specified, it acts like if it was in the minimal text
+  // output mode. This doesn't make much sense, we should have the minimal text
+  // as our default. In the case of backward compatibility concerns, this could
+  // be preserved with -analyzer-config-compatibility-mode=true.
+  createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, CTU);
+
+  // TODO: Emit an error here.
+  if (OutputDir.empty())
 return;
-  }
 
   C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, true));
-  createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, CTU);
 }
 
 void ento::createHTMLSingleFileDiagnosticConsumer(
@@ -153,11 +156,9 @@ void ento::createHTMLSingleFileDiagnosticConsumer(
 const std::string &OutputDir, const Preprocessor &PP,
 const cross_tu::CrossTranslationUnitContext &CTU) {
 
-  if (OutputDir.empty()) {
-PP.getDiagnostics().Report(diag::err_analyzer_missing_output_loc)
-  << "html-single-file" << "directory";
+  // TODO: Emit an error here.
+  if (OutputDir.empty())
 return;
-  }
 
   C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, false));
   createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, CTU);
@@ -167,13 +168,6 @@ void ento::createPlistHTMLDiagnosticConsumer(
 AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
 const std::string &prefix, const Preprocessor &PP,
 const cross_tu::CrossTranslationUnitContext &CTU) {
-
-  if (prefix.empty()) {
-

  1   2   >