[clang] 0c4935b - [docs/Coverage] Document -show-region-summary

2021-02-12 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2021-02-12T12:05:45-08:00
New Revision: 0c4935bb85166a4a0bf87a320b81e400d7be04f0

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

LOG: [docs/Coverage] Document -show-region-summary

As a drive-by, fix the section in the clang docs about the number of
statistics visible in a report.

Added: 


Modified: 
clang/docs/SourceBasedCodeCoverage.rst
llvm/docs/CommandGuide/llvm-cov.rst

Removed: 




diff  --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index b9cfe0f90297..a54bba94eb98 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -251,7 +251,7 @@ the exported data at a high level in the llvm-cov source 
code.
 Interpreting reports
 
 
-There are four statistics tracked in a coverage summary:
+There are five statistics tracked in a coverage summary:
 
 * Function coverage is the percentage of functions which have been executed at
   least once. A function is considered to be executed if any of its
@@ -260,7 +260,8 @@ There are four statistics tracked in a coverage summary:
 * Instantiation coverage is the percentage of function instantiations which
   have been executed at least once. Template functions and static inline
   functions from headers are two kinds of functions which may have multiple
-  instantiations.
+  instantiations. This statistic is hidden by default in reports, but can be
+  enabled via the ``-show-instantiation-summary`` option.
 
 * Line coverage is the percentage of code lines which have been executed at
   least once. Only executable lines within function bodies are considered to be

diff  --git a/llvm/docs/CommandGuide/llvm-cov.rst 
b/llvm/docs/CommandGuide/llvm-cov.rst
index 288d41b3ff70..d6e638f8f61d 100644
--- a/llvm/docs/CommandGuide/llvm-cov.rst
+++ b/llvm/docs/CommandGuide/llvm-cov.rst
@@ -364,6 +364,10 @@ OPTIONS
  universal binary or to use an architecture that does not match a
  non-universal binary.
 
+.. option:: -show-region-summary
+
+ Show statistics for all regions. Defaults to true.
+
 .. option:: -show-branch-summary
 
  Show statistics for all branch conditions. Defaults to true.



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


[clang] 13bd6fb - [docs/Coverage] Answer FAQ about optimization

2021-02-12 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2021-02-12T12:05:38-08:00
New Revision: 13bd6fb43da9e9b1d7e82272325ec781d1f16456

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

LOG: [docs/Coverage] Answer FAQ about optimization

Added: 


Modified: 
clang/docs/SourceBasedCodeCoverage.rst

Removed: 




diff  --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index 90feb41b0a3f..b9cfe0f90297 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -305,6 +305,19 @@ Format compatibility guarantees
   minor version increment is for added functionality, and patch version
   increments are for bugfixes.
 
+Impact of llvm optimizations on coverage reports
+
+
+llvm optimizations (such as inlining or CFG simplification) should have no
+impact on coverage report quality. This is due to the fact that the mapping
+from source regions to profile counters is immutable, and is generated before
+the llvm optimizer kicks in. The optimizer can't prove that profile counter
+instrumentation is safe to delete (because it's not: it affects the profile the
+program emits), and so leaves it alone.
+
+Note that this coverage feature does not rely on information that can degrade
+during the course of optimization, such as debug info line tables.
+
 Using the profiling runtime without static initializers
 ===
 



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


[clang] e05baf4 - [InitLLVM] Ensure SIGPIPE handler installed before sigaction()

2021-01-08 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2021-01-08T15:13:04-08:00
New Revision: e05baf40de8a3bbfcf4a765761b1147e94b7309c

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

LOG: [InitLLVM] Ensure SIGPIPE handler installed before sigaction()

The pipe signal handler must be installed before any other handlers are
registered. This is because the Unix RegisterHandlers function does not
perform a sigaction() for SIGPIPE unless a one-shot handler is present,
to allow long-lived processes (like lldb) to fully opt-out of llvm's
SIGPIPE handling and ignore the signal safely.

Fixes a bug introduced in D70277.

Tested by running Nick's test case:

% xcrun ./bin/clang -E -fno-integrated-cc1 x.c | tee foo.txt | head

I verified that child cc1 process exits with IO_ERR, and that the parent
recognizes the error code, exiting cleanly.

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

Added: 
clang/test/Driver/sigpipe-handling.c

Modified: 
llvm/include/llvm/Support/InitLLVM.h
llvm/lib/Support/InitLLVM.cpp

Removed: 




diff  --git a/clang/test/Driver/sigpipe-handling.c 
b/clang/test/Driver/sigpipe-handling.c
new file mode 100644
index ..852f0bfaf798
--- /dev/null
+++ b/clang/test/Driver/sigpipe-handling.c
@@ -0,0 +1,9 @@
+// REQUIRES: shell
+// RUN: %clang -E -fno-integrated-cc1 %s | head | FileCheck %s
+
+// Test that the parent clang driver process doesn't crash when the child cc1
+// process receives a SIGPIPE (Unix-only).
+//
+// The child should exit with IO_ERR, and the parent should exit cleanly.
+
+// CHECK: sigpipe-handling.c

diff  --git a/llvm/include/llvm/Support/InitLLVM.h 
b/llvm/include/llvm/Support/InitLLVM.h
index 3be8d6b6d2e0..879dc1514d10 100644
--- a/llvm/include/llvm/Support/InitLLVM.h
+++ b/llvm/include/llvm/Support/InitLLVM.h
@@ -9,6 +9,7 @@
 #ifndef LLVM_SUPPORT_LLVM_H
 #define LLVM_SUPPORT_LLVM_H
 
+#include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/PrettyStackTrace.h"
@@ -44,7 +45,7 @@ class InitLLVM {
 private:
   BumpPtrAllocator Alloc;
   SmallVector Args;
-  PrettyStackTraceProgram StackPrinter;
+  Optional StackPrinter;
 };
 } // namespace llvm
 

diff  --git a/llvm/lib/Support/InitLLVM.cpp b/llvm/lib/Support/InitLLVM.cpp
index 5c56b773ea69..152de6ebae0a 100644
--- a/llvm/lib/Support/InitLLVM.cpp
+++ b/llvm/lib/Support/InitLLVM.cpp
@@ -22,10 +22,17 @@ using namespace llvm;
 using namespace llvm::sys;
 
 InitLLVM::InitLLVM(int , const char **,
-   bool InstallPipeSignalExitHandler)
-: StackPrinter(Argc, Argv) {
+   bool InstallPipeSignalExitHandler) {
   if (InstallPipeSignalExitHandler)
+// The pipe signal handler must be installed before any other handlers are
+// registered. This is because the Unix \ref RegisterHandlers function does
+// not perform a sigaction() for SIGPIPE unless a one-shot handler is
+// present, to allow long-lived processes (like lldb) to fully opt-out of
+// llvm's SIGPIPE handling and ignore the signal safely.
 sys::SetOneShotPipeSignalFunction(sys::DefaultOneShotPipeSignalHandler);
+  // Initialize the stack printer after installing the one-shot pipe signal
+  // handler, so we can perform a sigaction() for SIGPIPE on Unix if requested.
+  StackPrinter.emplace(Argc, Argv);
   sys::PrintStackTraceOnErrorSignal(Argv[0]);
   install_out_of_memory_new_handler();
 



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


[clang] 06bc685 - [ubsan] nullability-arg: Fix crash on C++ member pointers

2020-09-28 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-09-28T09:41:18-07:00
New Revision: 06bc685fa2400cc28282ab6dd3c917d45bfa662f

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

LOG: [ubsan] nullability-arg: Fix crash on C++ member pointers

Extend -fsanitize=nullability-arg to handle call sites which accept C++
member pointers.

rdar://62476022

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

Added: 
clang/test/CodeGenCXX/ubsan-nullability-arg.cpp

Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CodeGenFunction.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 9ccbe87fab66..dd3f85617522 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3785,10 +3785,7 @@ void CodeGenFunction::EmitNonNullArgCheck(RValue RV, 
QualType ArgType,
   }
 
   SanitizerScope SanScope(this);
-  assert(RV.isScalar());
-  llvm::Value *V = RV.getScalarVal();
-  llvm::Value *Cond =
-  Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
+  llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
   llvm::Constant *StaticData[] = {
   EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
   llvm::ConstantInt::get(Int32Ty, ArgNo + 1),

diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 7351926035e6..27cf066466ca 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1175,6 +1175,13 @@ Address CodeGenFunction::EmitPointerWithAlignment(const 
Expr *E,
   return Address(EmitScalarExpr(E), Align);
 }
 
+llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
+  llvm::Value *V = RV.getScalarVal();
+  if (auto MPT = T->getAs())
+return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
+  return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
+}
+
 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
   if (Ty->isVoidType())
 return RValue::get(nullptr);

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index eb8a1125c7b6..16656de4e8f7 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3566,6 +3566,9 @@ class CodeGenFunction : public CodeGenTypeCache {
   // LValue Expression Emission
   
//======//
 
+  /// Create a check that a scalar RValue is non-null.
+  llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T);
+
   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
   RValue GetUndefRValue(QualType Ty);
 

diff  --git a/clang/test/CodeGenCXX/ubsan-nullability-arg.cpp 
b/clang/test/CodeGenCXX/ubsan-nullability-arg.cpp
new file mode 100644
index ..fbebd153a9ea
--- /dev/null
+++ b/clang/test/CodeGenCXX/ubsan-nullability-arg.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -x c++ -triple x86_64-apple-darwin10 -emit-llvm -o - %s 
-fsanitize=nullability-arg | FileCheck %s -check-prefixes=ITANIUM,ALL
+// RUN: %clang_cc1 -x c++ -triple x86_64-pc-windows-msvc -emit-llvm -o - %s 
-fsanitize=nullability-arg | FileCheck %s -check-prefixes=MSVC,ALL
+
+namespace method_ptr {
+
+struct S0 {
+  void foo1();
+};
+
+void foo1(void (S0::*_Nonnull f)());
+
+// ITANIUM-LABEL: @_ZN10method_ptr5test1Ev(){{.*}} {
+// ITANIUM: br i1 icmp ne (i64 ptrtoint (void (%"struct.method_ptr::S0"*)* 
@_ZN10method_ptr2S04foo1Ev to i64), i64 0), label %[[CONT:.*]], label 
%[[FAIL:[^,]*]]
+// ITANIUM-EMPTY:
+// ITANIUM-NEXT: [[FAIL]]:
+// ITANIUM-NEXT:   call void @__ubsan_handle_nullability_arg
+
+// MSVC-LABEL: @"?test1@method_ptr@@YAXXZ"(){{.*}} {
+// MSVC: br i1 true, label %[[CONT:.*]], label %[[FAIL:[^,]*]]
+// MSVC-EMPTY:
+// MSVC-NEXT: [[FAIL]]:
+// MSVC-NEXT:   call void @__ubsan_handle_nullability_arg
+void test1() {
+  foo1(::foo1);
+}
+
+} // namespace method_ptr
+
+namespace data_ptr {
+
+struct S0 {
+  int field1;
+};
+
+using member_ptr = int S0::*;
+
+void foo1(member_ptr _Nonnull);
+
+// ITANIUM-LABEL: @_ZN8data_ptr5test1ENS_2S0E(
+// MSVC-LABEL: @"?test1@data_ptr@@YAXUS0@1@@Z"(
+// ALL: [[DATA_PTR_CHECK:%.*]] = icmp ne {{.*}}, -1, !nosanitize
+// ALL-NEXT: br i1 [[DATA_PTR_CHECK]], label %[[CONT:.*]], label 
%[[FAIL:[^,]+]]
+// ALL-EMPTY:
+// ALL-NEXT: [[FAIL]]:
+// ALL-NEXT:   call void @__ubsan_handle_nullability_arg
+void test1(S0 s) {
+  int S0::*member = ::field1;
+  foo1(member);
+}
+
+} // namespace data_ptr



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


[clang] 62c3727 - [profile] Add %t LLVM_PROFILE_FILE option to substitute $TMPDIR

2020-09-25 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-09-25T09:39:40-07:00
New Revision: 62c372770d2e87f3e882a20d43c6814e6c4fe0f5

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

LOG: [profile] Add %t LLVM_PROFILE_FILE option to substitute $TMPDIR

Add support for expanding the %t filename specifier in LLVM_PROFILE_FILE
to the TMPDIR environment variable. This is supported on all platforms.

On Darwin, TMPDIR is used to specify a temporary application-specific
scratch directory. When testing apps on remote devices, it can be
challenging for the host device to determine the correct TMPDIR, so it's
helpful to have the runtime do this work.

rdar://68524185

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

Added: 
compiler-rt/test/profile/instrprof-tmpdir.c

Modified: 
clang/docs/SourceBasedCodeCoverage.rst
compiler-rt/lib/profile/InstrProfilingFile.c

Removed: 




diff  --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index 0e9c364fbf6b..f5b3d05262e9 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -79,6 +79,9 @@ directory structure will be created.  Additionally, the 
following special
 
 * "%h" expands out to the hostname of the machine running the program.
 
+* "%t" expands out to the value of the ``TMPDIR`` environment variable. On
+  Darwin, this is typically set to a temporary scratch directory.
+
 * "%Nm" expands out to the instrumented binary's signature. When this pattern
   is specified, the runtime creates a pool of N raw profiles which are used for
   on-line profile merging. The runtime takes care of selecting a raw profile

diff  --git a/compiler-rt/lib/profile/InstrProfilingFile.c 
b/compiler-rt/lib/profile/InstrProfilingFile.c
index 8c7bb0c25de1..b43f91794e28 100644
--- a/compiler-rt/lib/profile/InstrProfilingFile.c
+++ b/compiler-rt/lib/profile/InstrProfilingFile.c
@@ -72,6 +72,7 @@ typedef struct lprofFilename {
   unsigned OwnsFilenamePat;
   const char *ProfilePathPrefix;
   char PidChars[MAX_PID_SIZE];
+  char *TmpDir;
   char Hostname[COMPILER_RT_MAX_HOSTLEN];
   unsigned NumPids;
   unsigned NumHosts;
@@ -86,8 +87,8 @@ typedef struct lprofFilename {
   ProfileNameSpecifier PNS;
 } lprofFilename;
 
-static lprofFilename lprofCurFilename = {0, 0, 0, {0},{0},
- 0, 0, 0, PNS_unknown};
+static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
+ {0}, 0, 0, 0,   PNS_unknown};
 
 static int ProfileMergeRequested = 0;
 static int isProfileMergeRequested() { return ProfileMergeRequested; }
@@ -744,6 +745,14 @@ static int parseFilenamePattern(const char *FilenamePat,
   FilenamePat);
 return -1;
   }
+  } else if (FilenamePat[I] == 't') {
+lprofCurFilename.TmpDir = getenv("TMPDIR");
+if (!lprofCurFilename.TmpDir) {
+  PROF_WARN("Unable to get the TMPDIR environment variable, referenced 
"
+"in %s. Using the default path.",
+FilenamePat);
+  return -1;
+}
   } else if (FilenamePat[I] == 'c') {
 if (__llvm_profile_is_continuous_mode_enabled()) {
   PROF_WARN("%%c specifier can only be specified once in %s.\n",
@@ -827,12 +836,13 @@ static int getCurFilenameLength() {
 return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-lprofCurFilename.MergePoolSize))
+lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
 return strlen(lprofCurFilename.FilenamePat);
 
   Len = strlen(lprofCurFilename.FilenamePat) +
 lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
-lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2);
+lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
+(lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
   if (lprofCurFilename.MergePoolSize)
 Len += SIGLEN;
   return Len;
@@ -844,14 +854,14 @@ static int getCurFilenameLength() {
  * current filename pattern string is directly returned, unless ForceUseBuf
  * is enabled. */
 static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
-  int I, J, PidLength, HostNameLength, FilenamePatLength;
+  int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;
   const char *FilenamePat = lprofCurFilename.FilenamePat;
 
   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
 return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-lprofCurFilename.MergePoolSize ||
+lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
 

Re: [PATCH] D79219: [CMake] Simplify CMake handling for zlib

2020-07-25 Thread Vedant Kumar via cfe-commits
Thanks, that addressed the issue.

> On Jul 24, 2020, at 1:41 PM, Petr Hosek  wrote:
> 
> Thanks for the heads up, this should be addressed by 
> c86f56e32e724c6018e579bb2bc11e667c96fc96, let me know if there are other 
> issues.
> 
> On Fri, Jul 24, 2020 at 12:33 PM Vedant Kumar via Phabricator 
> mailto:revi...@reviews.llvm.org>> wrote:
> vsk added a comment.
> 
> @phosek I suspect this is causing a cmake error on the lldb standalone bot, 
> would you mind taking a look?
> 
> http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake-standalone/1858/ 
> 
> 
>   CMake Error at 
> /Users/buildslave/jenkins/workspace/lldb-cmake-standalone/clang-build/lib/cmake/llvm/AddLLVM.cmake:823
>  (add_executable):
> Target "lit-cpuid" links to target "ZLIB::ZLIB" but the target was not
> found.  Perhaps a find_package() call is missing for an IMPORTED target, 
> or
> an ALIAS target is missing?
>   Call Stack (most recent call first):
> cmake/modules/AddLLDB.cmake:165 (add_llvm_executable)
> utils/lit-cpuid/CMakeLists.txt:1 (add_lldb_executable)
> 
> 
> Repository:
>   rG LLVM Github Monorepo
> 
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D79219/new/ 
> 
> https://reviews.llvm.org/D79219 
> 
> 
> 

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


[clang] 8c4a65b - [ubsan] Check implicit casts in ObjC for-in statements

2020-07-13 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-07-13T15:11:18-07:00
New Revision: 8c4a65b9b2ca6961139beca92de37eea479f00fa

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

LOG: [ubsan] Check implicit casts in ObjC for-in statements

Check that the implicit cast from `id` used to construct the element
variable in an ObjC for-in statement is valid.

This check is included as part of a new `objc-cast` sanitizer, outside
of the main 'undefined' group, as (IIUC) the behavior it's checking for
is not technically UB.

The check can be extended to cover other kinds of invalid casts in ObjC.

Partially addresses: rdar://12903059, rdar://9542496

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

Added: 
compiler-rt/test/ubsan/TestCases/Misc/objc-cast.m

Modified: 
clang/docs/UndefinedBehaviorSanitizer.rst
clang/include/clang/Basic/Sanitizers.def
clang/lib/CodeGen/CGObjC.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/CodeGenObjC/for-in.m
compiler-rt/lib/ubsan/ubsan_checks.inc
compiler-rt/lib/ubsan/ubsan_handlers.cpp
compiler-rt/lib/ubsan/ubsan_handlers.h
compiler-rt/lib/ubsan/ubsan_value.cpp
compiler-rt/lib/ubsan/ubsan_value.h
compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp

Removed: 




diff  --git a/clang/docs/UndefinedBehaviorSanitizer.rst 
b/clang/docs/UndefinedBehaviorSanitizer.rst
index 0a27810150db..76676dfce95b 100644
--- a/clang/docs/UndefinedBehaviorSanitizer.rst
+++ b/clang/docs/UndefinedBehaviorSanitizer.rst
@@ -127,6 +127,10 @@ Available checks are:
  is annotated with ``_Nonnull``.
   -  ``-fsanitize=nullability-return``: Returning null from a function with
  a return type annotated with ``_Nonnull``.
+  -  ``-fsanitize=objc-cast``: Invalid implicit cast of an ObjC object pointer
+ to an incompatible type. This is often unintentional, but is not undefined
+ behavior, therefore the check is not a part of the ``undefined`` group.
+ Currently only supported on Darwin.
   -  ``-fsanitize=object-size``: An attempt to potentially use bytes which
  the optimizer can determine are not part of the object being accessed.
  This will also detect some types of undefined behavior that may not

diff  --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index 0037cc2146f2..2912bdd44b2d 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -156,6 +156,8 @@ SANITIZER_GROUP("implicit-integer-arithmetic-value-change",
 ImplicitIntegerArithmeticValueChange,
 ImplicitIntegerSignChange | ImplicitSignedIntegerTruncation)
 
+SANITIZER("objc-cast", ObjCCast)
+
 // FIXME:
 //SANITIZER_GROUP("implicit-integer-conversion", ImplicitIntegerConversion,
 //ImplicitIntegerArithmeticValueChange |

diff  --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index 158a548e66c1..cd2b84f5dd20 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -1836,6 +1836,40 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const 
ObjCForCollectionStmt ){
   llvm::Value *CurrentItem =
 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
 
+  if (SanOpts.has(SanitizerKind::ObjCCast)) {
+// Before using an item from the collection, check that the implicit cast
+// from id to the element type is valid. This is done with instrumentation
+// roughly corresponding to:
+//
+//   if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
+const ObjCObjectPointerType *ObjPtrTy =
+elementType->getAsObjCInterfacePointerType();
+const ObjCInterfaceType *InterfaceTy =
+ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
+if (InterfaceTy) {
+  SanitizerScope SanScope(this);
+  auto  = CGM.getContext();
+  assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
+  Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
+  CallArgList IsKindOfClassArgs;
+  llvm::Value *Cls =
+  CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
+  IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
+  llvm::Value *IsClass =
+  CGM.getObjCRuntime()
+  .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
+   IsKindOfClassSel, CurrentItem,
+   IsKindOfClassArgs)
+  .getScalarVal();
+  llvm::Constant *StaticData[] = {
+  EmitCheckSourceLocation(S.getBeginLoc()),
+  EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
+  EmitCheck({{IsClass, 

[clang] a66e1d2 - [os_log][test] Remove -O1 from a test, NFC

2020-06-01 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-06-01T16:54:16-07:00
New Revision: a66e1d2aa943959e158821be8956109cb5ef3b3b

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

LOG: [os_log][test] Remove -O1 from a test, NFC

Added: 


Modified: 
clang/test/CodeGenObjCXX/os_log.mm

Removed: 




diff  --git a/clang/test/CodeGenObjCXX/os_log.mm 
b/clang/test/CodeGenObjCXX/os_log.mm
index 7ed104f5e78e..b6e0bc25ca80 100644
--- a/clang/test/CodeGenObjCXX/os_log.mm
+++ b/clang/test/CodeGenObjCXX/os_log.mm
@@ -1,7 +1,5 @@
 // RUN: %clang_cc1 %s -emit-llvm -o - -triple x86_64-darwin-apple -fobjc-arc \
-// RUN:   -fexceptions -fcxx-exceptions -O1 -fno-experimental-new-pass-manager 
| FileCheck %s
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple x86_64-darwin-apple -fobjc-arc \
-// RUN:   -fexceptions -fcxx-exceptions -O1 -fexperimental-new-pass-manager 
-fno-inline | FileCheck %s
+// RUN:   -fexceptions -fcxx-exceptions | FileCheck %s
 
 // Check that no EH cleanup is emitted around the call to __os_log_helper.
 namespace no_eh_cleanup {
@@ -10,11 +8,11 @@
   // CHECK-LABEL: define {{.*}} @_ZN13no_eh_cleanup3logERiPcS1_(
   void log(int , char *data, char *buf) {
   int lock __attribute__((cleanup(release)));
-  // CHECK: call void @__os_log_helper_1_2_2_4_0_8_34(
-  // CHECK-NEXT: call void @_ZN13no_eh_cleanup7releaseEPi
   __builtin_os_log_format(buf, "%d %{public}s", i, data);
   }
 
+  // An `invoke` of a `nounwind` callee is simplified to a direct
+  // call by an optimization in llvm. Just check that we emit `nounwind`.
   // CHECK: define {{.*}} @__os_log_helper_1_2_2_4_0_8_34({{.*}} 
[[NUW:#[0-9]+]]
 }
 



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


[clang] cfb4f8c - [DirectoryWatcher] Do not use FSEvents on non-macOS platforms

2020-04-23 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-04-23T10:22:28-07:00
New Revision: cfb4f8c5fbc6fd8ad06bcfc6f91926b6d55d3766

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

LOG: [DirectoryWatcher] Do not use FSEvents on non-macOS platforms

The FSEvents APIs are available on iOS6+: however, the DirectoryWatcher
code isn't wired up to really use FSEvents on embedded platforms.

I've duplicated code from DirectoryWatcher-not-implemented.cpp here and
used TargetConditionals instead of adding cmakery to check try_compile;
I couldn't get that to work properly.

Added: 


Modified: 
clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp

Removed: 




diff  --git a/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp 
b/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
index 7864fb76d160..bdc389516289 100644
--- a/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
+++ b/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
@@ -14,10 +14,13 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/Path.h"
 #include 
+#include 
 
 using namespace llvm;
 using namespace clang;
 
+#if TARGET_OS_OSX
+
 static void stopFSEventStream(FSEventStreamRef);
 
 namespace {
@@ -249,3 +252,17 @@ llvm::Expected> 
clang::DirectoryWatcher::creat
 
   return Result;
 }
+
+#else // TARGET_OS_OSX
+
+llvm::Expected>
+clang::DirectoryWatcher::create(
+StringRef Path,
+std::function, bool)> 
Receiver,
+bool WaitForInitialSync) {
+  return llvm::make_error(
+  "DirectoryWatcher is not implemented for this platform!",
+  llvm::inconvertibleErrorCode());
+}
+
+#endif // TARGET_OS_OSX



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


[clang] 47622ef - [clang/test] Add test for DIFlagAllCallsDescribed under -ggdb + -gdwarf-4, NFC

2020-03-18 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-03-18T15:24:13-07:00
New Revision: 47622efc6f01532ef1c23490f516efb9081827f8

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

LOG: [clang/test] Add test for DIFlagAllCallsDescribed under -ggdb + -gdwarf-4, 
NFC

Added: 


Modified: 
clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp 
b/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
index 667c2469b55e..72caf119f869 100644
--- a/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
+++ b/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
@@ -22,6 +22,18 @@
 // RUN: | FileCheck %s -check-prefix=HAS-ATTR \
 // RUN: -implicit-check-not=DIFlagAllCallsDescribed
 
+// Note: DIFlagAllCallsDescribed may have been enabled prematurely when tuning
+// for GDB under -gdwarf-4 in https://reviews.llvm.org/D69743. It's possible
+// this should have been 'Unsupported' until entry values emission was enabled
+// by default.
+//
+// Supported: DWARF4 + GDB tuning
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-linux-gnu \
+// RUN:   %s -o - -O1 -disable-llvm-passes -debugger-tuning=gdb \
+// RUN:   -debug-info-kind=standalone -dwarf-version=4 \
+// RUN: | FileCheck %s -check-prefix=HAS-ATTR \
+// RUN: -implicit-check-not=DIFlagAllCallsDescribed
+
 // Supported: DWARF4 + LLDB tuning by using '-femit-debug-entry-values'
 // RUN: %clang_cc1 -femit-debug-entry-values -emit-llvm -triple 
x86_64-linux-gnu \
 // RUN:   %s -o - -O1 -disable-llvm-passes -debugger-tuning=lldb \



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


[clang] dd1ea9d - Reland: [Coverage] Revise format to reduce binary size

2020-02-28 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-02-28T18:12:04-08:00
New Revision: dd1ea9de2e3e3ac80a620f71411a9a36449f2697

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

LOG: Reland: [Coverage] Revise format to reduce binary size

Try again with an up-to-date version of D69471 (99317124 was a stale
revision).

---

Revise the coverage mapping format to reduce binary size by:

1. Naming function records and marking them `linkonce_odr`, and
2. Compressing filenames.

This shrinks the size of llc's coverage segment by 82% (334MB -> 62MB)
and speeds up end-to-end single-threaded report generation by 10%. For
reference the compressed name data in llc is 81MB (__llvm_prf_names).

Rationale for changes to the format:

- With the current format, most coverage function records are discarded.
  E.g., more than 97% of the records in llc are *duplicate* placeholders
  for functions visible-but-not-used in TUs. Placeholders *are* used to
  show under-covered functions, but duplicate placeholders waste space.

- We reached general consensus about giving (1) a try at the 2017 code
  coverage BoF [1]. The thinking was that using `linkonce_odr` to merge
  duplicates is simpler than alternatives like teaching build systems
  about a coverage-aware database/module/etc on the side.

- Revising the format is expensive due to the backwards compatibility
  requirement, so we might as well compress filenames while we're at it.
  This shrinks the encoded filenames in llc by 86% (12MB -> 1.6MB).

See CoverageMappingFormat.rst for the details on what exactly has
changed.

Fixes PR34533 [2], hopefully.

[1] http://lists.llvm.org/pipermail/llvm-dev/2017-October/118428.html
[2] https://bugs.llvm.org/show_bug.cgi?id=34533

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

Added: 
llvm/test/tools/llvm-cov/Inputs/binary-formats.v3.macho64l

Modified: 
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/lib/CodeGen/CoverageMappingGen.h
clang/test/CoverageMapping/abspath.cpp
clang/test/CoverageMapping/ir.c
clang/test/Profile/def-assignop.cpp
clang/test/Profile/def-ctors.cpp
clang/test/Profile/def-dtors.cpp
compiler-rt/include/profile/InstrProfData.inc
llvm/docs/CoverageMappingFormat.rst
llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h
llvm/include/llvm/ProfileData/Coverage/CoverageMappingWriter.h
llvm/include/llvm/ProfileData/InstrProf.h
llvm/include/llvm/ProfileData/InstrProfData.inc
llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp
llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
llvm/lib/ProfileData/InstrProf.cpp
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
llvm/test/Instrumentation/InstrProfiling/X86/alloc.ll
llvm/test/tools/llvm-cov/binary-formats.c
llvm/unittests/ProfileData/CoverageMappingTest.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index ee85694f043a..acf0b5a75336 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -13,6 +13,8 @@
 #include "CoverageMappingGen.h"
 #include "CodeGenFunction.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
@@ -24,6 +26,10 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
 
+// This selects the coverage mapping format defined when `InstrProfData.inc`
+// is textually included.
+#define COVMAP_V3
+
 using namespace clang;
 using namespace CodeGen;
 using namespace llvm::coverage;
@@ -1272,12 +1278,6 @@ struct CounterCoverageMappingBuilder
   }
 };
 
-std::string getCoverageSection(const CodeGenModule ) {
-  return llvm::getInstrProfSectionName(
-  llvm::IPSK_covmap,
-  CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
-}
-
 std::string normalizeFilename(StringRef Filename) {
   llvm::SmallString<256> Path(Filename);
   llvm::sys::fs::make_absolute(Path);
@@ -1317,30 +1317,71 @@ static void dump(llvm::raw_ostream , StringRef 
FunctionName,
   }
 }
 
-void CoverageMappingModuleGen::addFunctionMappingRecord(
-llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
-const std::string , bool IsUsed) {
+static std::string getInstrProfSection(const CodeGenModule ,
+   llvm::InstrProfSectKind SK) {
+  return llvm::getInstrProfSectionName(
+  SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
+}

[clang] 3388871 - Revert "[Coverage] Revise format to reduce binary size"

2020-02-28 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-02-28T18:03:15-08:00
New Revision: 3388871714d3b718b823e76499b0c03877105e5d

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

LOG: Revert "[Coverage] Revise format to reduce binary size"

This reverts commit 99317124e1c772e9a9de41a0cd56e1db049b4ea4. This is
still busted on Windows:

http://lab.llvm.org:8011/builders/lld-x86_64-win7/builds/40873

The llvm-cov tests report 'error: Could not load coverage information'.

Added: 


Modified: 
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/lib/CodeGen/CoverageMappingGen.h
clang/test/CoverageMapping/abspath.cpp
clang/test/CoverageMapping/ir.c
clang/test/Profile/def-assignop.cpp
clang/test/Profile/def-ctors.cpp
clang/test/Profile/def-dtors.cpp
compiler-rt/include/profile/InstrProfData.inc
llvm/docs/CoverageMappingFormat.rst
llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h
llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h
llvm/include/llvm/ProfileData/Coverage/CoverageMappingWriter.h
llvm/include/llvm/ProfileData/InstrProf.h
llvm/include/llvm/ProfileData/InstrProfData.inc
llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
llvm/lib/ProfileData/Coverage/CoverageMapping.cpp
llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp
llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
llvm/lib/ProfileData/InstrProf.cpp
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
llvm/test/Instrumentation/InstrProfiling/X86/alloc.ll
llvm/test/tools/llvm-cov/binary-formats.c
llvm/unittests/ProfileData/CoverageMappingTest.cpp

Removed: 
llvm/test/tools/llvm-cov/Inputs/binary-formats.v3.macho64l



diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index acf0b5a75336..ee85694f043a 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -13,8 +13,6 @@
 #include "CoverageMappingGen.h"
 #include "CodeGenFunction.h"
 #include "clang/AST/StmtVisitor.h"
-#include "clang/Basic/Diagnostic.h"
-#include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
@@ -26,10 +24,6 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
 
-// This selects the coverage mapping format defined when `InstrProfData.inc`
-// is textually included.
-#define COVMAP_V3
-
 using namespace clang;
 using namespace CodeGen;
 using namespace llvm::coverage;
@@ -1278,6 +1272,12 @@ struct CounterCoverageMappingBuilder
   }
 };
 
+std::string getCoverageSection(const CodeGenModule ) {
+  return llvm::getInstrProfSectionName(
+  llvm::IPSK_covmap,
+  CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
+}
+
 std::string normalizeFilename(StringRef Filename) {
   llvm::SmallString<256> Path(Filename);
   llvm::sys::fs::make_absolute(Path);
@@ -1317,71 +1317,30 @@ static void dump(llvm::raw_ostream , StringRef 
FunctionName,
   }
 }
 
-static std::string getInstrProfSection(const CodeGenModule ,
-   llvm::InstrProfSectKind SK) {
-  return llvm::getInstrProfSectionName(
-  SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
-}
-
-void CoverageMappingModuleGen::emitFunctionMappingRecord(
-const FunctionInfo , uint64_t FilenamesRef) {
+void CoverageMappingModuleGen::addFunctionMappingRecord(
+llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
+const std::string , bool IsUsed) {
   llvm::LLVMContext  = CGM.getLLVMContext();
-
-  // Assign a name to the function record. This is used to merge duplicates.
-  std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
-
-  // A dummy description for a function included-but-not-used in a TU can be
-  // replaced by full description provided by a 
diff erent TU. The two kinds of
-  // descriptions play distinct roles: therefore, assign them 
diff erent names
-  // to prevent `linkonce_odr` merging.
-  if (Info.IsUsed)
-FuncRecordName += "u";
-
-  // Create the function record type.
-  const uint64_t NameHash = Info.NameHash;
-  const uint64_t FuncHash = Info.FuncHash;
-  const std::string  = Info.CoverageMapping;
+  if (!FunctionRecordTy) {
 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
-  llvm::Type *FunctionRecordTypes[] = {
-#include "llvm/ProfileData/InstrProfData.inc"
-  };
-  auto *FunctionRecordTy =
-  llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
-/*isPacked=*/true);
+llvm::Type *FunctionRecordTypes[] = {
+  #include "llvm/ProfileData/InstrProfData.inc"
+};
+FunctionRecordTy =
+

[clang] c54597b - [ubsan] Add support for -fsanitize=nullability-* suppressions

2020-02-28 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-02-28T14:30:40-08:00
New Revision: c54597b99d6f6ea51616168a0c2ff3850c3869eb

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

LOG: [ubsan] Add support for -fsanitize=nullability-* suppressions

rdar://59402904

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.h
compiler-rt/lib/ubsan/ubsan_checks.inc
compiler-rt/lib/ubsan/ubsan_handlers.cpp
compiler-rt/test/ubsan/TestCases/Misc/nullability.c

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index c3b2ae0fda09..14111713ccac 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -2704,7 +2704,8 @@ class CodeGenFunction : public CodeGenTypeCache {
   Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
 
   /// Situations in which we might emit a check for the suitability of a
-  ///pointer or glvalue.
+  /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
+  /// compiler-rt.
   enum TypeCheckKind {
 /// Checking the operand of a load. Must be suitably sized and aligned.
 TCK_Load,

diff  --git a/compiler-rt/lib/ubsan/ubsan_checks.inc 
b/compiler-rt/lib/ubsan/ubsan_checks.inc
index 33a8dfcde026..2c1529a7d92c 100644
--- a/compiler-rt/lib/ubsan/ubsan_checks.inc
+++ b/compiler-rt/lib/ubsan/ubsan_checks.inc
@@ -18,6 +18,8 @@
 
 UBSAN_CHECK(GenericUB, "undefined-behavior", "undefined")
 UBSAN_CHECK(NullPointerUse, "null-pointer-use", "null")
+UBSAN_CHECK(NullPointerUseWithNullability, "null-pointer-use",
+"nullability-assign")
 UBSAN_CHECK(NullptrWithOffset, "nullptr-with-offset", "pointer-overflow")
 UBSAN_CHECK(NullptrWithNonZeroOffset, "nullptr-with-nonzero-offset",
 "pointer-overflow")
@@ -59,6 +61,10 @@ UBSAN_CHECK(InvalidEnumLoad, "invalid-enum-load", "enum")
 UBSAN_CHECK(FunctionTypeMismatch, "function-type-mismatch", "function")
 UBSAN_CHECK(InvalidNullReturn, "invalid-null-return",
 "returns-nonnull-attribute")
+UBSAN_CHECK(InvalidNullReturnWithNullability, "invalid-null-return",
+"nullability-return")
 UBSAN_CHECK(InvalidNullArgument, "invalid-null-argument", "nonnull-attribute")
+UBSAN_CHECK(InvalidNullArgumentWithNullability, "invalid-null-argument",
+"nullability-arg")
 UBSAN_CHECK(DynamicTypeMismatch, "dynamic-type-mismatch", "vptr")
 UBSAN_CHECK(CFIBadType, "cfi-bad-type", "cfi")

diff  --git a/compiler-rt/lib/ubsan/ubsan_handlers.cpp 
b/compiler-rt/lib/ubsan/ubsan_handlers.cpp
index 3f9da75a12a8..7f6a46fb6cf0 100644
--- a/compiler-rt/lib/ubsan/ubsan_handlers.cpp
+++ b/compiler-rt/lib/ubsan/ubsan_handlers.cpp
@@ -36,6 +36,45 @@ bool ignoreReport(SourceLocation SLoc, ReportOptions Opts, 
ErrorType ET) {
   return SLoc.isDisabled() || IsPCSuppressed(ET, Opts.pc, SLoc.getFilename());
 }
 
+/// Situations in which we might emit a check for the suitability of a
+/// pointer or glvalue. Needs to be kept in sync with CodeGenFunction.h in
+/// clang.
+enum TypeCheckKind {
+  /// Checking the operand of a load. Must be suitably sized and aligned.
+  TCK_Load,
+  /// Checking the destination of a store. Must be suitably sized and aligned.
+  TCK_Store,
+  /// Checking the bound value in a reference binding. Must be suitably sized
+  /// and aligned, but is not required to refer to an object (until the
+  /// reference is used), per core issue 453.
+  TCK_ReferenceBinding,
+  /// Checking the object expression in a non-static data member access. Must
+  /// be an object within its lifetime.
+  TCK_MemberAccess,
+  /// Checking the 'this' pointer for a call to a non-static member function.
+  /// Must be an object within its lifetime.
+  TCK_MemberCall,
+  /// Checking the 'this' pointer for a constructor call.
+  TCK_ConstructorCall,
+  /// Checking the operand of a static_cast to a derived pointer type. Must be
+  /// null or an object within its lifetime.
+  TCK_DowncastPointer,
+  /// Checking the operand of a static_cast to a derived reference type. Must
+  /// be an object within its lifetime.
+  TCK_DowncastReference,
+  /// Checking the operand of a cast to a base object. Must be suitably sized
+  /// and aligned.
+  TCK_Upcast,
+  /// Checking the operand of a cast to a virtual base object. Must be an
+  /// object within its lifetime.
+  TCK_UpcastToVirtualBase,
+  /// Checking the value assigned to a _Nonnull pointer. Must not be null.
+  TCK_NonnullAssign,
+  /// Checking the operand of a dynamic_cast or a typeid expression.  Must be
+  /// null or an object within its lifetime.
+  TCK_DynamicOperation
+};
+
 const char *TypeCheckKinds[] = {
 "load of", "store to", "reference binding to", "member access within",
 "member call on", "constructor call on", "downcast of", 

[clang] 8b81ebf - [ubsan] Null-check and adjust TypeLoc before using it

2020-02-10 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-02-10T14:10:06-08:00
New Revision: 8b81ebfe7eba089ed2016d523cc5ee9d05e957a7

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

LOG: [ubsan] Null-check and adjust TypeLoc before using it

Null-check and adjut a TypeLoc before casting it to a FunctionTypeLoc.
This fixes a crash in -fsanitize=nullability-return, and also makes the
location of the nonnull type available when the return type is adjusted.

rdar://59263039

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

Added: 
clang/test/CodeGenObjCXX/ubsan-nullability-return-notypeloc.mm

Modified: 
clang/lib/CodeGen/CGCall.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 9ef2a3b3d099..e6cb4a1fd93f 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3060,7 +3060,7 @@ void CodeGenFunction::EmitReturnValueCheck(llvm::Value 
*RV) {
   } else {
 if (auto *DD = dyn_cast(CurCodeDecl))
   if (auto *TSI = DD->getTypeSourceInfo())
-if (auto FTL = TSI->getTypeLoc().castAs())
+if (auto FTL = TSI->getTypeLoc().getAsAdjusted())
   AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
 CheckKind = SanitizerKind::NullabilityReturn;
 Handler = SanitizerHandler::NullabilityReturn;

diff  --git a/clang/test/CodeGenObjCXX/ubsan-nullability-return-notypeloc.mm 
b/clang/test/CodeGenObjCXX/ubsan-nullability-return-notypeloc.mm
new file mode 100644
index ..23025c9eb845
--- /dev/null
+++ b/clang/test/CodeGenObjCXX/ubsan-nullability-return-notypeloc.mm
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsanitize=nullability-return -emit-llvm %s -o - -triple 
x86_64-apple-macosx10.10.0 | FileCheck %s
+
+// CHECK: [[ATTR_LOC:@[0-9]+]] = {{.*}} global { {{.*}} i32 15, i32 38
+
+// CHECK-LABEL: define i8* @_Z3foov()
+// CHECK: [[CALL:%.*]] = call i8* @_Z6helperv()
+// CHECK: icmp ne i8* [[CALL]]
+// CHECK: call void 
@__ubsan_handle_nullability_return_v1_abort({{.*}}[[ATTR_LOC]]
+
+struct S {
+  using PtrTy = id;
+};
+
+#pragma clang assume_nonnull begin
+__attribute__((ns_returns_retained)) S::PtrTy foo(void) {
+  extern S::PtrTy helper(void);
+  return helper();
+}
+#pragma clang assume_nonnull end



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


[clang] 65f0785 - [ubsan] Omit return value check when return block is unreachable

2020-02-06 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-02-06T10:24:03-08:00
New Revision: 65f0785fff0e45f8cd1b9e90328597197beef899

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

LOG: [ubsan] Omit return value check when return block is unreachable

If the return block is unreachable, clang removes it in
CodeGenFunction::FinishFunction(). This removal can leave dangling
references to values defined in the return block if the return block has
successors, which it /would/ if UBSan's return value check is emitted.

In this case, as the UBSan check wouldn't be reachable, it's better to
simply not emit it.

rdar://59196131

Added: 
clang/test/CodeGenObjC/ubsan-nullability-return-unreachable.m

Modified: 
clang/lib/CodeGen/CGCall.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index cdd3ca474edf..b55d5856d92d 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3035,6 +3035,11 @@ void CodeGenFunction::EmitReturnValueCheck(llvm::Value 
*RV) {
   if (!CurCodeDecl)
 return;
 
+  // If the return block isn't reachable, neither is this check, so don't emit
+  // it.
+  if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
+return;
+
   ReturnsNonNullAttr *RetNNAttr = nullptr;
   if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
 RetNNAttr = CurCodeDecl->getAttr();

diff  --git a/clang/test/CodeGenObjC/ubsan-nullability-return-unreachable.m 
b/clang/test/CodeGenObjC/ubsan-nullability-return-unreachable.m
new file mode 100644
index ..eabc33c91e78
--- /dev/null
+++ b/clang/test/CodeGenObjC/ubsan-nullability-return-unreachable.m
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fsanitize=nullability-return -emit-llvm %s -o - -triple 
x86_64-apple-macosx10.10.0 -Wno-objc-root-class | FileCheck %s
+
+// CHECK-LABEL: define internal i8* @"\01-[I init]"
+// CHECK: unreachable
+// CHECK-NEXT: }
+
+#pragma clang assume_nonnull begin
+@interface I
+- (instancetype)init __attribute__((unavailable));
+@end
+@implementation I
+- (instancetype)init __attribute__((unavailable)) { __builtin_unreachable(); }
+@end
+#pragma clang assume_nonnull end



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


[clang] a156da5 - [clang/Darwin] Remove __llvm_profile_counter_bias from export list for profiling

2020-01-21 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-01-21T16:52:01-08:00
New Revision: a156da5fb361fd38ba379ec20856626c9e35f829

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

LOG: [clang/Darwin] Remove __llvm_profile_counter_bias from export list for 
profiling

Do not export __llvm_profile_counter_bias when profiling is enabled
because this symbol is hidden and cannot be exported.

Should fix this bot error:

```
URL: http://green.lab.llvm.org/green/job/clang-stage1-RA/5678/consoleFull

Problem: Command Output (stdout):
--
ld: warning: cannot export hidden symbol ___llvm_profile_counter_bias
from
/Users/buildslave/jenkins/workspace/clang-stage1-RA/clang-build/lib/clang/11.0.0/lib/darwin/libclang_rt.profile_osx.a(InstrProfilingBiasVar.c.o)
ld: warning: cannot export hidden symbol ___llvm_profile_counter_bias
from
/Users/buildslave/jenkins/workspace/clang-stage1-RA/clang-build/lib/clang/11.0.0/lib/darwin/libclang_rt.profile_osx.a(InstrProfilingBiasVar.c.o)
```

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index bc2a3e7ef61b..344a14fe1ea7 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1149,7 +1149,6 @@ void Darwin::addProfileRTLibs(const ArgList ,
 } else {
   addExportedSymbol(CmdArgs, "___llvm_profile_filename");
   addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
-  addExportedSymbol(CmdArgs, "___llvm_profile_counter_bias");
 }
 addExportedSymbol(CmdArgs, "_lprofDirMode");
   }



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


Re: [clang] 12038be - [Concepts] Fix crash in D41910

2019-12-18 Thread Vedant Kumar via cfe-commits
I've temporarily reverted the D41910 patchset in order to get the lldb bot 
unstuck (5094e6dad64).

vedant

> On Dec 18, 2019, at 1:34 PM, Vedant Kumar  wrote:
> 
> Hey Saar,
> Do you expect this to address this crash seen on the lldb bot after D41910 
> landed?
> 
> Assertion failed: (Idx < size() && "Out-of-bounds Bit access."), function 
> operator[], file 
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/llvm/include/llvm/ADT/SmallBitVector.h,
>  line 452.
> 
> Stack dump:
> 0.Program arguments: 
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/clang-10 -cc1 
> -triple x86_64-apple-macosx10.14.0 -Wdeprecated-objc-isa-usage 
> -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free 
> -main-file-name main.cpp -mrelocation-model pic -pic-level 2 -mthread-model 
> posix -mframe-pointer=all -fno-rounding-math -masm-verbose -munwind-tables 
> -target-sdk-version=10.14 -target-cpu penryn -dwarf-column-info 
> -debug-info-kind=standalone -dwarf-version=4 -debugger-tuning=lldb 
> -target-linker-version 409.12 -resource-dir 
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lib/clang/10.0.99 
> -isysroot 
> /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk
>  -include 
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/make/test_common.h
>  -I 
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/make/../../../../../include
>  -I 
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant
>  -I 
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/make
>  -D LLDB_USING_LIBCPP -stdlib=libc++ -internal-isystem 
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/../include/c++/v1
>  -internal-isystem 
> /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/c++/v1
>  -internal-isystem 
> /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/local/include
>  -internal-isystem 
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lib/clang/10.0.99/include
>  -internal-externc-isystem 
> /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include
>  -O0 -std=c++17 -fdeprecated-macro -fdebug-compilation-dir 
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lldb-test-build.noindex/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.test_with_run_command_dsym
>  -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fno-builtin -fblocks 
> -fencode-extended-block-signature -fregister-global-dtors-with-atexit 
> -fgnuc-version=4.2.1 -fobjc-runtime=macosx-10.14.0 -fcxx-exceptions 
> -fexceptions -fmax-type-align=16 -fdiagnostics-show-option -o main.o -x c++ 
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp
>  
> 1.
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp:26:39:
>  current parser token ';'
> 2.
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp:20:1:
>  parsing function body 'main'
> 3.
> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp:20:1:
>  in compound statement ('{}')
> 4.
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/../include/c++/v1/variant:1192:13:
>  instantiating function definition 'std::__1::variant char>::variant'
> 5.
> /Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/../include/c++/v1/variant:684:22:
>  instantiating function definition 
> 'std::__1::__variant_detail::__base  int, double, char>::__base<0>'
> 0  clang-10 0x0001077ed1a5 
> llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
> 1  clang-10 0x0001077ec0a8 llvm::sys::RunSignalHandlers() 
> + 248
> 2  clang-10 0x0001077ed796 SignalHandler(int) + 262
> 3  libsystem_platform.dylib 0x7fff66bc3b3d _sigtramp + 29
> 4  libsystem_platform.dylib 0x7ffeea2a2150 _sigtramp + 
> 18446744071619601968
> 5  libsystem_c.dylib0x7fff66a821c9 abort + 127
> 6  libsystem_c.dylib0x7fff66a4a868 basename_r + 0
> 7  clang-10 0x0001094b79d9 
> isAtLeastAsSpecializedAs(clang::Sema&, clang::SourceLocation, 
> clang::FunctionTemplateDecl*, 

Re: [clang] 12038be - [Concepts] Fix crash in D41910

2019-12-18 Thread Vedant Kumar via cfe-commits
Hey Saar,
Do you expect this to address this crash seen on the lldb bot after D41910 
landed?

Assertion failed: (Idx < size() && "Out-of-bounds Bit access."), function 
operator[], file 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/llvm/include/llvm/ADT/SmallBitVector.h,
 line 452.

Stack dump:
0.  Program arguments: 
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/clang-10 -cc1 
-triple x86_64-apple-macosx10.14.0 -Wdeprecated-objc-isa-usage 
-Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free 
-main-file-name main.cpp -mrelocation-model pic -pic-level 2 -mthread-model 
posix -mframe-pointer=all -fno-rounding-math -masm-verbose -munwind-tables 
-target-sdk-version=10.14 -target-cpu penryn -dwarf-column-info 
-debug-info-kind=standalone -dwarf-version=4 -debugger-tuning=lldb 
-target-linker-version 409.12 -resource-dir 
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lib/clang/10.0.99 
-isysroot 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk
 -include 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/make/test_common.h
 -I 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/make/../../../../../include
 -I 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant
 -I 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/make
 -D LLDB_USING_LIBCPP -stdlib=libc++ -internal-isystem 
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/../include/c++/v1 
-internal-isystem 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/c++/v1
 -internal-isystem 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/local/include
 -internal-isystem 
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lib/clang/10.0.99/include
 -internal-externc-isystem 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include
 -O0 -std=c++17 -fdeprecated-macro -fdebug-compilation-dir 
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/lldb-test-build.noindex/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.test_with_run_command_dsym
 -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fno-builtin -fblocks 
-fencode-extended-block-signature -fregister-global-dtors-with-atexit 
-fgnuc-version=4.2.1 -fobjc-runtime=macosx-10.14.0 -fcxx-exceptions 
-fexceptions -fmax-type-align=16 -fdiagnostics-show-option -o main.o -x c++ 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp
 
1.  
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp:26:39:
 current parser token ';'
2.  
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp:20:1:
 parsing function body 'main'
3.  
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp:20:1:
 in compound statement ('{}')
4.  
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/../include/c++/v1/variant:1192:13:
 instantiating function definition 'std::__1::variant::variant'
5.  
/Users/buildslave/jenkins/workspace/lldb-cmake/lldb-build/bin/../include/c++/v1/variant:684:22:
 instantiating function definition 
'std::__1::__variant_detail::__base::__base<0>'
0  clang-10 0x0001077ed1a5 
llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
1  clang-10 0x0001077ec0a8 llvm::sys::RunSignalHandlers() + 
248
2  clang-10 0x0001077ed796 SignalHandler(int) + 262
3  libsystem_platform.dylib 0x7fff66bc3b3d _sigtramp + 29
4  libsystem_platform.dylib 0x7ffeea2a2150 _sigtramp + 18446744071619601968
5  libsystem_c.dylib0x7fff66a821c9 abort + 127
6  libsystem_c.dylib0x7fff66a4a868 basename_r + 0
7  clang-10 0x0001094b79d9 
isAtLeastAsSpecializedAs(clang::Sema&, clang::SourceLocation, 
clang::FunctionTemplateDecl*, clang::FunctionTemplateDecl*, 
clang::TemplatePartialOrderingContext, unsigned int) + 1865
8  clang-10 0x0001094b7111 
clang::Sema::getMoreSpecializedTemplate(clang::FunctionTemplateDecl*, 
clang::FunctionTemplateDecl*, clang::SourceLocation, 
clang::TemplatePartialOrderingContext, unsigned int, unsigned int) + 97
9  clang-10  

Re: [clang] 00bc76e - Move Basic{Reader,Writer} emission into ASTPropsEmitter; NFC.

2019-12-16 Thread Vedant Kumar via cfe-commits
Thanks John, the bot has recovered.

> On Dec 16, 2019, at 1:08 PM, John McCall via cfe-commits 
>  wrote:
> 
> On 16 Dec 2019, at 15:11, John McCall wrote:
>> On 16 Dec 2019, at 15:07, Vedant Kumar wrote:
>>> Hi John,
>>> 
>>> The lldb bot went red after your clang AST changes landed: 
>>> http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake/4801/changes#detail0
>>>  
>>> 
>>> 
>>> All of the test failures were due to a clang assertion:
>>> 
>>> Assertion failed: (isOverloadedOperator() && "Template name isn't an 
>>> overloaded operator?"), function getOperator, file 
>>> /Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/clang/include/clang/AST/TemplateName.h,
>>>  line 520.
>>> 
>>> Perhaps this is related to "Commit a9db0d9f - Use property-based 
>>> serialization for TemplateName"?
>> 
>> Sorry, I’ll take a look.
> 
> Should be fixed in 803403afc83f659be1c620eb1896dcf704b18b0a.
> 
> John.
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

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


Re: [clang] 00bc76e - Move Basic{Reader,Writer} emission into ASTPropsEmitter; NFC.

2019-12-16 Thread Vedant Kumar via cfe-commits
Hi John,

The lldb bot went red after your clang AST changes landed: 
http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake/4801/changes#detail0 


All of the test failures were due to a clang assertion:

Assertion failed: (isOverloadedOperator() && "Template name isn't an overloaded 
operator?"), function getOperator, file 
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/clang/include/clang/AST/TemplateName.h,
 line 520.

Perhaps this is related to "Commit a9db0d9f - Use property-based serialization 
for TemplateName"?

vedant

p.s: I would have responded to that commit email directly, but for some reason 
it isn't in my inbox. Tom, do you know if there have been any issues with 
missing emails lately?

> On Dec 16, 2019, at 10:34 AM, John McCall via cfe-commits 
>  wrote:
> 
> 
> Author: John McCall
> Date: 2019-12-16T13:33:59-05:00
> New Revision: 00bc76edddb5a6cd417610e96289a5dc15245867
> 
> URL: 
> https://github.com/llvm/llvm-project/commit/00bc76edddb5a6cd417610e96289a5dc15245867
> DIFF: 
> https://github.com/llvm/llvm-project/commit/00bc76edddb5a6cd417610e96289a5dc15245867.diff
> 
> LOG: Move Basic{Reader,Writer} emission into ASTPropsEmitter; NFC.
> 
> I'm going to introduce some uses of the property read/write methods.
> 
> Added: 
> 
> 
> Modified: 
>clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
> 
> Removed: 
> 
> 
> 
> 
> diff  --git a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp 
> b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
> index c80b10e538cd..e14b9eb6e6ff 100644
> --- a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
> +++ b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
> @@ -84,6 +84,7 @@ class ASTPropsEmitter {
>   raw_ostream 
>   RecordKeeper 
>   std::map NodeInfos;
> +  std::vector AllPropertyTypes;
> 
> public:
>   ASTPropsEmitter(RecordKeeper , raw_ostream )
> @@ -124,6 +125,15 @@ class ASTPropsEmitter {
>   info.Override = overrideRule;
> }
> 
> +for (PropertyType type :
> +   records.getAllDerivedDefinitions(PropertyTypeClassName)) {
> +  // Ignore generic specializations; they're generally not useful when
> +  // emitting basic emitters etc.
> +  if (type.isGenericSpecialization()) continue;
> +
> +  AllPropertyTypes.push_back(type);
> +}
> +
> Validator(*this).validate();
>   }
> 
> @@ -175,6 +185,11 @@ class ASTPropsEmitter {
>   void emitReadOfProperty(Property property);
>   void emitWriteOfProperty(Property property);
> 
> +  void emitBasicReaderWriterFile(const ReaderWriterInfo );
> +  void emitDispatcherTemplate(const ReaderWriterInfo );
> +  void emitPackUnpackOptionalTemplate(const ReaderWriterInfo );
> +  void emitBasicReaderWriterTemplate(const ReaderWriterInfo );
> +
> private:
>   class Validator {
> const ASTPropsEmitter 
> @@ -477,11 +492,11 @@ void clang::EmitClangTypeWriter(RecordKeeper , 
> raw_ostream ) {
> /*** BASIC READER/WRITERS ***/
> //
> 
> -static void emitDispatcherTemplate(ArrayRef types, raw_ostream ,
> -   const ReaderWriterInfo ) {
> +void
> +ASTPropsEmitter::emitDispatcherTemplate(const ReaderWriterInfo ) {
>   // Declare the {Read,Write}Dispatcher template.
>   StringRef dispatcherPrefix = (info.IsReader ? "Read" : "Write");
> -  out << "template \n"
> +  Out << "template \n"
>  "struct " << dispatcherPrefix << "Dispatcher;\n";
> 
>   // Declare a specific specialization of the dispatcher template.
> @@ -490,10 +505,10 @@ static void emitDispatcherTemplate(ArrayRef 
> types, raw_ostream ,
> const Twine ,
> StringRef methodSuffix) {
> StringRef var = info.HelperVariable;
> -out << "template " << specializationParameters << "\n"
> +Out << "template " << specializationParameters << "\n"
>"struct " << dispatcherPrefix << "Dispatcher<"
>  << cxxTypeName << "> {\n";
> -out << "  template  Args>\n"
> +Out << "  template  Args>\n"
>"  static " << (info.IsReader ? cxxTypeName : "void") << " "
><< info.MethodPrefix
><< "(Basic" << info.ClassSuffix << " &" << var
> @@ -506,7 +521,7 @@ static void emitDispatcherTemplate(ArrayRef 
> types, raw_ostream ,
>   };
> 
>   // Declare explicit specializations for each of the concrete types.
> -  for (PropertyType type : types) {
> +  for (PropertyType type : AllPropertyTypes) {
> declareSpecialization("<>",
>   type.getCXXTypeName(),
>   type.getAbstractTypeName());
> @@ -524,22 +539,21 @@ static void emitDispatcherTemplate(ArrayRef 
> types, raw_ostream ,
>   declareSpecialization("",
>   

[clang] 3e1562e - Debug Info: Strengthen the synthesized-property-cleanup.mm test, NFC

2019-12-10 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-12-10T13:39:22-08:00
New Revision: 3e1562e83339bb1e18fb36a5a2fc629c75f5f239

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

LOG: Debug Info: Strengthen the synthesized-property-cleanup.mm test, NFC

After https://reviews.llvm.org/D71084, the line locations assigned when
emitting cleanups inside of property accessors changed. Update this test
to actually check that those locations are correct.

rdar://57796656

Added: 


Modified: 
clang/test/CodeGenObjCXX/synthesized-property-cleanup.mm

Removed: 




diff  --git a/clang/test/CodeGenObjCXX/synthesized-property-cleanup.mm 
b/clang/test/CodeGenObjCXX/synthesized-property-cleanup.mm
index 805766b23bdb..8740a4c279d7 100644
--- a/clang/test/CodeGenObjCXX/synthesized-property-cleanup.mm
+++ b/clang/test/CodeGenObjCXX/synthesized-property-cleanup.mm
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple arm64e-apple-ios13.0 -debug-info-kind=standalone 
-fobjc-arc \
+// RUN: %clang_cc1 -triple arm64e-apple-ios13.0 -debug-info-kind=standalone 
-fobjc-arc -fsanitize=nullability-return \
 // RUN:   %s -emit-llvm -o - | FileCheck %s
 
 @interface NSObject
@@ -10,16 +10,25 @@ @interface NSString : NSObject
 
 // CHECK: define {{.*}}@"\01-[MyData setData:]"
 // CHECK: [[DATA:%.*]] = alloca %struct.Data
-// CHECK: call %struct.Data* @_ZN4DataD1Ev(%struct.Data* [[DATA]]){{.*}}, !dbg 
[[LOC:![0-9]+]]
+// CHECK: call %struct.Data* @_ZN4DataD1Ev(%struct.Data* [[DATA]]){{.*}}, !dbg 
[[DATA_PROPERTY_LOC:![0-9]+]]
 // CHECK-NEXT: ret void
 
-// [[LOC]] = !DILocation(line: 0
+// CHECK: define {{.*}}@"\01-[MyData string]"
+// CHECK: call void @__ubsan_handle_nullability_return_v1_abort{{.*}}, !dbg 
[[STRING_PROPERTY_LOC:![0-9]+]]
+// CHECK: ret
 
 @interface MyData : NSObject
 struct Data {
 NSString *name;
 };
+
+// CHECK-DAG: [[DATA_PROPERTY_LOC]] = !DILocation(line: [[@LINE+1]]
 @property struct Data data;
+
+// CHECK-DAG: [[STRING_PROPERTY_LOC]] = !DILocation(line: [[@LINE+1]]
+@property (nonnull) NSString *string;
+
 @end
+
 @implementation MyData
 @end



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


[clang] 859bf4d - [Coverage] Emit a gap region to cover switch bodies

2019-12-03 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-12-03T12:35:54-08:00
New Revision: 859bf4d2bea2404bd2eac92451f2db4371ec6eb4

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

LOG: [Coverage] Emit a gap region to cover switch bodies

Emit a gap region beginning where the switch body begins. This sets line
execution counts in the areas between non-overlapping cases to 0.

This also removes some special handling of the first case in a switch:
these are now treated like any other case.

This does not resolve an outstanding issue with case statement regions
that do not end when a region is terminated. But it should address
llvm.org/PR44011.

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

Added: 


Modified: 
clang/docs/SourceBasedCodeCoverage.rst
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/test/CoverageMapping/switch.cpp
clang/test/CoverageMapping/switchmacro.c

Removed: 




diff  --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index 73197a57713f..7e711819be34 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -302,3 +302,37 @@ Drawbacks and limitations
   If the call to ``may_throw()`` propagates an exception into ``f``, the code
   coverage tool may mark the ``return`` statement as executed even though it is
   not. A call to ``longjmp()`` can have similar effects.
+
+Clang implementation details
+
+
+This section may be of interest to those wishing to understand or improve
+the clang code coverage implementation.
+
+Gap regions
+---
+
+Gap regions are source regions with counts. A reporting tool cannot set a line
+execution count to the count from a gap region unless that region is the only
+one on a line.
+
+Gap regions are used to eliminate unnatural artifacts in coverage reports, such
+as red "unexecuted" highlights present at the end of an otherwise covered line,
+or blue "executed" highlights present at the start of a line that is otherwise
+not executed.
+
+Switch statements
+-
+
+The region mapping for a switch body consists of a gap region that covers the
+entire body (starting from the '{' in 'switch (...) {', and terminating where 
the
+last case ends). This gap region has a zero count: this causes "gap" areas in
+between case statements, which contain no executable code, to appear uncovered.
+
+When a switch case is visited, the parent region is extended: if the parent
+region has no start location, its start location becomes the start of the case.
+This is used to support switch statements without a ``CompoundStmt`` body, in
+which the switch body and the single case share a count.
+
+For switches with ``CompoundStmt`` bodies, a new region is created at the start
+of each switch case.

diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 0a7a4fe33ac2..bdecff39c88f 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1114,8 +1114,8 @@ struct CounterCoverageMappingBuilder
 // Make a region for the body of the switch.  If the body starts with
 // a case, that case will reuse this region; otherwise, this covers
 // the unreachable code at the beginning of the switch body.
-size_t Index =
-pushRegion(Counter::getZero(), getStart(CS->body_front()));
+size_t Index = pushRegion(Counter::getZero(), getStart(CS));
+getRegion().setGap(true);
 for (const auto *Child : CS->children())
   Visit(Child);
 

diff  --git a/clang/test/CoverageMapping/switch.cpp 
b/clang/test/CoverageMapping/switch.cpp
index 30c64922201f..25ea4053f4e2 100644
--- a/clang/test/CoverageMapping/switch.cpp
+++ b/clang/test/CoverageMapping/switch.cpp
@@ -2,11 +2,11 @@
 
 // CHECK: foo
 void foo(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+8]]:2 = #0
-  switch(i) {
+  switch(i) {   // CHECK-NEXT: Gap,File 0, [[@LINE]]:13 -> [[@LINE+4]]:10 
= 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = #2
 return;
   case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #3
-break;  // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:3 = #1
+break;  // CHECK-NEXT: Gap,File 0, [[@LINE]]:10 -> [[@LINE+2]]:3 = 
#1
   }
   int x = 0;// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #1
 }
@@ -29,7 +29,7 @@ void bar(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> 
[[@LINE+20]]:2 = #0
 nop();
 
   switch (i) {  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:2 = #4
-nop();  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+2]]:10 = 0
+nop();  // 

[clang] 568db78 - [CGDebugInfo] Emit subprograms for decls when AT_tail_call is understood (reland with fixes)

2019-11-19 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-11-19T12:49:27-08:00
New Revision: 568db780bb7267651a902da8e85bc59fc89aea70

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

LOG: [CGDebugInfo] Emit subprograms for decls when AT_tail_call is understood 
(reland with fixes)

Currently, clang emits subprograms for declared functions when the
target debugger or DWARF standard is known to support entry values
(DW_OP_entry_value & the GNU equivalent).

Treat DW_AT_tail_call the same way to allow debuggers to follow cross-TU
tail calls.

Pre-patch debug session with a cross-TU tail call:

```
  * frame #0: 0x00010fa4 main`target at b.c:4:3 [opt]
frame #1: 0x00010f99 main`main at a.c:8:10 [opt]
```

Post-patch (note that the tail-calling frame, "helper", is visible):

```
  * frame #0: 0x00010fa4 main`target at b.c:4:3 [opt]
frame #1: 0x00010f80 main`helper [opt] [artificial]
frame #2: 0x00010f99 main`main at a.c:8:10 [opt]
```

This was reverted in 5b9a072c because it attached declaration
subprograms to inlinable builtin calls, which interacted badly with the
MergeICmps pass. The fix is to not attach declarations to builtins.

rdar://46577651

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

Added: 


Modified: 
clang/include/clang/Basic/IdentifierTable.h
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeGen/debug-info-extern-call.c
clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
llvm/test/DebugInfo/X86/dwarf-callsite-related-attrs.ll

Removed: 




diff  --git a/clang/include/clang/Basic/IdentifierTable.h 
b/clang/include/clang/Basic/IdentifierTable.h
index 7aa1d074a591..ea5d7adeb2da 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -384,6 +384,17 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
 return getName().startswith("<#") && getName().endswith("#>");
   }
 
+  /// Determine whether \p this is a name reserved for the implementation (C99
+  /// 7.1.3, C++ [lib.global.names]).
+  bool isReservedName(bool doubleUnderscoreOnly = false) const {
+if (getLength() < 2)
+  return false;
+const char *Name = getNameStart();
+return Name[0] == '_' &&
+   (Name[1] == '_' ||
+(Name[1] >= 'A' && Name[1] <= 'Z' && !doubleUnderscoreOnly));
+  }
+
   /// Provide less than operator for lexicographical sorting.
   bool operator<(const IdentifierInfo ) const {
 return getName() < RHS.getName();

diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 75c4b2ae2339..116517a9cb99 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3765,21 +3765,29 @@ void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, 
SourceLocation Loc,
 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
   QualType CalleeType,
   const FunctionDecl *CalleeDecl) {
-  auto  = CGM.getCodeGenOpts();
-  if (!CGOpts.EnableDebugEntryValues || !CGM.getLangOpts().Optimize ||
-  !CallOrInvoke)
+  if (!CallOrInvoke)
 return;
-
   auto *Func = CallOrInvoke->getCalledFunction();
   if (!Func)
 return;
+  if (Func->getSubprogram())
+return;
+
+  // Do not emit a declaration subprogram for a builtin or if call site info
+  // isn't required. Also, elide declarations for functions with reserved 
names,
+  // as call site-related features aren't interesting in this case (& also, the
+  // compiler may emit calls to these functions without debug locations, which
+  // makes the verifier complain).
+  if (CalleeDecl->getBuiltinID() != 0 ||
+  getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
+return;
+  if (const auto *Id = CalleeDecl->getIdentifier())
+if (Id->isReservedName())
+  return;
 
   // If there is no DISubprogram attached to the function being called,
   // create the one describing the function in order to have complete
   // call site debug info.
-  if (Func->getSubprogram())
-return;
-
   if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
 }
@@ -4841,10 +4849,10 @@ llvm::DINode::DIFlags 
CGDebugInfo::getCallSiteRelatedAttrs() const {
   bool SupportsDWARFv4Ext =
   CGM.getCodeGenOpts().DwarfVersion == 4 &&
   (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
-   (CGM.getCodeGenOpts().EnableDebugEntryValues &&
-   CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB));
+   CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
 
-  if (!SupportsDWARFv4Ext 

[clang] ea1db31 - [CodeGen] Assign locations to calls to special struct helpers

2019-11-18 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-11-18T15:07:59-08:00
New Revision: ea1db31d20a74e5025a86b0df49163d5bfecb67b

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

LOG: [CodeGen] Assign locations to calls to special struct helpers

Assign artificial locations to calls to special struct-related helper
functions.

Such calls may not inherit a location if emitted within FinishFunction,
at which point the lexical scope stack may be empty, causing CGDebugInfo
to report the current DebugLoc as empty.

Fixes an IR verifier complaint about a call to '__destructor_8_s0' not
having a !dbg location attached.

rdar://57293361

Added: 


Modified: 
clang/lib/CodeGen/CGNonTrivialStruct.cpp
clang/test/CodeGenObjC/nontrivial-c-struct-exception.m

Removed: 




diff  --git a/clang/lib/CodeGen/CGNonTrivialStruct.cpp 
b/clang/lib/CodeGen/CGNonTrivialStruct.cpp
index 05615aa12881..332e51e57ded 100644
--- a/clang/lib/CodeGen/CGNonTrivialStruct.cpp
+++ b/clang/lib/CodeGen/CGNonTrivialStruct.cpp
@@ -817,6 +817,7 @@ template 
 static void callSpecialFunction(G &, StringRef FuncName, QualType QT,
 bool IsVolatile, CodeGenFunction ,
 std::array Addrs) {
+  auto SetArtificialLoc = ApplyDebugLocation::CreateArtificial(CGF);
   for (unsigned I = 0; I < N; ++I)
 Addrs[I] = CGF.Builder.CreateBitCast(Addrs[I], CGF.CGM.Int8PtrPtrTy);
   QT = IsVolatile ? QT.withVolatile() : QT;

diff  --git a/clang/test/CodeGenObjC/nontrivial-c-struct-exception.m 
b/clang/test/CodeGenObjC/nontrivial-c-struct-exception.m
index 7db53bb74249..1733a019026c 100644
--- a/clang/test/CodeGenObjC/nontrivial-c-struct-exception.m
+++ b/clang/test/CodeGenObjC/nontrivial-c-struct-exception.m
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple arm64-apple-ios11 -fobjc-arc -fblocks 
-fobjc-runtime=ios-11.0 -fobjc-exceptions -fexceptions -emit-llvm -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -triple arm64-apple-ios11 -fobjc-arc -fblocks 
-fobjc-runtime=ios-11.0 -fobjc-exceptions -fexceptions 
-debug-info-kind=line-tables-only -emit-llvm -o - %s | FileCheck %s
 
 // CHECK: %[[STRUCT_STRONG:.*]] = type { i32, i8* }
 // CHECK: %[[STRUCT_WEAK:.*]] = type { i32, i8* }
@@ -25,8 +25,8 @@
 // CHECK-NEXT: ret void
 
 // CHECK: landingpad { i8*, i32 }
-// CHECK: %[[V9:.*]] = bitcast %[[STRUCT_STRONG]]* %[[AGG_TMP]] to i8**
-// CHECK: call void @__destructor_8_s8(i8** %[[V9]])
+// CHECK: %[[V9:.*]] = bitcast %[[STRUCT_STRONG]]* %[[AGG_TMP]] to i8**{{.*}}, 
!dbg [[ARTIFICIAL_LOC_1:![0-9]+]]
+// CHECK: call void @__destructor_8_s8(i8** %[[V9]]){{.*}}, !dbg 
[[ARTIFICIAL_LOC_1]]
 // CHECK: br label
 
 // CHECK: resume
@@ -48,8 +48,8 @@ void testStrongException(void) {
 // CHECK: ret void
 
 // CHECK: landingpad { i8*, i32 }
-// CHECK: %[[V3:.*]] = bitcast %[[STRUCT_WEAK]]* %[[AGG_TMP]] to i8**
-// CHECK: call void @__destructor_8_w8(i8** %[[V3]])
+// CHECK: %[[V3:.*]] = bitcast %[[STRUCT_WEAK]]* %[[AGG_TMP]] to i8**{{.*}}, 
!dbg [[ARTIFICIAL_LOC_2:![0-9]+]]
+// CHECK: call void @__destructor_8_w8(i8** %[[V3]]){{.*}}, !dbg 
[[ARTIFICIAL_LOC_2]]
 // CHECK: br label
 
 // CHECK: resume
@@ -60,3 +60,6 @@ void testStrongException(void) {
 void testWeakException(void) {
   calleeWeak(genWeak(), genWeak());
 }
+
+// CHECK-DAG: [[ARTIFICIAL_LOC_1]] = !DILocation(line: 0
+// CHECK-DAG: [[ARTIFICIAL_LOC_2]] = !DILocation(line: 0



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


[clang] 2492b5a - [profile] Support online merging with continuous sync mode

2019-11-18 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-11-18T12:56:58-08:00
New Revision: 2492b5a12550f7c4bb428c3761392f2ce47fa269

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

LOG: [profile] Support online merging with continuous sync mode

Make it possible to use online profile merging ("%m" mode) with
continuous sync ("%c" mode).

To implement this, the merged profile is locked in the runtime
initialization step and either a) filled out for the first time or b)
checked for compatibility. Then, the profile can simply be mmap()'d with
MAP_SHARED set. With the mmap() in place, counter updates from every
process which uses an image are mapped onto the same set of physical
pages assigned by the filesystem cache. After the mmap() is set up, the
profile is unlocked.

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

Added: 
compiler-rt/test/profile/ContinuousSyncMode/online-merging.c

Modified: 
clang/docs/SourceBasedCodeCoverage.rst
compiler-rt/lib/profile/InstrProfilingBuffer.c
compiler-rt/lib/profile/InstrProfilingFile.c
compiler-rt/lib/profile/InstrProfilingPort.h

Removed: 




diff  --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index 0beb284e475e..73197a57713f 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -90,12 +90,11 @@ directory structure will be created.  Additionally, the 
following special
 * "%c" expands out to nothing, but enables a mode in which profile counter
   updates are continuously synced to a file. This means that if the
   instrumented program crashes, or is killed by a signal, perfect coverage
-  information can still be recovered. Continuous mode is not yet compatible 
with
-  the "%Nm" merging mode described above, does not support value profiling for
-  PGO, and is only supported on Darwin. Support for Linux may be mostly
-  complete but requires testing, and support for Fuchsia/Windows may require
-  more extensive changes: please get involved if you are interested in porting
-  this feature.
+  information can still be recovered. Continuous mode does not support value
+  profiling for PGO, and is only supported on Darwin at the moment. Support for
+  Linux may be mostly complete but requires testing, and support for
+  Fuchsia/Windows may require more extensive changes: please get involved if
+  you are interested in porting this feature.
 
 .. code-block:: console
 

diff  --git a/compiler-rt/lib/profile/InstrProfilingBuffer.c 
b/compiler-rt/lib/profile/InstrProfilingBuffer.c
index 089ff5a0153d..174280fd4b52 100644
--- a/compiler-rt/lib/profile/InstrProfilingBuffer.c
+++ b/compiler-rt/lib/profile/InstrProfilingBuffer.c
@@ -10,11 +10,7 @@
 #include "InstrProfilingInternal.h"
 #include "InstrProfilingPort.h"
 
-/* When continuous mode is enabled (%c), this parameter is set to 1. This is
- * incompatible with the in-process merging mode. Lifting this restriction
- * may be complicated, as merging mode requires a lock on the profile, and
- * mmap() mode would require that lock to be held for the entire process
- * lifetime.
+/* When continuous mode is enabled (%c), this parameter is set to 1.
  *
  * This parameter is defined here in InstrProfilingBuffer.o, instead of in
  * InstrProfilingFile.o, to sequester all libc-dependent code in

diff  --git a/compiler-rt/lib/profile/InstrProfilingFile.c 
b/compiler-rt/lib/profile/InstrProfilingFile.c
index 6594fa991d59..208ae587bb3e 100644
--- a/compiler-rt/lib/profile/InstrProfilingFile.c
+++ b/compiler-rt/lib/profile/InstrProfilingFile.c
@@ -380,11 +380,6 @@ static void truncateCurrentFile(void) {
   if (!Filename)
 return;
 
-  /* By pass file truncation to allow online raw profile
-   * merging. */
-  if (lprofCurFilename.MergePoolSize)
-return;
-
   /* Only create the profile directory and truncate an existing profile once.
* In continuous mode, this is necessary, as the profile is written-to by the
* runtime initializer. */
@@ -397,8 +392,14 @@ static void truncateCurrentFile(void) {
   setenv(LPROF_INIT_ONCE_ENV, LPROF_INIT_ONCE_ENV, 1);
 #endif
 
+  /* Create the profile dir (even if online merging is enabled), so that
+   * the profile file can be set up if continuous mode is enabled. */
   createProfileDir(Filename);
 
+  /* By pass file truncation to allow online raw profile merging. */
+  if (lprofCurFilename.MergePoolSize)
+return;
+
   /* Truncate the file.  Later we'll reopen and append. */
   File = fopen(Filename, "w");
   if (!File)
@@ -406,6 +407,33 @@ static void truncateCurrentFile(void) {
   fclose(File);
 }
 
+#ifndef _MSC_VER
+static void assertIsZero(int *i) {
+  if (*i)
+PROF_WARN("Expected flag to be 0, but got: %d\n", *i);
+}
+#endif
+
+/* Write a partial profile to 

[clang] b95bb08 - [CodeGenModule] Group blocks runtime globals together, NFC

2019-11-07 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-11-07T12:46:26-08:00
New Revision: b95bb0847a1ea366dda69901c24415e0d00a9527

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

LOG: [CodeGenModule] Group blocks runtime globals together, NFC

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.h

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index f5014c05b067..33d419a02903 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -523,18 +523,18 @@ class CodeGenModule : public CodeGenTypeCache {
 int GlobalUniqueCount;
   } Block;
 
+  GlobalDecl initializedGlobalDecl;
+
+  /// @}
+
   /// void @llvm.lifetime.start(i64 %size, i8* nocapture )
   llvm::Function *LifetimeStartFn = nullptr;
 
   /// void @llvm.lifetime.end(i64 %size, i8* nocapture )
   llvm::Function *LifetimeEndFn = nullptr;
 
-  GlobalDecl initializedGlobalDecl;
-
   std::unique_ptr SanitizerMD;
 
-  /// @}
-
   llvm::MapVector DeferredEmptyCoverageMappingDecls;
 
   std::unique_ptr CoverageMapping;



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


[clang] a5c8ec4 - [CGDebugInfo] Emit subprograms for decls when AT_tail_call is understood

2019-11-04 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2019-11-04T15:14:24-08:00
New Revision: a5c8ec4baa2c00d8dbca36ffd236a40f9e0c07ed

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

LOG: [CGDebugInfo] Emit subprograms for decls when AT_tail_call is understood

Currently, clang emits subprograms for declared functions when the
target debugger or DWARF standard is known to support entry values
(DW_OP_entry_value & the GNU equivalent).

Treat DW_AT_tail_call the same way to allow debuggers to follow cross-TU
tail calls.

Pre-patch debug session with a cross-TU tail call:

```
  * frame #0: 0x00010fa4 main`target at b.c:4:3 [opt]
frame #1: 0x00010f99 main`main at a.c:8:10 [opt]
```

Post-patch (note that the tail-calling frame, "helper", is visible):

```
  * frame #0: 0x00010fa4 main`target at b.c:4:3 [opt]
frame #1: 0x00010f80 main`helper [opt] [artificial]
frame #2: 0x00010f99 main`main at a.c:8:10 [opt]
```

rdar://46577651

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

Added: 


Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/test/CodeGen/debug-info-extern-call.c
clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
llvm/test/DebugInfo/X86/dwarf-callsite-related-attrs.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index e0bb3fda7acf..c0c8fd3c8f16 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3748,9 +3748,7 @@ void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, 
SourceLocation Loc,
 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
   QualType CalleeType,
   const FunctionDecl *CalleeDecl) {
-  auto  = CGM.getCodeGenOpts();
-  if (!CGOpts.EnableDebugEntryValues || !CGM.getLangOpts().Optimize ||
-  !CallOrInvoke)
+  if (!CallOrInvoke || getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
 return;
 
   auto *Func = CallOrInvoke->getCalledFunction();
@@ -4824,10 +4822,10 @@ llvm::DINode::DIFlags 
CGDebugInfo::getCallSiteRelatedAttrs() const {
   bool SupportsDWARFv4Ext =
   CGM.getCodeGenOpts().DwarfVersion == 4 &&
   (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
-   (CGM.getCodeGenOpts().EnableDebugEntryValues &&
-   CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB));
+   CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
 
-  if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
+  if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5 &&
+  !CGM.getCodeGenOpts().EnableDebugEntryValues)
 return llvm::DINode::FlagZero;
 
   return llvm::DINode::FlagAllCallsDescribed;

diff  --git a/clang/test/CodeGen/debug-info-extern-call.c 
b/clang/test/CodeGen/debug-info-extern-call.c
index e35669b78f93..7f58fe59a635 100644
--- a/clang/test/CodeGen/debug-info-extern-call.c
+++ b/clang/test/CodeGen/debug-info-extern-call.c
@@ -1,8 +1,21 @@
-// RUN: %clang -Xclang -femit-debug-entry-values -g -O2 -target 
x86_64-none-linux-gnu -S -emit-llvm %s -o - | FileCheck %s 
-check-prefix=CHECK-EXT
-// CHECK-EXT: !DISubprogram(name: "fn1"
+// 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.
+//
+// RUN: %clang -Xclang -femit-debug-entry-values -g -O2 -target 
x86_64-none-linux-gnu -S -emit-llvm %s -o - | FileCheck %s 
-check-prefix=ENTRY-VAL
+// ENTRY-VAL: !DISubprogram(name: "fn1"
 
-// RUN: %clang -g -O2 -target x86_64-none-linux-gnu -S -emit-llvm %s -o - | 
FileCheck %s
-// CHECK-NOT: !DISubprogram(name: "fn1"
+// Similarly, when the debugger tuning is gdb, expect a subprogram for extern
+// decls so that the dwarf generator can describe information needed for tail
+// call frame reconstrution.
+//
+// RUN: %clang -g -O2 -target x86_64-none-linux-gnu -ggdb -S -emit-llvm %s -o 
- | FileCheck %s -check-prefix=GDB
+// GDB: !DISubprogram(name: "fn1"
+//
+// Do not emit a subprogram for extern decls when entry values are disabled and
+// the tuning is not set to gdb.
+//
+// RUN: %clang -g -O2 -target x86_64-none-linux-gnu -gsce -S -emit-llvm %s -o 
- | FileCheck %s -check-prefix=SCE
+// SCE-NOT: !DISubprogram(name: "fn1"
 
 extern int fn1(int a, int b);
 

diff  --git a/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp 
b/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
index 1cb2b6c609f3..667c2469b55e 100644
--- a/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
+++ b/clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
@@ -56,6 +56,7 @@
 
 // NO-ATTR-NOT: FlagAllCallsDescribed
 
+// HAS-ATTR-DAG: 

r375301 - [profile] Do not cache __llvm_profile_get_filename result

2019-10-18 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Oct 18 16:33:40 2019
New Revision: 375301

URL: http://llvm.org/viewvc/llvm-project?rev=375301=rev
Log:
[profile] Do not cache __llvm_profile_get_filename result

When the %m filename pattern is used, the filename is unique to each
image, so the cached value is wrong.

It struck me that the full filename isn't something that's recomputed
often, so perhaps it doesn't need to be cached at all. David Li pointed
out we can go further and just hide lprofCurFilename. This may regress
workflows that depend on using the set-filename API to change filenames
across all loaded DSOs, but this is expected to be very rare.

rdar://55137071

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/test/Driver/darwin-ld.c

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=375301=375300=375301=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Fri Oct 18 16:33:40 2019
@@ -1128,7 +1128,6 @@ void Darwin::addProfileRTLibs(const ArgL
 } else {
   addExportedSymbol(CmdArgs, "___llvm_profile_filename");
   addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
-  addExportedSymbol(CmdArgs, "_lprofCurFilename");
 }
 addExportedSymbol(CmdArgs, "_lprofDirMode");
   }

Modified: cfe/trunk/test/Driver/darwin-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/darwin-ld.c?rev=375301=375300=375301=diff
==
--- cfe/trunk/test/Driver/darwin-ld.c (original)
+++ cfe/trunk/test/Driver/darwin-ld.c Fri Oct 18 16:33:40 2019
@@ -355,7 +355,7 @@
 // RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate -Xlinker 
-exported_symbols_list -Xlinker /dev/null -### %t.o 2> %t.log
 // RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
-// PROFILE_EXPORT: "-exported_symbol" "___llvm_profile_filename" 
"-exported_symbol" "___llvm_profile_raw_version" "-exported_symbol" 
"_lprofCurFilename"
+// PROFILE_EXPORT: "-exported_symbol" "___llvm_profile_filename" 
"-exported_symbol" "___llvm_profile_raw_version"
 //
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate 
--coverage -### %t.o 2> %t.log
 // RUN: FileCheck -check-prefix=NO_PROFILE_EXPORT %s < %t.log


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


r372903 - [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Sep 25 11:00:31 2019
New Revision: 372903

URL: http://llvm.org/viewvc/llvm-project?rev=372903=rev
Log:
[Mangle] Add flag to asm labels to disable '\01' prefixing

LLDB synthesizes decls using asm labels. These decls cannot have a mangle
different than the one specified in the label name. I.e., the '\01' prefix
should not be added.

Fixes an expression evaluation failure in lldb's TestVirtual.py on iOS.

rdar://45827323

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

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/lib/AST/Mangle.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/unittests/AST/DeclTest.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=372903=372902=372903=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed Sep 25 11:00:31 2019
@@ -722,9 +722,25 @@ def AVRSignal : InheritableAttr, TargetS
 
 def AsmLabel : InheritableAttr {
   let Spellings = [Keyword<"asm">, Keyword<"__asm__">];
-  let Args = [StringArgument<"Label">];
+  let Args = [
+// Label specifies the mangled name for the decl.
+StringArgument<"Label">,
+
+// IsLiteralLabel specifies whether the label is literal (i.e. suppresses
+// the global C symbol prefix) or not. If not, the mangle-suppression 
prefix
+// ('\01') is omitted from the decl name at the LLVM IR level.
+//
+// Non-literal labels are used by some external AST sources like LLDB.
+BoolArgument<"IsLiteralLabel", /*optional=*/0, /*fake=*/1>
+  ];
   let SemaHandler = 0;
-  let Documentation = [Undocumented];
+  let Documentation = [AsmLabelDocs];
+  let AdditionalMembers =
+[{
+bool isEquivalent(AsmLabelAttr *Other) const {
+  return getLabel() == Other->getLabel() && getIsLiteralLabel() == 
Other->getIsLiteralLabel();
+}
+}];
 }
 
 def Availability : InheritableAttr {

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=372903=372902=372903=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Wed Sep 25 11:00:31 2019
@@ -2558,6 +2558,30 @@ manipulating bits of the enumerator when
   }];
 }
 
+def AsmLabelDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+This attribute can be used on a function or variable to specify its symbol 
name.
+
+On some targets, all C symbols are prefixed by default with a single 
character, typically ``_``.  This was done historically to distinguish them 
from symbols used by other languages.  (This prefix is also added to the 
standard Itanium C++ ABI prefix on "mangled" symbol names, so that e.g. on such 
targets the true symbol name for a C++ variable declared as ``int cppvar;`` 
would be ``__Z6cppvar``; note the two underscores.)  This prefix is *not* added 
to the symbol names specified by the ``asm`` attribute; programmers wishing to 
match a C symbol name must compensate for this.
+
+For example, consider the following C code:
+
+.. code-block:: c
+
+  int var1 asm("altvar") = 1;  // "altvar" in symbol table.
+  int var2 = 1; // "_var2" in symbol table.
+
+  void func1(void) asm("altfunc");
+  void func1(void) {} // "altfunc" in symbol table.
+  void func2(void) {} // "_func2" in symbol table.
+
+Clang's implementation of this attribute is compatible with GCC's, `documented 
here `_.
+
+While it is possible to use this attribute to name a special symbol used 
internally by the compiler, such as an LLVM intrinsic, this is neither 
recommended nor supported and may cause the compiler to crash or miscompile.  
Users who wish to gain access to intrinsic behavior are strongly encouraged to 
request new builtin functions.
+  }];
+}
+
 def EnumExtensibilityDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{

Modified: cfe/trunk/lib/AST/Mangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Mangle.cpp?rev=372903=372902=372903=diff
==
--- cfe/trunk/lib/AST/Mangle.cpp (original)
+++ cfe/trunk/lib/AST/Mangle.cpp Wed Sep 25 11:00:31 2019
@@ -122,15 +122,21 @@ void MangleContext::mangleName(const Nam
   if (const AsmLabelAttr *ALA = D->getAttr()) {
 // If we have an asm name, then we use it as the mangling.
 
+// If the label isn't literal, or if this is an alias for an LLVM 
intrinsic,
+// do not add a "\01" prefix.
+if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) {
+  Out << ALA->getLabel();
+  return;
+}
+
 // Adding the prefix can cause problems 

r369964 - [DebugInfo] Add debug-entry-values test coverage, NFC

2019-08-26 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Aug 26 13:50:54 2019
New Revision: 369964

URL: http://llvm.org/viewvc/llvm-project?rev=369964=rev
Log:
[DebugInfo] Add debug-entry-values test coverage, NFC

Check that call site descriptions are emitted in dwarf4 + lldb +
debug-entry-values mode.

Modified:
cfe/trunk/test/CodeGenCXX/dbg-info-all-calls-described.cpp

Modified: cfe/trunk/test/CodeGenCXX/dbg-info-all-calls-described.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dbg-info-all-calls-described.cpp?rev=369964=369963=369964=diff
==
--- cfe/trunk/test/CodeGenCXX/dbg-info-all-calls-described.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/dbg-info-all-calls-described.cpp Mon Aug 26 
13:50:54 2019
@@ -22,6 +22,13 @@
 // RUN: | FileCheck %s -check-prefix=HAS-ATTR \
 // RUN: -implicit-check-not=DIFlagAllCallsDescribed
 
+// Supported: DWARF4 + LLDB tuning by using '-femit-debug-entry-values'
+// RUN: %clang_cc1 -femit-debug-entry-values -emit-llvm -triple 
x86_64-linux-gnu \
+// RUN:   %s -o - -O1 -disable-llvm-passes -debugger-tuning=lldb \
+// RUN:   -debug-info-kind=standalone -dwarf-version=4 \
+// RUN: | FileCheck %s -check-prefix=HAS-ATTR \
+// RUN: -implicit-check-not=DIFlagAllCallsDescribed
+
 // Unsupported: -O0 + '-femit-debug-entry-values'
 // RUN: %clang_cc1 -femit-debug-entry-values -emit-llvm -triple 
x86_64-linux-gnu \
 // RUN:   %s -o - -O0 -disable-llvm-passes -debugger-tuning=gdb \


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


r367270 - [docs] Add a note about where UBSan emits logs

2019-07-29 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Jul 29 15:54:43 2019
New Revision: 367270

URL: http://llvm.org/viewvc/llvm-project?rev=367270=rev
Log:
[docs] Add a note about where UBSan emits logs

Modified:
cfe/trunk/docs/UndefinedBehaviorSanitizer.rst

Modified: cfe/trunk/docs/UndefinedBehaviorSanitizer.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/UndefinedBehaviorSanitizer.rst?rev=367270=367269=367270=diff
==
--- cfe/trunk/docs/UndefinedBehaviorSanitizer.rst (original)
+++ cfe/trunk/docs/UndefinedBehaviorSanitizer.rst Mon Jul 29 15:54:43 2019
@@ -224,6 +224,12 @@ will need to:
``UBSAN_OPTIONS=print_stacktrace=1``.
 #. Make sure ``llvm-symbolizer`` binary is in ``PATH``.
 
+Logging
+===
+
+The default log file for diagnostics is "stderr". To log diagnostics to another
+file, you can set ``UBSAN_OPTIONS=log_path=...``.
+
 Silencing Unsigned Integer Overflow
 ===
 To silence reports from unsigned integer overflow, you can set


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


r367269 - [DebugInfo] Don't emit incorrect descriptions of thunk params (PR42627)

2019-07-29 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Jul 29 15:49:55 2019
New Revision: 367269

URL: http://llvm.org/viewvc/llvm-project?rev=367269=rev
Log:
[DebugInfo] Don't emit incorrect descriptions of thunk params (PR42627)

The `this` parameter of a thunk requires adjustment. Stop emitting an
incorrect dbg.declare pointing to the unadjusted pointer.

We could describe the adjusted value instead, but there may not be much
benefit in doing so as users tend not to debug thunks.

Robert O'Callahan reports that this matches gcc's behavior.

Fixes PR42627.

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

Modified:
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/test/CodeGenCXX/thunks.cpp

Modified: cfe/trunk/lib/CodeGen/CGDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDecl.cpp?rev=367269=367268=367269=diff
==
--- cfe/trunk/lib/CodeGen/CGDecl.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDecl.cpp Mon Jul 29 15:49:55 2019
@@ -2496,10 +2496,11 @@ void CodeGenFunction::EmitParmDecl(const
 
   setAddrOfLocalVar(, DeclPtr);
 
-  // Emit debug info for param declaration.
+  // Emit debug info for param declarations in non-thunk functions.
   if (CGDebugInfo *DI = getDebugInfo()) {
 if (CGM.getCodeGenOpts().getDebugInfo() >=
-codegenoptions::LimitedDebugInfo) {
+codegenoptions::LimitedDebugInfo &&
+!CurFuncIsThunk) {
   DI->EmitDeclareOfArgVariable(, DeclPtr.getPointer(), ArgNo, Builder);
 }
   }

Modified: cfe/trunk/test/CodeGenCXX/thunks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/thunks.cpp?rev=367269=367268=367269=diff
==
--- cfe/trunk/test/CodeGenCXX/thunks.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/thunks.cpp Mon Jul 29 15:49:55 2019
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -triple=x86_64-pc-linux-gnu -munwind-tables -emit-llvm 
-o - | FileCheck --check-prefix=CHECK --check-prefix=CHECK-NONOPT %s
+// RUN: %clang_cc1 %s -triple=x86_64-pc-linux-gnu -debug-info-kind=standalone 
-dwarf-version=5 -munwind-tables -emit-llvm -o - | FileCheck 
--check-prefix=CHECK --check-prefix=CHECK-NONOPT --check-prefix=CHECK-DBG %s
 // RUN: %clang_cc1 %s -triple=x86_64-pc-linux-gnu -munwind-tables -emit-llvm 
-o - -O1 -disable-llvm-passes | FileCheck --check-prefix=CHECK 
--check-prefix=CHECK-OPT %s
 
 namespace Test1 {
@@ -20,6 +21,8 @@ struct C : A, B {
 };
 
 // CHECK-LABEL: define void @_ZThn8_N5Test11C1fEv(
+// CHECK-DBG-NOT: dbg.declare
+// CHECK: ret void
 void C::f() { }
 
 }
@@ -38,6 +41,8 @@ struct B : virtual A {
 };
 
 // CHECK-LABEL: define void @_ZTv0_n24_N5Test21B1fEv(
+// CHECK-DBG-NOT: dbg.declare
+// CHECK: ret void
 void B::f() { }
 
 }
@@ -83,6 +88,8 @@ struct __attribute__((visibility("protec
 };
 
 // CHECK-LABEL: define protected void @_ZThn8_N5Test41C1fEv(
+// CHECK-DBG-NOT: dbg.declare
+// CHECK: ret void
 void C::f() { }
 
 }
@@ -166,6 +173,7 @@ namespace Test6 {
   };
 
   // CHECK-LABEL: define void @_ZThn16_N5Test66Thunks1fEv
+   // CHECK-DBG-NOT: dbg.declare
   // CHECK-NOT: memcpy
   // CHECK: {{call void @_ZN5Test66Thunks1fEv.*sret}}
   // CHECK: ret void
@@ -212,6 +220,7 @@ namespace Test7 {
   void D::baz(X, X&, _Complex float, Small, Small&, Large) { }
 
   // CHECK-LABEL: define void 
@_ZThn8_N5Test71D3bazENS_1XERS1_CfNS_5SmallERS4_NS_5LargeE(
+  // CHECK-DBG-NOT: dbg.declare
   // CHECK-NOT: memcpy
   // CHECK: ret void
   void testD() { D d; }
@@ -227,6 +236,7 @@ namespace Test8 {
   void C::helper(NonPOD var) {}
 
   // CHECK-LABEL: define void @_ZThn8_N5Test81C3barENS_6NonPODE(
+  // CHECK-DBG-NOT: dbg.declare
   // CHECK-NOT: load [[NONPODTYPE]], [[NONPODTYPE]]*
   // CHECK-NOT: memcpy
   // CHECK: ret void
@@ -269,10 +279,14 @@ namespace Test11 {
   //  The this-adjustment and return-adjustment thunk required when
   //  C::f appears in a vtable where A is at a nonzero offset from C.
   // CHECK: define {{.*}} @_ZTcv0_n24_v0_n32_N6Test111C1fEv(
+  // CHECK-DBG-NOT: dbg.declare
+  // CHECK: ret
 
   //  The return-adjustment thunk required when C::f appears in a vtable
   //  where A is at a zero offset from C.
   // CHECK: define {{.*}} @_ZTch0_v0_n32_N6Test111C1fEv(
+  // CHECK-DBG-NOT: dbg.declare
+  // CHECK: ret
 }
 
 // Varargs thunk test.
@@ -295,6 +309,7 @@ namespace Test12 {
   // Varargs thunk; check that both the this and covariant adjustments
   // are generated.
   // CHECK: define {{.*}} @_ZTchn8_h8_N6Test121C1fEiz
+  // CHECK-DBG-NOT: dbg.declare
   // CHECK: getelementptr inbounds i8, i8* {{.*}}, i64 -8
   // CHECK: getelementptr inbounds i8, i8* {{.*}}, i64 8
 }
@@ -318,6 +333,7 @@ namespace Test13 {
 return *this;
   }
   // CHECK: define {{.*}} @_ZTcvn8_n32_v8_n24_N6Test131D4foo1Ev
+  // CHECK-DBG-NOT: dbg.declare
   // CHECK: getelementptr inbounds i8, i8* {{.*}}, i64 -8
   // CHECK: getelementptr inbounds i8, i8* {{.*}}, i64 -32
   // 

r366744 - [Driver] Set the default win32-macho debug format to DWARF

2019-07-22 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Jul 22 14:46:45 2019
New Revision: 366744

URL: http://llvm.org/viewvc/llvm-project?rev=366744=rev
Log:
[Driver] Set the default win32-macho debug format to DWARF

rdar://53267670

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

Modified:
cfe/trunk/lib/Driver/ToolChains/MSVC.h
cfe/trunk/test/Misc/win32-macho.c

Modified: cfe/trunk/lib/Driver/ToolChains/MSVC.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/MSVC.h?rev=366744=366743=366744=diff
==
--- cfe/trunk/lib/Driver/ToolChains/MSVC.h (original)
+++ cfe/trunk/lib/Driver/ToolChains/MSVC.h Mon Jul 22 14:46:45 2019
@@ -78,10 +78,12 @@ public:
   bool isPIEDefault() const override;
   bool isPICDefaultForced() const override;
 
-  /// Set CodeView as the default debug info format. Users can use -gcodeview
-  /// and -gdwarf to override the default.
+  /// Set CodeView as the default debug info format for non-MachO binary
+  /// formats, and to DWARF otherwise. Users can use -gcodeview and -gdwarf to
+  /// override the default.
   codegenoptions::DebugInfoFormat getDefaultDebugFormat() const override {
-return codegenoptions::DIF_CodeView;
+return getTriple().isOSBinFormatMachO() ? codegenoptions::DIF_DWARF
+: codegenoptions::DIF_CodeView;
   }
 
   /// Set the debugger tuning to "default", since we're definitely not tuning

Modified: cfe/trunk/test/Misc/win32-macho.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Misc/win32-macho.c?rev=366744=366743=366744=diff
==
--- cfe/trunk/test/Misc/win32-macho.c (original)
+++ cfe/trunk/test/Misc/win32-macho.c Mon Jul 22 14:46:45 2019
@@ -1,2 +1,5 @@
 // Check that basic use of win32-macho targets works.
 // RUN: %clang -fsyntax-only -target x86_64-pc-win32-macho %s
+
+// RUN: %clang -fsyntax-only -target x86_64-pc-win32-macho -g %s -### 2>&1 | 
FileCheck %s -check-prefix=DEBUG-INFO
+// DEBUG-INFO: -dwarf-version={{.*}}


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


r365814 - Revert "[CGDebugInfo] Simplify EmitFunctionDecl parameters, NFC"

2019-07-11 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Jul 11 12:28:07 2019
New Revision: 365814

URL: http://llvm.org/viewvc/llvm-project?rev=365814=rev
Log:
Revert "[CGDebugInfo] Simplify EmitFunctionDecl parameters, NFC"

This reverts commit 1af41074445229fea66b99710a850e5f42ecfa95.

Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.h

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=365814=365813=365814=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Thu Jul 11 12:28:07 2019
@@ -3621,19 +3621,18 @@ void CGDebugInfo::EmitFunctionStart(Glob
 RegionMap[D].reset(SP);
 }
 
-llvm::DISubprogram *CGDebugInfo::EmitFunctionDecl(GlobalDecl GD,
-  SourceLocation Loc,
-  QualType FnType,
-  bool IsDeclForCallSite) {
+void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
+   QualType FnType, llvm::Function *Fn) {
   StringRef Name;
   StringRef LinkageName;
 
   const Decl *D = GD.getDecl();
   if (!D)
-return nullptr;
+return;
 
   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
   llvm::DIFile *Unit = getOrCreateFile(Loc);
+  bool IsDeclForCallSite = Fn ? true : false;
   llvm::DIScope *FDContext =
   IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
   llvm::DINodeArray TParamsArray;
@@ -3666,8 +3665,11 @@ llvm::DISubprogram *CGDebugInfo::EmitFun
   FDContext, Name, LinkageName, Unit, LineNo,
   getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
   TParamsArray.get(), getFunctionDeclaration(D));
+
+  if (IsDeclForCallSite)
+Fn->setSubprogram(SP);
+
   DBuilder.retainType(SP);
-  return SP;
 }
 
 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
@@ -3689,13 +3691,8 @@ void CGDebugInfo::EmitFuncDeclForCallSit
   if (Func->getSubprogram())
 return;
 
-  if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) {
-llvm::DISubprogram *SP =
-EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType,
- /*IsDeclForCallSite=*/true);
-assert(SP && "Could not find decl for callee?");
-Func->setSubprogram(SP);
-  }
+  if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
+EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
 }
 
 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy , GlobalDecl GD) 
{

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.h?rev=365814=365813=365814=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.h (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.h Thu Jul 11 12:28:07 2019
@@ -408,11 +408,10 @@ public:
   /// End an inlined function scope.
   void EmitInlineFunctionEnd(CGBuilderTy );
 
-  /// Emit debug info for a function declaration. Set \p IsDeclForCallSite if
-  /// a call site entry must reference the declaration.
-  llvm::DISubprogram *EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
-   QualType FnType,
-   bool IsDeclForCallSite = false);
+  /// Emit debug info for a function declaration.
+  /// \p Fn is set only when a declaration for a debug call site gets created.
+  void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
+QualType FnType, llvm::Function *Fn = nullptr);
 
   /// Emit debug info for an extern function being called.
   /// This is needed for call site debug info.


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


r365809 - [CGDebugInfo] Simplify EmitFunctionDecl parameters, NFC

2019-07-11 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Jul 11 12:11:46 2019
New Revision: 365809

URL: http://llvm.org/viewvc/llvm-project?rev=365809=rev
Log:
[CGDebugInfo] Simplify EmitFunctionDecl parameters, NFC

Replace a `llvm::Function *` parameter with a bool, which seems harder
to set to the wrong value by accident.

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

Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.h

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=365809=365808=365809=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Thu Jul 11 12:11:46 2019
@@ -3621,18 +3621,19 @@ void CGDebugInfo::EmitFunctionStart(Glob
 RegionMap[D].reset(SP);
 }
 
-void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
-   QualType FnType, llvm::Function *Fn) {
+llvm::DISubprogram *CGDebugInfo::EmitFunctionDecl(GlobalDecl GD,
+  SourceLocation Loc,
+  QualType FnType,
+  bool IsDeclForCallSite) {
   StringRef Name;
   StringRef LinkageName;
 
   const Decl *D = GD.getDecl();
   if (!D)
-return;
+return nullptr;
 
   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
   llvm::DIFile *Unit = getOrCreateFile(Loc);
-  bool IsDeclForCallSite = Fn ? true : false;
   llvm::DIScope *FDContext =
   IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
   llvm::DINodeArray TParamsArray;
@@ -3665,11 +3666,8 @@ void CGDebugInfo::EmitFunctionDecl(Globa
   FDContext, Name, LinkageName, Unit, LineNo,
   getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
   TParamsArray.get(), getFunctionDeclaration(D));
-
-  if (IsDeclForCallSite)
-Fn->setSubprogram(SP);
-
   DBuilder.retainType(SP);
+  return SP;
 }
 
 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
@@ -3691,8 +3689,13 @@ void CGDebugInfo::EmitFuncDeclForCallSit
   if (Func->getSubprogram())
 return;
 
-  if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
-EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
+  if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) {
+llvm::DISubprogram *SP =
+EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType,
+ /*IsDeclForCallSite=*/true);
+assert(SP && "Could not find decl for callee?");
+Func->setSubprogram(SP);
+  }
 }
 
 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy , GlobalDecl GD) 
{

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.h?rev=365809=365808=365809=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.h (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.h Thu Jul 11 12:11:46 2019
@@ -408,10 +408,11 @@ public:
   /// End an inlined function scope.
   void EmitInlineFunctionEnd(CGBuilderTy );
 
-  /// Emit debug info for a function declaration.
-  /// \p Fn is set only when a declaration for a debug call site gets created.
-  void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
-QualType FnType, llvm::Function *Fn = nullptr);
+  /// Emit debug info for a function declaration. Set \p IsDeclForCallSite if
+  /// a call site entry must reference the declaration.
+  llvm::DISubprogram *EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
+   QualType FnType,
+   bool IsDeclForCallSite = false);
 
   /// Emit debug info for an extern function being called.
   /// This is needed for call site debug info.


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


Re: r364424 - [clang/DIVar] Emit the flag for params that have unmodified value

2019-07-10 Thread Vedant Kumar via cfe-commits
Hi Djordje,

Just a heads-up that I’ve landed r365716 to fix a crash in a stage2 build of 
AppleClang with -femit-debug-entry-values enabled.

I went ahead and landed the fix as it seemed simple enough. Let me know if you 
have any concerns.

Thanks,
Vedant

> On Jun 26, 2019, at 6:32 AM, Djordje Todorovic via cfe-commits 
>  wrote:
> 
> Author: djtodoro
> Date: Wed Jun 26 06:32:02 2019
> New Revision: 364424
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=364424=rev
> Log:
> [clang/DIVar] Emit the flag for params that have unmodified value
> 
> Emit the debug info flag that indicates that a parameter has unchanged
> value throughout a function.
> 
> ([5/13] Introduce the debug entry values.)
> 
> Co-authored-by: Ananth Sowda 
> Co-authored-by: Nikola Prica 
> Co-authored-by: Ivan Baev 
> 
> Differential Revision: https://reviews.llvm.org/D58035
> 
> Added:
>cfe/trunk/test/CodeGen/debug-info-param-modification.c
> Modified:
>cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
>cfe/trunk/lib/CodeGen/CGDebugInfo.h
> 
> Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=364424=364423=364424=diff
> ==
> --- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Wed Jun 26 06:32:02 2019
> @@ -18,6 +18,7 @@
> #include "CodeGenFunction.h"
> #include "CodeGenModule.h"
> #include "ConstantEmitter.h"
> +#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
> #include "clang/AST/ASTContext.h"
> #include "clang/AST/DeclFriend.h"
> #include "clang/AST/DeclObjC.h"
> @@ -3588,6 +3589,12 @@ void CGDebugInfo::EmitFunctionStart(Glob
>   if (HasDecl && isa(D))
> DeclCache[D->getCanonicalDecl()].reset(SP);
> 
> +  // We use the SPDefCache only in the case when the debug entry values 
> option
> +  // is set, in order to speed up parameters modification analysis.
> +  if (CGM.getCodeGenOpts().EnableDebugEntryValues && HasDecl &&
> +  isa(D))
> +SPDefCache[cast(D)].reset(SP);
> +
>   if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
> // Starting with DWARF V5 method declarations are emitted as children of
> // the interface type.
> @@ -3964,6 +3971,11 @@ llvm::DILocalVariable *CGDebugInfo::Emit
>  llvm::DebugLoc::get(Line, Column, Scope, 
> CurInlinedAt),
>  Builder.GetInsertBlock());
> 
> +  if (CGM.getCodeGenOpts().EnableDebugEntryValues && ArgNo) {
> +if (auto *PD = dyn_cast(VD))
> +  ParamCache[PD].reset(D);
> +  }
> +
>   return D;
> }
> 
> @@ -4555,6 +4567,29 @@ void CGDebugInfo::setDwoId(uint64_t Sign
>   TheCU->setDWOId(Signature);
> }
> 
> +/// Analyzes each function parameter to determine whether it is constant
> +/// throughout the function body.
> +static void analyzeParametersModification(
> +ASTContext ,
> +llvm::DenseMap ,
> +llvm::DenseMap ) {
> +  for (auto  : SPDefCache) {
> +auto *FD = SP.first;
> +assert(FD->hasBody() && "Functions must have body here");
> +const Stmt *FuncBody = (*FD).getBody();
> +for (auto Parm : FD->parameters()) {
> +  ExprMutationAnalyzer FuncAnalyzer(*FuncBody, Ctx);
> +  if (FuncAnalyzer.isMutated(Parm))
> +continue;
> +
> +  auto I = ParamCache.find(Parm);
> +  assert(I != ParamCache.end() && "Parameters should be already cached");
> +  auto *DIParm = cast(I->second);
> +  DIParm->setIsNotModified();
> +}
> +  }
> +}
> +
> void CGDebugInfo::finalize() {
>   // Creating types might create further types - invalidating the current
>   // element and the size(), so don't cache/reference them.
> @@ -4627,6 +4662,10 @@ void CGDebugInfo::finalize() {
> if (auto MD = TypeCache[RT])
>   DBuilder.retainType(cast(MD));
> 
> +  if (CGM.getCodeGenOpts().EnableDebugEntryValues)
> +// This will be used to emit debug entry values.
> +analyzeParametersModification(CGM.getContext(), SPDefCache, ParamCache);
> +
>   DBuilder.finalize();
> }
> 
> 
> Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.h?rev=364424=364423=364424=diff
> ==
> --- cfe/trunk/lib/CodeGen/CGDebugInfo.h (original)
> +++ cfe/trunk/lib/CodeGen/CGDebugInfo.h Wed Jun 26 06:32:02 2019
> @@ -134,6 +134,10 @@ class CGDebugInfo {
> 
>   llvm::DenseMap DIFileCache;
>   llvm::DenseMap SPCache;
> +  /// Cache function definitions relevant to use for parameters mutation
> +  /// analysis.
> +  llvm::DenseMap SPDefCache;
> +  llvm::DenseMap ParamCache;
>   /// Cache declarations relevant to DW_TAG_imported_declarations (C++
>   /// using declarations) that aren't covered by other more specific caches.
>   llvm::DenseMap DeclCache;
> 
> Added: cfe/trunk/test/CodeGen/debug-info-param-modification.c
> URL: 
> 

r365716 - [CGDebugInfo] Fix -femit-debug-entry-values crash on os_log_helpers

2019-07-10 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Jul 10 17:09:16 2019
New Revision: 365716

URL: http://llvm.org/viewvc/llvm-project?rev=365716=rev
Log:
[CGDebugInfo] Fix -femit-debug-entry-values crash on os_log_helpers

An os_log_helper FunctionDecl may not have a body. Ignore these for the
purposes of debug entry value emission.

Fixes an assertion failure seen in a stage2 build of clang:

Assertion failed: (FD->hasBody() && "Functions must have body here"),
function analyzeParametersModification

Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/test/CodeGen/debug-info-param-modification.c

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=365716=365715=365716=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Wed Jul 10 17:09:16 2019
@@ -3587,9 +3587,12 @@ void CGDebugInfo::EmitFunctionStart(Glob
 
   // We use the SPDefCache only in the case when the debug entry values option
   // is set, in order to speed up parameters modification analysis.
-  if (CGM.getCodeGenOpts().EnableDebugEntryValues && HasDecl &&
-  isa(D))
-SPDefCache[cast(D)].reset(SP);
+  //
+  // FIXME: Use AbstractCallee here to support ObjCMethodDecl.
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues && HasDecl)
+if (auto *FD = dyn_cast(D))
+  if (FD->hasBody() && !FD->param_empty())
+SPDefCache[FD].reset(SP);
 
   if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
 // Starting with DWARF V5 method declarations are emitted as children of

Modified: cfe/trunk/test/CodeGen/debug-info-param-modification.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/debug-info-param-modification.c?rev=365716=365715=365716=diff
==
--- cfe/trunk/test/CodeGen/debug-info-param-modification.c (original)
+++ cfe/trunk/test/CodeGen/debug-info-param-modification.c Wed Jul 10 17:09:16 
2019
@@ -1,12 +1,21 @@
-// RUN: %clang -Xclang -femit-debug-entry-values -g -O2 -S -target 
x86_64-none-linux-gnu -emit-llvm %s -o - | FileCheck %s 
-check-prefix=CHECK-ENTRY-VAL-OPT
+// RUN: %clang -Xclang -femit-debug-entry-values -g -O2 -Xclang 
-disable-llvm-passes -S -target x86_64-none-linux-gnu -emit-llvm %s -o - | 
FileCheck %s -check-prefix=CHECK-ENTRY-VAL-OPT
 // CHECK-ENTRY-VAL-OPT: !DILocalVariable(name: "a", arg: 1, scope: {{.*}}, 
file: {{.*}}, line: {{.*}}, type: {{.*}})
 // CHECK-ENTRY-VAL-OPT: !DILocalVariable(name: "b", arg: 2, scope: {{.*}}, 
file: {{.*}}, line: {{.*}}, type: {{.*}}, flags: DIFlagArgumentNotModified)
 //
-// RUN: %clang -g -O2 -target x86_64-none-linux-gnu -S -emit-llvm %s -o - | 
FileCheck %s
+// For the os_log_helper:
+// CHECK-ENTRY-VAL-OPT: !DILocalVariable(name: "buffer", arg: 1, {{.*}}, 
flags: DIFlagArtificial)
+//
+// RUN: %clang -g -O2 -Xclang -disable-llvm-passes -target 
x86_64-none-linux-gnu -S -emit-llvm %s -o - | FileCheck %s
 // CHECK-NOT: !DILocalVariable(name: "b", arg: 2, scope: {{.*}}, file: {{.*}}, 
line: {{.*}}, type: {{.*}}, flags: DIFlagArgumentNotModified)
 //
+// For the os_log_helper:
+// CHECK: !DILocalVariable(name: "buffer", arg: 1, {{.*}}, flags: 
DIFlagArtificial)
 
 int fn2 (int a, int b) {
   ++a;
   return b;
 }
+
+void test_builtin_os_log(void *buf, int i, const char *data) {
+  __builtin_os_log_format(buf, "%d %{public}s %{private}.16P", i, data, data);
+}


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


r357501 - [os_log] Mark os_log_helper `nounwind`

2019-04-02 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Apr  2 10:42:38 2019
New Revision: 357501

URL: http://llvm.org/viewvc/llvm-project?rev=357501=rev
Log:
[os_log] Mark os_log_helper `nounwind`

Allow the optimizer to remove unnecessary EH cleanups surrounding calls
to os_log_helper, to save some code size.

As a follow-up, it might be worthwhile to add a BasicNoexcept exception
spec to os_log_helper, and to then teach CGCall to emit direct calls for
callees which can't throw. This could save some compile-time.

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

Added:
cfe/trunk/test/CodeGenObjCXX/os_log.mm
Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=357501=357500=357501=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Tue Apr  2 10:42:38 2019
@@ -1138,6 +1138,7 @@ llvm::Function *CodeGenFunction::generat
   Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
   CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
   CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
+  Fn->setDoesNotThrow();
 
   // Attach 'noinline' at -Oz.
   if (CGM.getCodeGenOpts().OptimizeSize == 2)

Added: cfe/trunk/test/CodeGenObjCXX/os_log.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/os_log.mm?rev=357501=auto
==
--- cfe/trunk/test/CodeGenObjCXX/os_log.mm (added)
+++ cfe/trunk/test/CodeGenObjCXX/os_log.mm Tue Apr  2 10:42:38 2019
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - -triple x86_64-darwin-apple -fobjc-arc \
+// RUN:   -fexceptions -fcxx-exceptions -O1 | FileCheck %s
+
+// Check that no EH cleanup is emitted around the call to __os_log_helper.
+namespace no_eh_cleanup {
+  void release(int *lock);
+
+  // CHECK-LABEL: define {{.*}} @_ZN13no_eh_cleanup3logERiPcS1_(
+  void log(int , char *data, char *buf) {
+  int lock __attribute__((cleanup(release)));
+  // CHECK: call void @__os_log_helper_1_2_2_4_0_8_34(
+  // CHECK-NEXT: call void @_ZN13no_eh_cleanup7releaseEPi
+  __builtin_os_log_format(buf, "%d %{public}s", i, data);
+  }
+
+  // CHECK: define {{.*}} @__os_log_helper_1_2_2_4_0_8_34({{.*}} 
[[NUW:#[0-9]+]]
+}
+
+// CHECK: attributes [[NUW]] = { {{.*}}nounwind


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


r350952 - [MergeFunc] Update clang test for r350939

2019-01-11 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Jan 11 10:51:02 2019
New Revision: 350952

URL: http://llvm.org/viewvc/llvm-project?rev=350952=rev
Log:
[MergeFunc] Update clang test for r350939

In r350939, the MergeFunc pass learned to erase duplicate functions
which are discardable if unused.

Modified:
cfe/trunk/test/CodeGenCXX/merge-functions.cpp

Modified: cfe/trunk/test/CodeGenCXX/merge-functions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/merge-functions.cpp?rev=350952=350951=350952=diff
==
--- cfe/trunk/test/CodeGenCXX/merge-functions.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/merge-functions.cpp Fri Jan 11 10:51:02 2019
@@ -1,5 +1,5 @@
 // REQUIRES: x86-registered-target
-// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions 
-emit-llvm -o - -x c++ < %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions 
-emit-llvm -o - -x c++ < %s | FileCheck %s -implicit-check-not=_ZN1A1gEiPi
 
 // Basic functionality test. Function merging doesn't kick in on functions that
 // are too simple.
@@ -9,6 +9,4 @@ struct A {
   virtual int g(int x, int *p) { return x ? *p : 1; }
 } a;
 
-// CHECK: define {{.*}} @_ZN1A1gEiPi
-// CHECK-NEXT: tail call i32 @_ZN1A1fEiPi
-// CHECK-NEXT: ret
+// CHECK: define {{.*}} @_ZN1A1fEiPi


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


r349542 - [CodeGen] Handle mixed-width ops in mixed-sign mul-with-overflow lowering

2018-12-18 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Dec 18 13:05:03 2018
New Revision: 349542

URL: http://llvm.org/viewvc/llvm-project?rev=349542=rev
Log:
[CodeGen] Handle mixed-width ops in mixed-sign mul-with-overflow lowering

The special lowering for __builtin_mul_overflow introduced in r320902
fixed an ICE seen when passing mixed-sign operands to the builtin.

This patch extends the special lowering to cover mixed-width, mixed-sign
operands. In a few common scenarios, calls to muloti4 will no longer be
emitted.

This should address the latest comments in PR34920 and work around the
link failure seen in:

  https://bugzilla.redhat.com/show_bug.cgi?id=1657544

Testing:
- check-clang
- A/B output comparison with: 
https://gist.github.com/vedantk/3eb9c88f82e5c32f2e590555b4af5081

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

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/builtins-overflow.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=349542=349541=349542=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Tue Dec 18 13:05:03 2018
@@ -1235,7 +1235,7 @@ static bool isSpecialMixedSignMultiply(u
WidthAndSignedness Op2Info,
WidthAndSignedness ResultInfo) {
   return BuiltinID == Builtin::BI__builtin_mul_overflow &&
- Op1Info.Width == Op2Info.Width && Op1Info.Width >= ResultInfo.Width &&
+ std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width &&
  Op1Info.Signed != Op2Info.Signed;
 }
 
@@ -1256,11 +1256,20 @@ EmitCheckedMixedSignMultiply(CodeGenFunc
   const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
   llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
   llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
+  unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width;
+  unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width;
+
+  // One of the operands may be smaller than the other. If so, [s|z]ext it.
+  if (SignedOpWidth < UnsignedOpWidth)
+Signed = CGF.Builder.CreateSExt(Signed, Unsigned->getType(), "op.sext");
+  if (UnsignedOpWidth < SignedOpWidth)
+Unsigned = CGF.Builder.CreateZExt(Unsigned, Signed->getType(), "op.zext");
 
   llvm::Type *OpTy = Signed->getType();
   llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
   Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
   llvm::Type *ResTy = ResultPtr.getElementType();
+  unsigned OpWidth = std::max(Op1Info.Width, Op2Info.Width);
 
   // Take the absolute value of the signed operand.
   llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
@@ -1278,8 +1287,8 @@ EmitCheckedMixedSignMultiply(CodeGenFunc
   if (ResultInfo.Signed) {
 // Signed overflow occurs if the result is greater than INT_MAX or lesser
 // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
-auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width)
-  .zextOrSelf(Op1Info.Width);
+auto IntMax =
+llvm::APInt::getSignedMaxValue(ResultInfo.Width).zextOrSelf(OpWidth);
 llvm::Value *MaxResult =
 CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
   CGF.Builder.CreateZExt(IsNegative, OpTy));
@@ -1297,9 +1306,9 @@ EmitCheckedMixedSignMultiply(CodeGenFunc
 llvm::Value *Underflow = CGF.Builder.CreateAnd(
 IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
-if (ResultInfo.Width < Op1Info.Width) {
+if (ResultInfo.Width < OpWidth) {
   auto IntMax =
-  llvm::APInt::getMaxValue(ResultInfo.Width).zext(Op1Info.Width);
+  llvm::APInt::getMaxValue(ResultInfo.Width).zext(OpWidth);
   llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
   UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
   Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);

Modified: cfe/trunk/test/CodeGen/builtins-overflow.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtins-overflow.c?rev=349542=349541=349542=diff
==
--- cfe/trunk/test/CodeGen/builtins-overflow.c (original)
+++ cfe/trunk/test/CodeGen/builtins-overflow.c Tue Dec 18 13:05:03 2018
@@ -339,6 +339,27 @@ long long test_smulll_overflow(long long
   return result;
 }
 
+int test_mixed_sign_mul_overflow_sext_signed_op(int x, unsigned long long y) {
+// CHECK: @test_mixed_sign_mul_overflow_sext_signed_op
+// CHECK: [[SignedOp:%.*]] = sext i32 %0 to i64
+// CHECK: [[IsNeg:%.*]] = icmp slt i64 [[SignedOp]], 0
+  int result;
+  if (__builtin_mul_overflow(x, y, ))
+return LongErrorCode;
+  return result;
+}
+
+int 

r348187 - [gcov/Darwin] Ensure external symbols are exported when using an export list

2018-12-03 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Dec  3 12:53:58 2018
New Revision: 348187

URL: http://llvm.org/viewvc/llvm-project?rev=348187=rev
Log:
[gcov/Darwin] Ensure external symbols are exported when using an export list

Make sure that symbols needed to implement runtime support for gcov are
exported when using an export list on Darwin.

Without the clang driver exporting these symbols, the linker hides them,
resulting in tapi verification failures.

rdar://45944768

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

Modified:
cfe/trunk/include/clang/Driver/ToolChain.h
cfe/trunk/lib/Driver/ToolChain.cpp
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/test/Driver/darwin-ld.c

Modified: cfe/trunk/include/clang/Driver/ToolChain.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/ToolChain.h?rev=348187=348186=348187=diff
==
--- cfe/trunk/include/clang/Driver/ToolChain.h (original)
+++ cfe/trunk/include/clang/Driver/ToolChain.h Mon Dec  3 12:53:58 2018
@@ -381,6 +381,9 @@ public:
   /// needsProfileRT - returns true if instrumentation profile is on.
   static bool needsProfileRT(const llvm::opt::ArgList );
 
+  /// Returns true if gcov instrumentation (-fprofile-arcs or --coverage) is 
on.
+  static bool needsGCovInstrumentation(const llvm::opt::ArgList );
+
   /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
   /// by default.
   virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList ) const;

Modified: cfe/trunk/lib/Driver/ToolChain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChain.cpp?rev=348187=348186=348187=diff
==
--- cfe/trunk/lib/Driver/ToolChain.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChain.cpp Mon Dec  3 12:53:58 2018
@@ -403,19 +403,23 @@ std::string ToolChain::getArchSpecificLi
 }
 
 bool ToolChain::needsProfileRT(const ArgList ) {
-  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
-   false) ||
+  if (needsGCovInstrumentation(Args) ||
   Args.hasArg(options::OPT_fprofile_generate) ||
   Args.hasArg(options::OPT_fprofile_generate_EQ) ||
   Args.hasArg(options::OPT_fprofile_instr_generate) ||
   Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
-  Args.hasArg(options::OPT_fcreate_profile) ||
-  Args.hasArg(options::OPT_coverage))
+  Args.hasArg(options::OPT_fcreate_profile))
 return true;
 
   return false;
 }
 
+bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList ) {
+  return Args.hasFlag(options::OPT_fprofile_arcs, 
options::OPT_fno_profile_arcs,
+  false) ||
+ Args.hasArg(options::OPT_coverage);
+}
+
 Tool *ToolChain::SelectTool(const JobAction ) const {
   if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
   Action::ActionClass AC = JA.getKind();

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=348187=348186=348187=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Mon Dec  3 12:53:58 2018
@@ -1034,11 +1034,17 @@ void Darwin::addProfileRTLibs(const ArgL
   // runtime, automatically export symbols necessary to implement some of the
   // runtime's functionality.
   if (hasExportSymbolDirective(Args)) {
-addExportedSymbol(CmdArgs, "___llvm_profile_filename");
-addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
-addExportedSymbol(CmdArgs, "_lprofCurFilename");
+if (needsGCovInstrumentation(Args)) {
+  addExportedSymbol(CmdArgs, "___gcov_flush");
+  addExportedSymbol(CmdArgs, "_flush_fn_list");
+  addExportedSymbol(CmdArgs, "_writeout_fn_list");
+} else {
+  addExportedSymbol(CmdArgs, "___llvm_profile_filename");
+  addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
+  addExportedSymbol(CmdArgs, "_lprofCurFilename");
+  addExportedSymbol(CmdArgs, "_lprofMergeValueProfData");
+}
 addExportedSymbol(CmdArgs, "_lprofDirMode");
-addExportedSymbol(CmdArgs, "_lprofMergeValueProfData");
   }
 }
 

Modified: cfe/trunk/test/Driver/darwin-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/darwin-ld.c?rev=348187=348186=348187=diff
==
--- cfe/trunk/test/Driver/darwin-ld.c (original)
+++ cfe/trunk/test/Driver/darwin-ld.c Mon Dec  3 12:53:58 2018
@@ -341,10 +341,22 @@
 // RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
 // PROFILE_EXPORT: "-exported_symbol" "___llvm_profile_filename" 
"-exported_symbol" "___llvm_profile_raw_version" "-exported_symbol" 
"_lprofCurFilename"
 //
-// RUN: %clang -target x86_64-apple-darwin12 

r347804 - [Coverage] Specify the Itanium ABI triple for a C++ test

2018-11-28 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Nov 28 12:51:09 2018
New Revision: 347804

URL: http://llvm.org/viewvc/llvm-project?rev=347804=rev
Log:
[Coverage] Specify the Itanium ABI triple for a C++ test

Modified:
cfe/trunk/test/CoverageMapping/default-method.cpp

Modified: cfe/trunk/test/CoverageMapping/default-method.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/default-method.cpp?rev=347804=347803=347804=diff
==
--- cfe/trunk/test/CoverageMapping/default-method.cpp (original)
+++ cfe/trunk/test/CoverageMapping/default-method.cpp Wed Nov 28 12:51:09 2018
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++17 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -emit-llvm-only -main-file-name default-method.cpp -w %s 
| FileCheck %s -implicit-check-not="->"
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++17 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only -main-file-name default-method.cpp -w %s | FileCheck %s 
-implicit-check-not="->"
 
 namespace PR39822 {
   struct unique_ptr {


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


r347803 - [Coverage] Do not visit artificial stmts in defaulted methods (PR39822)

2018-11-28 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Nov 28 12:48:07 2018
New Revision: 347803

URL: http://llvm.org/viewvc/llvm-project?rev=347803=rev
Log:
[Coverage] Do not visit artificial stmts in defaulted methods (PR39822)

There is no reason to emit coverage mappings for artificial statements
contained within defaulted methods, as these statements are not visible
to users.

Only emit a mapping for the body of the defaulted method (clang treats
the text of the "default" keyword as the body when reporting locations).
This allows users to see how often the default method is called, but
trims down the coverage mapping by skipping visitation of the children
of the method.

The immediate motivation for this change is that the lexer's
getPreciseTokenLocEnd API cannot return the correct location when given
an artificial statement (with a somewhat made-up location) as an input.

Test by Orivej Desh!

Fixes llvm.org/PR39822.

Added:
cfe/trunk/test/CoverageMapping/default-method.cpp
Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=347803=347802=347803=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Wed Nov 28 12:48:07 2018
@@ -656,12 +656,15 @@ struct CounterCoverageMappingBuilder
 return RegionStack.back();
   }
 
-  /// Propagate counts through the children of \c S.
-  Counter propagateCounts(Counter TopCount, const Stmt *S) {
+  /// Propagate counts through the children of \p S if \p VisitChildren is 
true.
+  /// Otherwise, only emit a count for \p S itself.
+  Counter propagateCounts(Counter TopCount, const Stmt *S,
+  bool VisitChildren = true) {
 SourceLocation StartLoc = getStart(S);
 SourceLocation EndLoc = getEnd(S);
 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
-Visit(S);
+if (VisitChildren)
+  Visit(S);
 Counter ExitCount = getRegion().getCounter();
 popRegions(Index);
 
@@ -874,7 +877,16 @@ struct CounterCoverageMappingBuilder
 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body
   return;
 
-propagateCounts(getRegionCounter(Body), Body);
+// Do not visit the artificial children nodes of defaulted methods. The
+// lexer may not be able to report back precise token end locations for
+// these children nodes (llvm.org/PR39822), and moreover users will not be
+// able to see coverage for them.
+bool Defaulted = false;
+if (auto *Method = dyn_cast(D))
+  Defaulted = Method->isDefaulted();
+
+propagateCounts(getRegionCounter(Body), Body,
+/*VisitChildren=*/!Defaulted);
 assert(RegionStack.empty() && "Regions entered but never exited");
 
 // Discard the last uncompleted deferred region in a decl, if one exists.

Added: cfe/trunk/test/CoverageMapping/default-method.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/default-method.cpp?rev=347803=auto
==
--- cfe/trunk/test/CoverageMapping/default-method.cpp (added)
+++ cfe/trunk/test/CoverageMapping/default-method.cpp Wed Nov 28 12:48:07 2018
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -std=c++17 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -emit-llvm-only -main-file-name default-method.cpp -w %s 
| FileCheck %s -implicit-check-not="->"
+
+namespace PR39822 {
+  struct unique_ptr {
+unique_ptr =(unique_ptr &);
+  };
+
+  class foo {
+foo =(foo &);
+unique_ptr convertable_values_[2];
+  };
+
+  // CHECK: _ZN7PR398223fooaSERS0_:
+  // CHECK-NEXT: File 0, [[@LINE+1]]:28 -> [[@LINE+1]]:29 = #0
+  foo ::operator=(foo &) = default;
+} // namespace PR39822
+


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


r347261 - [Sema] Fix PR38987: keep end location of a direct initializer list

2018-11-19 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Nov 19 12:10:21 2018
New Revision: 347261

URL: http://llvm.org/viewvc/llvm-project?rev=347261=rev
Log:
[Sema] Fix PR38987: keep end location of a direct initializer list

If PerformConstructorInitialization of a direct initializer list constructor is
called while instantiating a template, it has brace locations in its BraceLoc
arguments but not in the Kind argument.

This reverts the hunk https://reviews.llvm.org/D41921#inline-468844.

Patch by Orivej Desh!

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/SemaCXX/sourceranges.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=347261=347260=347261=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Nov 19 12:10:21 2018
@@ -6186,7 +6186,10 @@ PerformConstructorInitialization(Sema 
 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
 if (!TSInfo)
   TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
-SourceRange ParenOrBraceRange = Kind.getParenOrBraceRange();
+SourceRange ParenOrBraceRange =
+(Kind.getKind() == InitializationKind::IK_DirectList)
+? SourceRange(LBraceLoc, RBraceLoc)
+: Kind.getParenOrBraceRange();
 
 if (auto *Shadow = dyn_cast(
 Step.Function.FoundDecl.getDecl())) {

Modified: cfe/trunk/test/SemaCXX/sourceranges.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/sourceranges.cpp?rev=347261=347260=347261=diff
==
--- cfe/trunk/test/SemaCXX/sourceranges.cpp (original)
+++ cfe/trunk/test/SemaCXX/sourceranges.cpp Mon Nov 19 12:10:21 2018
@@ -52,6 +52,13 @@ void construct() {
   // CHECK: CXXConstructExpr {{0x[0-9a-fA-F]+}}  'D' 'void 
(int){{( __attribute__\(\(thiscall\)\))?}}'
 }
 
+namespace PR38987 {
+struct A { A(); };
+template  void f() { T{}; }
+template void f();
+// CHECK: CXXTemporaryObjectExpr {{.*}}  
'PR38987::A':'PR38987::A'
+}
+
 void abort() __attribute__((noreturn));
 
 namespace std {


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


r347262 - [Coverage] Fix PR39258: support coverage regions that start deeper than they end

2018-11-19 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Nov 19 12:10:22 2018
New Revision: 347262

URL: http://llvm.org/viewvc/llvm-project?rev=347262=rev
Log:
[Coverage] Fix PR39258: support coverage regions that start deeper than they end

popRegions used to assume that the start location of a region can't be
nested deeper than the end location, which is not always true.

Patch by Orivej Desh!

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

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/macros.c

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=347262=347261=347262=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Mon Nov 19 12:10:22 2018
@@ -552,6 +552,15 @@ struct CounterCoverageMappingBuilder
 completeDeferred(Count, DeferredEndLoc);
   }
 
+  size_t locationDepth(SourceLocation Loc) {
+size_t Depth = 0;
+while (Loc.isValid()) {
+  Loc = getIncludeOrExpansionLoc(Loc);
+  Depth++;
+}
+return Depth;
+  }
+
   /// Pop regions from the stack into the function's list of regions.
   ///
   /// Adds all regions from \c ParentIndex to the top of the stack to the
@@ -566,19 +575,41 @@ struct CounterCoverageMappingBuilder
 SourceLocation EndLoc = Region.hasEndLoc()
 ? Region.getEndLoc()
 : RegionStack[ParentIndex].getEndLoc();
+size_t StartDepth = locationDepth(StartLoc);
+size_t EndDepth = locationDepth(EndLoc);
 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
-  // The region ends in a nested file or macro expansion. Create a
-  // separate region for each expansion.
-  SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
-  assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
-
-  if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
-SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
-
-  EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
-  if (EndLoc.isInvalid())
-llvm::report_fatal_error("File exit not handled before 
popRegions");
+  bool UnnestStart = StartDepth >= EndDepth;
+  bool UnnestEnd = EndDepth >= StartDepth;
+  if (UnnestEnd) {
+// The region ends in a nested file or macro expansion. Create a
+// separate region for each expansion.
+SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
+assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
+
+if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
+  SourceRegions.emplace_back(Region.getCounter(), NestedLoc, 
EndLoc);
+
+EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
+if (EndLoc.isInvalid())
+  llvm::report_fatal_error("File exit not handled before 
popRegions");
+EndDepth--;
+  }
+  if (UnnestStart) {
+// The region begins in a nested file or macro expansion. Create a
+// separate region for each expansion.
+SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
+assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
+
+if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
+  SourceRegions.emplace_back(Region.getCounter(), StartLoc, 
NestedLoc);
+
+StartLoc = getIncludeOrExpansionLoc(StartLoc);
+if (StartLoc.isInvalid())
+  llvm::report_fatal_error("File exit not handled before 
popRegions");
+StartDepth--;
+  }
 }
+Region.setStartLoc(StartLoc);
 Region.setEndLoc(EndLoc);
 
 MostRecentLocation = EndLoc;

Modified: cfe/trunk/test/CoverageMapping/macros.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/macros.c?rev=347262=347261=347262=diff
==
--- cfe/trunk/test/CoverageMapping/macros.c (original)
+++ cfe/trunk/test/CoverageMapping/macros.c Mon Nov 19 12:10:22 2018
@@ -4,6 +4,7 @@
 #define MACRO_2 bar()
 #define MACRO_1 return; MACRO_2
 #define MACRO_3 MACRO_2
+#define GOTO goto
 
 void bar() {}
 
@@ -56,6 +57,15 @@ void func5() { // CHECK-NEXT: File 0, [[
 // CHECK-NEXT: Expansion,File 1, 6:17 -> 6:24 = #1
 // CHECK-NEXT: File 2, 4:17 -> 4:22 = #1
 
+// CHECK-NEXT: func6
+void func6(unsigned count) { // CHECK-NEXT: File 0, [[@LINE]]:28 -> 
[[@LINE+4]]:2 = #0
+begin:   // CHECK-NEXT: File 0, [[@LINE]]:1 -> 
[[@LINE+3]]:2 = #1
+if (count--) // CHECK-NEXT: File 0, [[@LINE]]:9 -> 
[[@LINE]]:16 = #1
+GOTO begin;  // CHECK-NEXT: File 0, [[@LINE]]:9 -> 
[[@LINE]]:19 = #2
+}
+// 

r346276 - [Darwin] Export new weak external symbols when compiling with coverage

2018-11-06 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Nov  6 14:25:00 2018
New Revision: 346276

URL: http://llvm.org/viewvc/llvm-project?rev=346276=rev
Log:
[Darwin] Export new weak external symbols when compiling with coverage

Some weak external symbols were added to the profile runtime in D49953,
and on Darwin, these need to be exported for tapi verification purposes.

I've tightened the test so that future breakages can be caught earlier.

rdar://45831054

Modified:
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=346276=346275=346276=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Tue Nov  6 14:25:00 2018
@@ -1037,6 +1037,8 @@ void Darwin::addProfileRTLibs(const ArgL
 addExportedSymbol(CmdArgs, "___llvm_profile_filename");
 addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
 addExportedSymbol(CmdArgs, "_lprofCurFilename");
+addExportedSymbol(CmdArgs, "_lprofDirMode");
+addExportedSymbol(CmdArgs, "_lprofMergeValueProfData");
   }
 }
 


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


r343883 - [DebugInfo] Add support for DWARF5 call site-related attributes

2018-10-05 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Oct  5 13:37:17 2018
New Revision: 343883

URL: http://llvm.org/viewvc/llvm-project?rev=343883=rev
Log:
[DebugInfo] Add support for DWARF5 call site-related attributes

DWARF v5 introduces DW_AT_call_all_calls, a subprogram attribute which
indicates that all calls (both regular and tail) within the subprogram
have call site entries. The information within these call site entries
can be used by a debugger to populate backtraces with synthetic tail
call frames.

Tail calling frames go missing in backtraces because the frame of the
caller is reused by the callee. Call site entries allow a debugger to
reconstruct a sequence of (tail) calls which led from one function to
another. This improves backtrace quality. There are limitations: tail
recursion isn't handled, variables within synthetic frames may not
survive to be inspected, etc. This approach is not novel, see:

  
https://gcc.gnu.org/wiki/summit2010?action=AttachFile=get=jelinek.pdf

This patch adds an IR-level flag (DIFlagAllCallsDescribed) which lowers
to DW_AT_call_all_calls. It adds the minimal amount of DWARF generation
support needed to emit standards-compliant call site entries. For easier
deployment, when the debugger tuning is LLDB, the DWARF requirement is
adjusted to v4.

Testing: Apart from check-{llvm, clang}, I built a stage2 RelWithDebInfo
clang binary. Its dSYM passed verification and grew by 1.4% compared to
the baseline. 151,879 call site entries were added.

rdar://42001377

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

Added:
cfe/trunk/test/CodeGenCXX/dbg-info-all-calls-described.cpp
Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.h

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=343883=343882=343883=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Fri Oct  5 13:37:17 2018
@@ -3168,6 +3168,7 @@ llvm::DISubprogram *CGDebugInfo::getFunc
   QualType FnType = CGM.getContext().getFunctionType(
   FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
   if (Stub) {
+Flags |= getCallSiteRelatedAttrs();
 return DBuilder.createFunction(
 DContext, Name, LinkageName, Unit, Line,
 getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
@@ -3407,6 +3408,8 @@ void CGDebugInfo::EmitFunctionStart(Glob
   if (CurFuncIsThunk)
 Flags |= llvm::DINode::FlagThunk;
 
+  llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
+
   unsigned LineNo = getLineNumber(Loc);
   unsigned ScopeLine = getLineNumber(ScopeLoc);
 
@@ -3418,7 +3421,7 @@ void CGDebugInfo::EmitFunctionStart(Glob
   llvm::DISubprogram *SP = DBuilder.createFunction(
   FDContext, Name, LinkageName, Unit, LineNo,
   getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
-  true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
+  true /*definition*/, ScopeLine, FlagsForDef, CGM.getLangOpts().Optimize,
   TParamsArray.get(), getFunctionDeclaration(D));
   Fn->setSubprogram(SP);
   // We might get here with a VarDecl in the case we're generating
@@ -4422,3 +4425,22 @@ llvm::DebugLoc CGDebugInfo::SourceLocToD
   llvm::MDNode *Scope = LexicalBlockStack.back();
   return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
 }
+
+llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
+  // Call site-related attributes are only useful in optimized programs, and
+  // when there's a possibility of debugging backtraces.
+  if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo 
||
+  DebugKind == codegenoptions::LocTrackingOnly)
+return llvm::DINode::FlagZero;
+
+  // Call site-related attributes are available in DWARF v5. Some debuggers,
+  // while not fully DWARF v5-compliant, may accept these attributes as if they
+  // were part of DWARF v4.
+  bool SupportsDWARFv4Ext =
+  CGM.getCodeGenOpts().DwarfVersion == 4 &&
+  CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB;
+  if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
+return llvm::DINode::FlagZero;
+
+  return llvm::DINode::FlagAllCallsDescribed;
+}

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.h?rev=343883=343882=343883=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.h (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.h Fri Oct  5 13:37:17 2018
@@ -608,6 +608,11 @@ private:
  unsigned LineNo, StringRef LinkageName,
  llvm::GlobalVariable *Var, llvm::DIScope *DContext);
 
+
+  /// Return flags which enable debug info emission for call sites, provided
+  

r342196 - Relax alignment assumptions in a test after r342194

2018-09-13 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Sep 13 17:16:37 2018
New Revision: 342196

URL: http://llvm.org/viewvc/llvm-project?rev=342196=rev
Log:
Relax alignment assumptions in a test after r342194

Don't hardcode align 8.

Fixes a bot failure:
http://lab.llvm.org:8011/builders/clang-cmake-armv8-full/builds/6373

Modified:
cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp

Modified: cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp?rev=342196=342195=342196=diff
==
--- cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp Thu Sep 13 17:16:37 2018
@@ -4,8 +4,8 @@
 // CHECK-LABEL: define{{.*}}lambda_in_func
 void lambda_in_func(int ) {
   // CHECK: [[ref_slot:%.*]] = getelementptr inbounds %class.anon, 
%class.anon* {{.*}}, i32 0, i32 0, !dbg [[lambda_decl_loc:![0-9]+]]
-  // CHECK-NEXT: %1 = load i32*, i32** %ref.addr, align 8, !dbg 
[[capture_init_loc:![0-9]+]]
-  // CHECK-NEXT: store i32* %1, i32** %0, align 8, !dbg [[lambda_decl_loc]]
+  // CHECK-NEXT: %1 = load i32*, i32** %ref.addr, align {{.*}}, !dbg 
[[capture_init_loc:![0-9]+]]
+  // CHECK-NEXT: store i32* %1, i32** %0, align {{.*}}, !dbg 
[[lambda_decl_loc]]
   // CHECK-NEXT: call void {{.*}}, !dbg [[lambda_call_loc:![0-9]+]]
 
   auto helper = [   // CHECK: [[lambda_decl_loc]] = !DILocation(line: 
[[@LINE]], column: 17


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


[clang-tools-extra] r342195 - Update a clang-tidy test for r342194

2018-09-13 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Sep 13 16:50:20 2018
New Revision: 342195

URL: http://llvm.org/viewvc/llvm-project?rev=342195=rev
Log:
Update a clang-tidy test for r342194

The location of implicit captures has changed. Update a use-after-move
checker test to reflect that.

This fixes a bot failure:
http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/36500

Modified:
clang-tools-extra/trunk/test/clang-tidy/bugprone-use-after-move.cpp

Modified: clang-tools-extra/trunk/test/clang-tidy/bugprone-use-after-move.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/bugprone-use-after-move.cpp?rev=342195=342194=342195=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/bugprone-use-after-move.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/bugprone-use-after-move.cpp Thu Sep 
13 16:50:20 2018
@@ -339,7 +339,7 @@ void lambdas() {
 A a;
 std::move(a);
 auto lambda = [=]() { a.foo(); };
-// CHECK-MESSAGES: [[@LINE-1]]:27: warning: 'a' used after it was moved
+// CHECK-MESSAGES: [[@LINE-1]]:20: warning: 'a' used after it was moved
 // CHECK-MESSAGES: [[@LINE-3]]:5: note: move occurred here
   }
   // Same tests but for capture by reference.
@@ -354,7 +354,7 @@ void lambdas() {
 A a;
 std::move(a);
 auto lambda = [&]() { a.foo(); };
-// CHECK-MESSAGES: [[@LINE-1]]:27: warning: 'a' used after it was moved
+// CHECK-MESSAGES: [[@LINE-1]]:20: warning: 'a' used after it was moved
 // CHECK-MESSAGES: [[@LINE-3]]:5: note: move occurred here
   }
   // But don't warn if the move happened after the capture.


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


r342194 - [Sema] Remove location from implicit capture init expr

2018-09-13 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Sep 13 16:28:25 2018
New Revision: 342194

URL: http://llvm.org/viewvc/llvm-project?rev=342194=rev
Log:
[Sema] Remove location from implicit capture init expr

A lambda's closure is initialized when the lambda is declared. For
implicit captures, the initialization code emitted from EmitLambdaExpr
references source locations *within the lambda body* in the function
containing the lambda. This results in a poor debugging experience: we
step to the line containing the lambda, then into lambda, out again,
over and over, until every capture's field is initialized.

To improve stepping behavior, assign the starting location of the lambda
to expressions which initialize an implicit capture within it.

rdar://39807527

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

Added:
cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp
Modified:
cfe/trunk/lib/Sema/SemaLambda.cpp
cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp
cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/templates.cpp
cfe/trunk/test/SemaCXX/uninitialized.cpp
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/DeclRefExpr.cpp

Modified: cfe/trunk/lib/Sema/SemaLambda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLambda.cpp?rev=342194=342193=342194=diff
==
--- cfe/trunk/lib/Sema/SemaLambda.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLambda.cpp Thu Sep 13 16:28:25 2018
@@ -1392,13 +1392,14 @@ static void addBlockPointerConversion(Se
   Class->addDecl(Conversion);
 }
 
-static ExprResult performLambdaVarCaptureInitialization(Sema ,
-const Capture ,
-FieldDecl *Field) {
+static ExprResult performLambdaVarCaptureInitialization(
+Sema , const Capture , FieldDecl *Field,
+SourceLocation ImplicitCaptureLoc, bool IsImplicitCapture) {
   assert(Capture.isVariableCapture() && "not a variable capture");
 
   auto *Var = Capture.getVariable();
-  SourceLocation Loc = Capture.getLocation();
+  SourceLocation Loc =
+  IsImplicitCapture ? ImplicitCaptureLoc : Capture.getLocation();
 
   // C++11 [expr.prim.lambda]p21:
   //   When the lambda-expression is evaluated, the entities that
@@ -1607,8 +1608,8 @@ ExprResult Sema::BuildLambdaExpr(SourceL
Var, From.getEllipsisLoc()));
   Expr *Init = From.getInitExpr();
   if (!Init) {
-auto InitResult =
-performLambdaVarCaptureInitialization(*this, From, *CurField);
+auto InitResult = performLambdaVarCaptureInitialization(
+*this, From, *CurField, CaptureDefaultLoc, IsImplicit);
 if (InitResult.isInvalid())
   return ExprError();
 Init = InitResult.get();

Modified: cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp?rev=342194=342193=342194=diff
==
--- cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp (original)
+++ cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp Thu Sep 13 
16:28:25 2018
@@ -15,8 +15,8 @@ public:
 
 void capture_by_copy(NonCopyable nc, NonCopyable , const NonConstCopy nco) 
{
   (void)[nc] { }; // expected-error{{capture of variable 'nc' as type 
'NonCopyable' calls private copy constructor}}
-  (void)[=] {
-ncr.foo(); // expected-error{{capture of variable 'ncr' as type 
'NonCopyable' calls private copy constructor}} 
+  (void)[=] { // expected-error{{capture of variable 'ncr' as type 
'NonCopyable' calls private copy constructor}}
+ncr.foo();
   }();
 
   [nco] {}(); // expected-error{{no matching constructor for initialization of 
'const NonConstCopy'}}

Modified: cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/templates.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/templates.cpp?rev=342194=342193=342194=diff
==
--- cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/templates.cpp (original)
+++ cfe/trunk/test/CXX/expr/expr.prim/expr.prim.lambda/templates.cpp Thu Sep 13 
16:28:25 2018
@@ -88,8 +88,8 @@ namespace p2 {
   template
   void odr_used2(R , Boom boom) {
 const std::type_info 
-  = typeid([=,] () -> R& {
-  boom.tickle(); // expected-note{{in instantiation of member 
function}}
+  = typeid([=,] () -> R& { // expected-note{{in instantiation of member 
function 'p2::Boom::Boom' requested here}}
+  boom.tickle();
   return r; 
 }()); 
   }

Added: cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/debug-info-lambda.cpp?rev=342194=auto

r341985 - [gcov] Update a clang test for r341977

2018-09-11 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Sep 11 12:42:58 2018
New Revision: 341985

URL: http://llvm.org/viewvc/llvm-project?rev=341985=rev
Log:
[gcov] Update a clang test for r341977

Update test/CodeGen/code-coverage.c so that it doesn't refer to a gcov
function which is no longer emitted after r341977.

Fixes bot failure:
http://lab.llvm.org:8011/builders/clang-ppc64be-linux/builds/23831

Modified:
cfe/trunk/test/CodeGen/code-coverage.c

Modified: cfe/trunk/test/CodeGen/code-coverage.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/code-coverage.c?rev=341985=341984=341985=diff
==
--- cfe/trunk/test/CodeGen/code-coverage.c (original)
+++ cfe/trunk/test/CodeGen/code-coverage.c Tue Sep 11 12:42:58 2018
@@ -40,8 +40,7 @@ int test2(int b) {
 
 // Check that the noredzone flag is set on the generated functions.
 
-// CHECK: void @__llvm_gcov_indirect_counter_increment(i32* %{{.*}}, i64** 
%{{.*}}) unnamed_addr [[NRZ:#[0-9]+]]
-// CHECK: void @__llvm_gcov_writeout() unnamed_addr [[NRZ]]
+// CHECK: void @__llvm_gcov_writeout() unnamed_addr [[NRZ:#[0-9]+]]
 // CHECK: void @__llvm_gcov_flush() unnamed_addr [[NRZ]]
 // CHECK: void @__llvm_gcov_init() unnamed_addr [[NRZ]]
 


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


r340849 - [ubsan] Enable -fsanitize=vptr on Apple devices and simulators

2018-08-28 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Aug 28 11:01:42 2018
New Revision: 340849

URL: http://llvm.org/viewvc/llvm-project?rev=340849=rev
Log:
[ubsan] Enable -fsanitize=vptr on Apple devices and simulators

It seems like an oversight that this check was not always enabled for
on-device or device simulator targets.

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/test/Driver/fsanitize.c

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=340849=340848=340849=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Tue Aug 28 11:01:42 2018
@@ -2258,9 +2258,15 @@ SanitizerMask Darwin::getSupportedSaniti
   Res |= SanitizerKind::Fuzzer;
   Res |= SanitizerKind::FuzzerNoLink;
   Res |= SanitizerKind::Function;
+
+  // Prior to 10.9, macOS shipped a version of the C++ standard library without
+  // C++11 support. The same is true of iOS prior to version 5. These OS'es are
+  // incompatible with -fsanitize=vptr.
+  if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
+  && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
+Res |= SanitizerKind::Vptr;
+
   if (isTargetMacOS()) {
-if (!isMacosxVersionLT(10, 9))
-  Res |= SanitizerKind::Vptr;
 if (IsX86_64)
   Res |= SanitizerKind::Thread;
   } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {

Modified: cfe/trunk/test/Driver/fsanitize.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fsanitize.c?rev=340849=340848=340849=diff
==
--- cfe/trunk/test/Driver/fsanitize.c (original)
+++ cfe/trunk/test/Driver/fsanitize.c Tue Aug 28 11:01:42 2018
@@ -423,6 +423,15 @@
 // RUN: %clang -target x86_64-apple-darwin10 -mmacosx-version-min=10.8 
-fsanitize=vptr %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-DARWIN-OLD
 // CHECK-VPTR-DARWIN-OLD: unsupported option '-fsanitize=vptr' for target 
'x86_64-apple-darwin10'
 
+// RUN: %clang -target arm-apple-ios4 -fsanitize=vptr %s -### 2>&1 | FileCheck 
%s --check-prefix=CHECK-VPTR-IOS-OLD
+// CHECK-VPTR-IOS-OLD: unsupported option '-fsanitize=vptr' for target 
'arm-apple-ios4'
+
+// RUN: %clang -target aarch64-apple-darwin15.0.0 -fsanitize=vptr %s -### 2>&1
+// OK
+
+// RUN: %clang -target x86_64-apple-darwin15.0.0-simulator -fsanitize=vptr %s 
-### 2>&1
+// OK
+
 // RUN: %clang -target x86_64-apple-darwin10 -mmacosx-version-min=10.9 
-fsanitize=alignment,vptr %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-VPTR-DARWIN-NEW
 // CHECK-VPTR-DARWIN-NEW: -fsanitize=alignment,vptr
 


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


r340559 - [docs] Regenerate ClangCommandLineReference.rst

2018-08-23 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Aug 23 10:55:03 2018
New Revision: 340559

URL: http://llvm.org/viewvc/llvm-project?rev=340559=rev
Log:
[docs] Regenerate ClangCommandLineReference.rst

Modified:
cfe/trunk/docs/ClangCommandLineReference.rst

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=340559=340558=340559=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Thu Aug 23 10:55:03 2018
@@ -36,7 +36,7 @@ Treat source input files as Objective-C
 
 Treat source input files as Objective-C++ inputs
 
-.. option:: -Qn
+.. option:: -Qn, -fno-ident
 
 Do not emit metadata containing compiler name and version
 
@@ -44,7 +44,7 @@ Do not emit metadata containing compiler
 
 Don't emit warning for unused driver arguments
 
-.. option:: -Qy
+.. option:: -Qy, -fident
 
 Emit metadata containing compiler name and version
 
@@ -214,9 +214,13 @@ Flush denormal floating point values to
 
 Generate relocatable device code, also known as separate compilation mode.
 
+.. option:: -fcuda-short-ptr, -fno-cuda-short-ptr
+
+Use 32-bit pointers for accessing const/local/shared address spaces.
+
 .. option:: -ffixed-r19
 
-Reserve the r19 register (Hexagon only)
+Reserve register r19 (Hexagon only)
 
 .. option:: -fheinous-gnu-extensions
 
@@ -260,6 +264,10 @@ Display available options
 
 Display help for hidden options
 
+.. option:: --hip-link
+
+Link clang-offload-bundler bundles for HIP
+
 .. option:: -image\_base 
 
 .. option:: -index-header-map
@@ -452,6 +460,10 @@ Use pipes between commands, when possibl
 
 .. option:: --print-diagnostic-categories
 
+.. option:: -print-effective-triple, --print-effective-triple
+
+Print the effective target triple
+
 .. option:: -print-file-name=, --print-file-name=, 
--print-file-name 
 
 Print the full library path of 
@@ -480,6 +492,10 @@ Print the resource directory pathname
 
 Print the paths used for finding libraries and programs
 
+.. option:: -print-target-triple, --print-target-triple
+
+Print the normalized target triple
+
 .. option:: -private\_bundle
 
 .. option:: -pthread, -no-pthread
@@ -558,6 +574,8 @@ Serialize compiler diagnostics to a file
 
 .. option:: -shared-libsan, -shared-libasan
 
+Dynamically link the sanitizer runtime
+
 .. option:: -single\_module
 
 .. option:: -specs=, --specs=
@@ -568,6 +586,8 @@ Serialize compiler diagnostics to a file
 
 .. option:: -static-libsan
 
+Statically link the sanitizer runtime
+
 .. option:: -static-libstdc++
 
 .. option:: -std-default=
@@ -712,6 +732,12 @@ Attempt to match the ABI of Clang  as a documentation comment block 
command
 
+.. option:: -fcomplete-member-pointers, -fno-complete-member-pointers
+
+Require member pointer base types to be complete if they would be significant 
under the Microsoft ABI
+
+.. option:: -fcrash-diagnostics-dir=
+
 .. option:: -fdeclspec, -fno-declspec
 
 Allow \_\_declspec as a keyword
@@ -746,7 +772,7 @@ Enables an experimental new pass manager
 
 .. option:: -ffine-grained-bitfield-accesses, 
-fno-fine-grained-bitfield-accesses
 
-Use separate accesses for bitfields with legal widths and alignments.
+Use separate accesses for consecutive bitfield runs with legal widths and 
alignments.
 
 .. option:: -finline-functions, -fno-inline-functions
 
@@ -854,6 +880,10 @@ Strip (or keep only, if negative) a give
 
 Turn on runtime checks for various forms of undefined or suspicious behavior. 
See user manual for available checks
 
+.. option:: -moutline, -mno-outline
+
+Enable function outlining (AArch64 only)
+
 .. option:: --param , --param=
 
 .. option:: -std=, --std=, --std 
@@ -1151,6 +1181,10 @@ Target-independent compilation options
 
 .. option:: -faccess-control, -fno-access-control
 
+.. option:: -faddrsig, -fno-addrsig
+
+Emit an address-significance table
+
 .. option:: -falign-functions, -fno-align-functions
 
 .. program:: clang1
@@ -1223,12 +1257,20 @@ Accept non-standard constructs supported
 
 Load the clang builtins module map file.
 
+.. option:: -fc++-static-destructors, -fno-c++-static-destructors
+
+Enable C++ static destructor registration (the default)
+
 .. option:: -fcaret-diagnostics, -fno-caret-diagnostics
 
 .. option:: -fcf-protection=, -fcf-protection (equivalent to 
-fcf-protection=full)
 
 Instrument control-flow architecture protection. Options: return, branch, 
full, none.
 
+.. option:: -fchar8\_t, -fno-char8\_t
+
+Enable C++ builtin type char8\_t
+
 .. option:: -fclasspath=, --CLASSPATH , --CLASSPATH=, 
--classpath , --classpath=
 
 .. option:: -fcolor-diagnostics, -fno-color-diagnostics
@@ -1293,6 +1335,10 @@ Place debug types in their own section (
 
 Parse templated function definitions at the end of the translation unit
 
+.. option:: -fdelete-null-pointer-checks, -fno-delete-null-pointer-checks
+
+Treat usage of null 

r340558 - [options] Document -(static|shared)-libsan

2018-08-23 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Aug 23 10:54:48 2018
New Revision: 340558

URL: http://llvm.org/viewvc/llvm-project?rev=340558=rev
Log:
[options] Document -(static|shared)-libsan

Modified:
cfe/trunk/include/clang/Driver/Options.td

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=340558=340557=340558=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Thu Aug 23 10:54:48 2018
@@ -639,8 +639,10 @@ def fapple_kext : Flag<["-"], "fapple-ke
   HelpText<"Use Apple's kernel extensions ABI">;
 def fapple_pragma_pack : Flag<["-"], "fapple-pragma-pack">, Group, 
Flags<[CC1Option]>,
   HelpText<"Enable Apple gcc-compatible #pragma pack handling">;
-def shared_libsan : Flag<["-"], "shared-libsan">;
-def static_libsan : Flag<["-"], "static-libsan">;
+def shared_libsan : Flag<["-"], "shared-libsan">,
+  HelpText<"Dynamically link the sanitizer runtime">;
+def static_libsan : Flag<["-"], "static-libsan">,
+  HelpText<"Statically link the sanitizer runtime">;
 def : Flag<["-"], "shared-libasan">, Alias;
 def fasm : Flag<["-"], "fasm">, Group;
 


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


r339964 - Relax a CHECK line to allow for dso_local

2018-08-16 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Aug 16 16:19:50 2018
New Revision: 339964

URL: http://llvm.org/viewvc/llvm-project?rev=339964=rev
Log:
Relax a CHECK line to allow for dso_local

Fixes a bot failure:
http://lab.llvm.org:8011/builders/llvm-clang-x86_64-expensive-checks-win/builds/11806

Modified:
cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c

Modified: cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c?rev=339964=339963=339964=diff
==
--- cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c (original)
+++ cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c Thu Aug 16 16:19:50 2018
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 %s -emit-llvm -fprofile-instrument=clang -fsanitize=thread 
-o - | FileCheck %s
 
-// CHECK: define void @foo
+// CHECK: define {{.*}}@foo
 // CHECK-NOT: load {{.*}}foo
 // CHECK: ret void
 void foo() {}


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


r339955 - [InstrProf] Use atomic profile counter updates for TSan

2018-08-16 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Aug 16 15:24:47 2018
New Revision: 339955

URL: http://llvm.org/viewvc/llvm-project?rev=339955=rev
Log:
[InstrProf] Use atomic profile counter updates for TSan

Thread sanitizer instrumentation fails to skip all loads and stores to
profile counters. This can happen if profile counter updates are merged:

  %.sink = phi i64* ...
  %pgocount5 = load i64, i64* %.sink
  %27 = add i64 %pgocount5, 1
  %28 = bitcast i64* %.sink to i8*
  call void @__tsan_write8(i8* %28)
  store i64 %27, i64* %.sink

To suppress TSan diagnostics about racy counter updates, make the
counter updates atomic when TSan is enabled. If there's general interest
in this mode it can be surfaced as a clang/swift driver option.

Testing: check-{llvm,clang,profile}

rdar://40477803

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

Added:
cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c
Modified:
cfe/trunk/lib/CodeGen/BackendUtil.cpp

Modified: cfe/trunk/lib/CodeGen/BackendUtil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/BackendUtil.cpp?rev=339955=339954=339955=diff
==
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp (original)
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp Thu Aug 16 15:24:47 2018
@@ -653,6 +653,11 @@ void EmitAssemblyHelper::CreatePasses(le
 InstrProfOptions Options;
 Options.NoRedZone = CodeGenOpts.DisableRedZone;
 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
+
+// TODO: Surface the option to emit atomic profile counter increments at
+// the driver level.
+Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
+
 MPM.add(createInstrProfilingLegacyPass(Options));
   }
   if (CodeGenOpts.hasProfileIRInstr()) {

Added: cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c?rev=339955=auto
==
--- cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c (added)
+++ cfe/trunk/test/CodeGen/tsan-instrprof-atomic.c Thu Aug 16 15:24:47 2018
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 %s -emit-llvm -fprofile-instrument=clang -fsanitize=thread 
-o - | FileCheck %s
+
+// CHECK: define void @foo
+// CHECK-NOT: load {{.*}}foo
+// CHECK: ret void
+void foo() {}


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


Re: r337928 - [OPENMP] Fix PR38256: Fix locations of the artificial conditional op.

2018-07-25 Thread Vedant Kumar via cfe-commits
Ah, great. Thanks again!

vedant

> On Jul 25, 2018, at 10:33 AM, Alexey Bataev  wrote:
> 
> This is visible to the user, the statement under #pragma omp parallel 
> directive is outlined as a function.
> -
> Best regards,
> Alexey Bataev
> 25.07.2018 13:31, Vedant Kumar пишет:
>> Thanks!
>> 
>> Just out of curiosity, what is the "omp_outlined" function you're checking 
>> for? Is it implicitly-defined? If it's not user-visible, i.e it doesn't 
>> actually appear in the source code of a program, why should we generate a 
>> code coverage mapping for it at all?
>> 
>> vedant
>> 
>>> On Jul 25, 2018, at 7:40 AM, Alexey Bataev via cfe-commits 
>>>   wrote:
>>> 
>>> Author: abataev
>>> Date: Wed Jul 25 07:40:26 2018
>>> New Revision: 337928
>>> 
>>> URL: http://llvm.org/viewvc/llvm-project?rev=337928=rev 
>>> 
>>> Log:
>>> [OPENMP] Fix PR38256: Fix locations of the artificial conditional op.
>>> 
>>> Fixed the source locations of the conditional op so that they don'r
>>> crash coverage pass.
>>> 
>>> Added:
>>>cfe/trunk/test/CoverageMapping/openmp.c
>>> Modified:
>>>cfe/trunk/lib/Sema/SemaOpenMP.cpp
>>> 
>>> Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
>>> URL: 
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=337928=337927=337928=diff
>>>  
>>> 
>>> ==
>>> --- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
>>> +++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Wed Jul 25 07:40:26 2018
>>> @@ -4909,7 +4909,8 @@ checkOpenMPLoop(OpenMPDirectiveKind DKin
>>> ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
>>> UB.get(), 
>>> LastIteration.get());
>>> ExprResult CondOp = SemaRef.ActOnConditionalOp(
>>> -InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), 
>>> UB.get());
>>> +LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
>>> +LastIteration.get(), UB.get());
>>> EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
>>>  CondOp.get());
>>> EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
>>> 
>>> Added: cfe/trunk/test/CoverageMapping/openmp.c
>>> URL: 
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/openmp.c?rev=337928=auto
>>>  
>>> 
>>> ==
>>> --- cfe/trunk/test/CoverageMapping/openmp.c (added)
>>> +++ cfe/trunk/test/CoverageMapping/openmp.c Wed Jul 25 07:40:26 2018
>>> @@ -0,0 +1,12 @@
>>> +// RUN: %clang_cc1 -fopenmp -fprofile-instrument=clang -fcoverage-mapping 
>>> -dump-coverage-mapping -emit-llvm-only -main-file-name openmp.c %s | 
>>> FileCheck %s
>>> +
>>> +// CHECK: openmp.c:{{.+}}omp_outlined{{.+}}:
>>> +// CHECK: File 0, 10:3 -> 10:31
>>> +// CHECK: File 0, 10:19 -> 10:24
>>> +// CHECK: File 0, 10:26 -> 10:29
>>> +// CHECK: File 0, 10:30 -> 10:31
>>> +int foo(int time, int n) {
>>> +#pragma omp parallel for default(shared) schedule(dynamic, 1) reduction(+ 
>>> : time)
>>> +  for (int i = 1; i < n; ++i);
>>> +  return 0;
>>> +}
>>> 
>>> 
>>> ___
>>> cfe-commits mailing list
>>> cfe-commits@lists.llvm.org 
>>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits 
>>> 
> 

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


Re: r337928 - [OPENMP] Fix PR38256: Fix locations of the artificial conditional op.

2018-07-25 Thread Vedant Kumar via cfe-commits
Thanks!

Just out of curiosity, what is the "omp_outlined" function you're checking for? 
Is it implicitly-defined? If it's not user-visible, i.e it doesn't actually 
appear in the source code of a program, why should we generate a code coverage 
mapping for it at all?

vedant

> On Jul 25, 2018, at 7:40 AM, Alexey Bataev via cfe-commits 
>  wrote:
> 
> Author: abataev
> Date: Wed Jul 25 07:40:26 2018
> New Revision: 337928
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=337928=rev
> Log:
> [OPENMP] Fix PR38256: Fix locations of the artificial conditional op.
> 
> Fixed the source locations of the conditional op so that they don'r
> crash coverage pass.
> 
> Added:
>cfe/trunk/test/CoverageMapping/openmp.c
> Modified:
>cfe/trunk/lib/Sema/SemaOpenMP.cpp
> 
> Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=337928=337927=337928=diff
> ==
> --- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Wed Jul 25 07:40:26 2018
> @@ -4909,7 +4909,8 @@ checkOpenMPLoop(OpenMPDirectiveKind DKin
> ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
> UB.get(), 
> LastIteration.get());
> ExprResult CondOp = SemaRef.ActOnConditionalOp(
> -InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
> +LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
> +LastIteration.get(), UB.get());
> EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
>  CondOp.get());
> EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
> 
> Added: cfe/trunk/test/CoverageMapping/openmp.c
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/openmp.c?rev=337928=auto
> ==
> --- cfe/trunk/test/CoverageMapping/openmp.c (added)
> +++ cfe/trunk/test/CoverageMapping/openmp.c Wed Jul 25 07:40:26 2018
> @@ -0,0 +1,12 @@
> +// RUN: %clang_cc1 -fopenmp -fprofile-instrument=clang -fcoverage-mapping 
> -dump-coverage-mapping -emit-llvm-only -main-file-name openmp.c %s | 
> FileCheck %s
> +
> +// CHECK: openmp.c:{{.+}}omp_outlined{{.+}}:
> +// CHECK: File 0, 10:3 -> 10:31
> +// CHECK: File 0, 10:19 -> 10:24
> +// CHECK: File 0, 10:26 -> 10:29
> +// CHECK: File 0, 10:30 -> 10:31
> +int foo(int time, int n) {
> +#pragma omp parallel for default(shared) schedule(dynamic, 1) reduction(+ : 
> time)
> +  for (int i = 1; i < n; ++i);
> +  return 0;
> +}
> 
> 
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

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


r336937 - [Driver] Conform warn_drv_object_size_disabled_O0 to DefaultWarnNoError

2018-07-12 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Jul 12 12:53:15 2018
New Revision: 336937

URL: http://llvm.org/viewvc/llvm-project?rev=336937=rev
Log:
[Driver] Conform warn_drv_object_size_disabled_O0 to DefaultWarnNoError

This diagnostic triggers when -fsanitize=object-size is explicitly
specified but will be a no-op (i.e, at -O0).

This diagnostic should not fail a -Werror build because it's just an
explanatory note to the user. It's not always actionable.

For example, a user may not be able to simply disable object-size,
because they want it enabled in optimized builds.

rdar://42128447

Modified:
cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
cfe/trunk/test/Driver/fsanitize-object-size.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=336937=336936=336937=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Thu Jul 12 12:53:15 
2018
@@ -273,7 +273,7 @@ def warn_drv_disabling_vptr_no_rtti_defa
   InGroup;
 def warn_drv_object_size_disabled_O0 : Warning<
   "the object size sanitizer has no effect at -O0, but is explicitly enabled: 
%0">,
-  InGroup;
+  InGroup, DefaultWarnNoWerror;
 
 def note_drv_command_failed_diag_msg : Note<
   "diagnostic msg: %0">;

Modified: cfe/trunk/test/Driver/fsanitize-object-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fsanitize-object-size.c?rev=336937=336936=336937=diff
==
--- cfe/trunk/test/Driver/fsanitize-object-size.c (original)
+++ cfe/trunk/test/Driver/fsanitize-object-size.c Thu Jul 12 12:53:15 2018
@@ -2,8 +2,9 @@
 //
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=object-size %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NO-OSIZE
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=object-size %s -O0 -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NO-OSIZE
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=null,object-size %s -### 
2>&1 | FileCheck %s --check-prefixes=CHECK-NO-OSIZE
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined %s -### 2>&1 | 
FileCheck %s --check-prefixes=CHECK-NO-OSIZE-NO-WARNING
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=null,object-size %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-NO-OSIZE
+// RUN: %clang -target x86_64-linux-gnu -Werror -fsanitize=null,object-size %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-OSIZE
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NO-OSIZE-NO-WARNING
 
 // Check that the object size check is enabled at other optimization levels.
 //


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


r335890 - [Darwin] Remove _VPMergeHook from the auto-export list

2018-06-28 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Jun 28 10:53:35 2018
New Revision: 335890

URL: http://llvm.org/viewvc/llvm-project?rev=335890=rev
Log:
[Darwin] Remove _VPMergeHook from the auto-export list

Remove _VPMergeHook from Darwin's automatically-exported symbol list for
PGO. As of r328987 this symbol is no longer weak.

An integration test in compiler-rt will follow.

rdar://41470205

Modified:
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/test/Driver/darwin-ld.c

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=335890=335889=335890=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Thu Jun 28 10:53:35 2018
@@ -1019,7 +1019,6 @@ void Darwin::addProfileRTLibs(const ArgL
   // runtime, automatically export symbols necessary to implement some of the
   // runtime's functionality.
   if (hasExportSymbolDirective(Args)) {
-addExportedSymbol(CmdArgs, "_VPMergeHook");
 addExportedSymbol(CmdArgs, "___llvm_profile_filename");
 addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
 addExportedSymbol(CmdArgs, "_lprofCurFilename");

Modified: cfe/trunk/test/Driver/darwin-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/darwin-ld.c?rev=335890=335889=335890=diff
==
--- cfe/trunk/test/Driver/darwin-ld.c (original)
+++ cfe/trunk/test/Driver/darwin-ld.c Thu Jun 28 10:53:35 2018
@@ -366,7 +366,7 @@
 // RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate -Xlinker 
-exported_symbols_list -Xlinker /dev/null -### %t.o 2> %t.log
 // RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
-// PROFILE_EXPORT: "-exported_symbol" "_VPMergeHook" "-exported_symbol" 
"___llvm_profile_filename" "-exported_symbol" "___llvm_profile_raw_version" 
"-exported_symbol" "_lprofCurFilename"
+// PROFILE_EXPORT: "-exported_symbol" "___llvm_profile_filename" 
"-exported_symbol" "___llvm_profile_raw_version" "-exported_symbol" 
"_lprofCurFilename"
 //
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate -### 
%t.o 2> %t.log
 // RUN: FileCheck -check-prefix=NO_PROFILE_EXPORT %s < %t.log


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


r335577 - Fix an ambiguous overload issue pointed out by MSVC

2018-06-25 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Jun 25 20:53:06 2018
New Revision: 335577

URL: http://llvm.org/viewvc/llvm-project?rev=335577=rev
Log:
Fix an ambiguous overload issue pointed out by MSVC

Log:
http://lab.llvm.org:8011/builders/clang-x64-ninja-win7/builds/11390

Modified:
cfe/trunk/include/clang/Basic/Specifiers.h
cfe/trunk/lib/Sema/SemaLambda.cpp

Modified: cfe/trunk/include/clang/Basic/Specifiers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Specifiers.h?rev=335577=335576=335577=diff
==
--- cfe/trunk/include/clang/Basic/Specifiers.h (original)
+++ cfe/trunk/include/clang/Basic/Specifiers.h Mon Jun 25 20:53:06 2018
@@ -296,7 +296,7 @@ namespace clang {
 
   /// Return true if \p L has a weaker nullability annotation than \p R. The
   /// ordering is: Unspecified < Nullable < NonNull.
-  inline bool operator<(NullabilityKind L, NullabilityKind R) {
+  inline bool hasWeakerNullability(NullabilityKind L, NullabilityKind R) {
 return uint8_t(L) > uint8_t(R);
   }
 

Modified: cfe/trunk/lib/Sema/SemaLambda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLambda.cpp?rev=335577=335576=335577=diff
==
--- cfe/trunk/lib/Sema/SemaLambda.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLambda.cpp Mon Jun 25 20:53:06 2018
@@ -712,7 +712,8 @@ void Sema::deduceClosureReturnType(Captu
   auto RetTyNullability = ReturnType->getNullability(Ctx);
   auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
   if (BlockNullability &&
-  (!RetTyNullability || *RetTyNullability < *BlockNullability))
+  (!RetTyNullability ||
+   hasWeakerNullability(*RetTyNullability, *BlockNullability)))
 CSI.ReturnType = ReturnType;
   continue;
 }


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


r335571 - Modernize a function, NFC.

2018-06-25 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Jun 25 19:50:01 2018
New Revision: 335571

URL: http://llvm.org/viewvc/llvm-project?rev=335571=rev
Log:
Modernize a function, NFC.

Modified:
cfe/trunk/lib/Sema/SemaLambda.cpp

Modified: cfe/trunk/lib/Sema/SemaLambda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLambda.cpp?rev=335571=335570=335571=diff
==
--- cfe/trunk/lib/Sema/SemaLambda.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLambda.cpp Mon Jun 25 19:50:01 2018
@@ -692,9 +692,7 @@ void Sema::deduceClosureReturnType(Captu
   }
 
   // Third case: only one return statement. Don't bother doing extra work!
-  SmallVectorImpl::iterator I = CSI.Returns.begin(),
- E = CSI.Returns.end();
-  if (I+1 == E)
+  if (CSI.Returns.size() == 1)
 return;
 
   // General case: many return statements.
@@ -703,8 +701,7 @@ void Sema::deduceClosureReturnType(Captu
   // We require the return types to strictly match here.
   // Note that we've already done the required promotions as part of
   // processing the return statement.
-  for (; I != E; ++I) {
-const ReturnStmt *RS = *I;
+  for (const ReturnStmt *RS : CSI.Returns) {
 const Expr *RetE = RS->getRetValue();
 
 QualType ReturnType =


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


r335572 - [ubsan] Relax nullability-return for blocks with deduced types

2018-06-25 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Jun 25 19:50:04 2018
New Revision: 335572

URL: http://llvm.org/viewvc/llvm-project?rev=335572=rev
Log:
[ubsan] Relax nullability-return for blocks with deduced types

When the return type of an ObjC-style block literals is deduced, pick
the candidate type with the strictest nullability annotation applicable
to every other candidate.

This suppresses a UBSan false-positive in situations where a too-strict
nullability would be deduced, despite the fact that the returned value
would be implicitly cast to _Nullable.

rdar://41317163

Modified:
cfe/trunk/include/clang/Basic/Specifiers.h
cfe/trunk/lib/Sema/SemaLambda.cpp
cfe/trunk/test/CodeGenObjC/ubsan-nullability.m

Modified: cfe/trunk/include/clang/Basic/Specifiers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Specifiers.h?rev=335572=335571=335572=diff
==
--- cfe/trunk/include/clang/Basic/Specifiers.h (original)
+++ cfe/trunk/include/clang/Basic/Specifiers.h Mon Jun 25 19:50:04 2018
@@ -294,6 +294,12 @@ namespace clang {
 Unspecified
   };
 
+  /// Return true if \p L has a weaker nullability annotation than \p R. The
+  /// ordering is: Unspecified < Nullable < NonNull.
+  inline bool operator<(NullabilityKind L, NullabilityKind R) {
+return uint8_t(L) > uint8_t(R);
+  }
+
   /// Retrieve the spelling of the given nullability kind.
   llvm::StringRef getNullabilitySpelling(NullabilityKind kind,
  bool isContextSensitive = false);

Modified: cfe/trunk/lib/Sema/SemaLambda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLambda.cpp?rev=335572=335571=335572=diff
==
--- cfe/trunk/lib/Sema/SemaLambda.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLambda.cpp Mon Jun 25 19:50:04 2018
@@ -707,8 +707,15 @@ void Sema::deduceClosureReturnType(Captu
 QualType ReturnType =
 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
 if (Context.getCanonicalFunctionResultType(ReturnType) ==
-  Context.getCanonicalFunctionResultType(CSI.ReturnType))
+  Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
+  // Use the return type with the strictest possible nullability 
annotation.
+  auto RetTyNullability = ReturnType->getNullability(Ctx);
+  auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
+  if (BlockNullability &&
+  (!RetTyNullability || *RetTyNullability < *BlockNullability))
+CSI.ReturnType = ReturnType;
   continue;
+}
 
 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
 // TODO: It's possible that the *first* return is the divergent one.

Modified: cfe/trunk/test/CodeGenObjC/ubsan-nullability.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/ubsan-nullability.m?rev=335572=335571=335572=diff
==
--- cfe/trunk/test/CodeGenObjC/ubsan-nullability.m (original)
+++ cfe/trunk/test/CodeGenObjC/ubsan-nullability.m Mon Jun 25 19:50:04 2018
@@ -1,6 +1,6 @@
 // REQUIRES: asserts
-// RUN: %clang_cc1 -x objective-c -emit-llvm -triple 
x86_64-apple-macosx10.10.0 
-fsanitize=nullability-arg,nullability-assign,nullability-return -w %s -o - | 
FileCheck %s
-// RUN: %clang_cc1 -x objective-c++ -emit-llvm -triple 
x86_64-apple-macosx10.10.0 
-fsanitize=nullability-arg,nullability-assign,nullability-return -w %s -o - | 
FileCheck %s
+// RUN: %clang_cc1 -x objective-c -emit-llvm -triple 
x86_64-apple-macosx10.10.0 -fblocks -fobjc-arc 
-fsanitize=nullability-arg,nullability-assign,nullability-return -w %s -o - | 
FileCheck %s
+// RUN: %clang_cc1 -x objective-c++ -emit-llvm -triple 
x86_64-apple-macosx10.10.0 -fblocks -fobjc-arc 
-fsanitize=nullability-arg,nullability-assign,nullability-return -w %s -o - | 
FileCheck %s
 
 // CHECK: [[NONNULL_RV_LOC1:@.*]] = private unnamed_addr global {{.*}} i32 
100, i32 6
 // CHECK: [[NONNULL_ARG_LOC:@.*]] = private unnamed_addr global {{.*}} i32 
204, i32 15 {{.*}} i32 190, i32 23
@@ -177,6 +177,37 @@ void call_A(A *a, int *p) {
 
 void dont_crash(int *_Nonnull p, ...) {}
 
+@protocol NSObject
+- (id)init;
+@end
+@interface NSObject  {}
+@end
+
+#pragma clang assume_nonnull begin
+
+/// Create a "NSObject * _Nonnull" instance.
+NSObject *get_nonnull_error() {
+  // Use nil for convenience. The actual object doesn't matter.
+  return (NSObject *)NULL;
+}
+
+NSObject *_Nullable no_null_return_value_diagnostic(int flag) {
+// CHECK-LABEL: define internal 
{{.*}}no_null_return_value_diagnostic{{i?}}_block_invoke
+// CHECK-NOT: @__ubsan_handle_nullability_return
+  NSObject *_Nullable (^foo)() = ^() {
+if (flag) {
+  // Clang should not infer a nonnull return value for this block when this
+  // call is present.
+  return get_nonnull_error();
+  

r333775 - [Coverage] Remove a test dependency on the itanium ABI

2018-06-01 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Jun  1 10:11:18 2018
New Revision: 333775

URL: http://llvm.org/viewvc/llvm-project?rev=333775=rev
Log:
[Coverage] Remove a test dependency on the itanium ABI

This should address a bot failure:
http://lab.llvm.org:8011/builders/llvm-clang-x86_64-expensive-checks-win/builds/9994/

Modified:
cfe/trunk/test/CoverageMapping/label.cpp

Modified: cfe/trunk/test/CoverageMapping/label.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/label.cpp?rev=333775=333774=333775=diff
==
--- cfe/trunk/test/CoverageMapping/label.cpp (original)
+++ cfe/trunk/test/CoverageMapping/label.cpp Fri Jun  1 10:11:18 2018
@@ -48,7 +48,17 @@ b:   // CHECK-NE
   x = x + 1;
 }
 
- // CHECK-NEXT: main
+// CHECK-NEXT: test3
+#define a b
+void test3() {
+  if (0)
+goto b; // CHECK: Gap,File 0, [[@LINE]]:11 -> [[@LINE+1]]:1 = 
[[retnCount:#[0-9]+]]
+a: // CHECK-NEXT: Expansion,File 0, [[@LINE]]:1 -> [[@LINE]]:2 = [[retnCount]] 
(Expanded file = 1)
+  return; // CHECK-NEXT: File 0, [[@LINE-1]]:2 -> [[@LINE]]:9 = [[retnCount]]
+}
+#undef a
+
+ // CHECK: main
 int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> 
{{[0-9]+}}:2 = #0
   int j = 0;
   for(int i = 0; i < 10; ++i) { // CHECK: File 0, [[@LINE]]:31 -> 
[[@LINE+13]]:4 = #1
@@ -69,12 +79,3 @@ int main() { // CHECK-NE
   test1(0);
   test2(2);
 }
-
-// CHECK-LABEL: _Z5test3v:
-#define a b
-void test3() {
-  if (0)
-goto b; // CHECK: Gap,File 0, [[@LINE]]:11 -> [[@LINE+1]]:1 = 
[[retnCount:#[0-9]+]]
-a: // CHECK-NEXT: Expansion,File 0, [[@LINE]]:1 -> [[@LINE]]:2 = [[retnCount]] 
(Expanded file = 1)
-  return; // CHECK-NEXT: File 0, [[@LINE-1]]:2 -> [[@LINE]]:9 = [[retnCount]]
-}


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


r333715 - [Coverage] End deferred regions before labels, fixes PR35867

2018-05-31 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu May 31 17:37:13 2018
New Revision: 333715

URL: http://llvm.org/viewvc/llvm-project?rev=333715=rev
Log:
[Coverage] End deferred regions before labels, fixes PR35867

A deferred region should end before the start of a label, and should not
extend to the start of the label sub-statement.

Fixes llvm.org/PR35867.

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/label.cpp

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=333715=333714=333715=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Thu May 31 17:37:13 2018
@@ -872,6 +872,7 @@ struct CounterCoverageMappingBuilder
 Counter LabelCount = getRegionCounter(S);
 SourceLocation Start = getStart(S);
 completeTopLevelDeferredRegion(LabelCount, Start);
+completeDeferred(LabelCount, Start);
 // We can't extendRegion here or we risk overlapping with our new region.
 handleFileExit(Start);
 pushRegion(LabelCount, Start);

Modified: cfe/trunk/test/CoverageMapping/label.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/label.cpp?rev=333715=333714=333715=diff
==
--- cfe/trunk/test/CoverageMapping/label.cpp (original)
+++ cfe/trunk/test/CoverageMapping/label.cpp Thu May 31 17:37:13 2018
@@ -69,3 +69,12 @@ int main() { // CHECK-NE
   test1(0);
   test2(2);
 }
+
+// CHECK-LABEL: _Z5test3v:
+#define a b
+void test3() {
+  if (0)
+goto b; // CHECK: Gap,File 0, [[@LINE]]:11 -> [[@LINE+1]]:1 = 
[[retnCount:#[0-9]+]]
+a: // CHECK-NEXT: Expansion,File 0, [[@LINE]]:1 -> [[@LINE]]:2 = [[retnCount]] 
(Expanded file = 1)
+  return; // CHECK-NEXT: File 0, [[@LINE-1]]:2 -> [[@LINE]]:9 = [[retnCount]]
+}


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


r333609 - [Coverage] Discard the last uncompleted deferred region in a decl

2018-05-30 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed May 30 16:35:44 2018
New Revision: 333609

URL: http://llvm.org/viewvc/llvm-project?rev=333609=rev
Log:
[Coverage] Discard the last uncompleted deferred region in a decl

Discard the last uncompleted deferred region in a decl, if one exists.
This prevents lines at the end of a function containing only whitespace
or closing braces from being marked as uncovered, if they follow a
region terminator (return/break/etc).

The previous behavior was to heuristically complete deferred regions at
the end of a decl. In practice this ended up being too brittle for too
little gain. Users would complain that there was no way to reach full
code coverage because whitespace at the end of a function would be
marked uncovered.

rdar://40238228

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

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/deferred-region.cpp
cfe/trunk/test/CoverageMapping/label.cpp
cfe/trunk/test/CoverageMapping/moremacros.c
cfe/trunk/test/CoverageMapping/trycatch.cpp

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=333609=333608=333609=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Wed May 30 16:35:44 2018
@@ -834,22 +834,6 @@ struct CounterCoverageMappingBuilder
 handleFileExit(getEnd(S));
   }
 
-  /// Determine whether the final deferred region emitted in \p Body should be
-  /// discarded.
-  static bool discardFinalDeferredRegionInDecl(Stmt *Body) {
-if (auto *CS = dyn_cast(Body)) {
-  Stmt *LastStmt = CS->body_back();
-  if (auto *IfElse = dyn_cast(LastStmt)) {
-if (auto *Else = dyn_cast_or_null(IfElse->getElse()))
-  LastStmt = Else->body_back();
-else
-  LastStmt = IfElse->getElse();
-  }
-  return dyn_cast_or_null(LastStmt);
-}
-return false;
-  }
-
   void VisitDecl(const Decl *D) {
 assert(!DeferredRegion && "Deferred region never completed");
 
@@ -859,17 +843,13 @@ struct CounterCoverageMappingBuilder
 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body
   return;
 
-Counter ExitCount = propagateCounts(getRegionCounter(Body), Body);
+propagateCounts(getRegionCounter(Body), Body);
 assert(RegionStack.empty() && "Regions entered but never exited");
 
-if (DeferredRegion) {
-  // Complete (or discard) any deferred regions introduced by the last
-  // statement.
-  if (discardFinalDeferredRegionInDecl(Body))
-DeferredRegion = None;
-  else
-popRegions(completeDeferred(ExitCount, getEnd(Body)));
-}
+// Discard the last uncompleted deferred region in a decl, if one exists.
+// This prevents lines at the end of a function containing only whitespace
+// or closing braces from being marked as uncovered.
+DeferredRegion = None;
   }
 
   void VisitReturnStmt(const ReturnStmt *S) {

Modified: cfe/trunk/test/CoverageMapping/deferred-region.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/deferred-region.cpp?rev=333609=333608=333609=diff
==
--- cfe/trunk/test/CoverageMapping/deferred-region.cpp (original)
+++ cfe/trunk/test/CoverageMapping/deferred-region.cpp Wed May 30 16:35:44 2018
@@ -7,11 +7,12 @@
 void foo(int x) {
   if (x == 0) {
 return;
-  } // CHECK: Gap,File 0, [[@LINE]]:4 -> [[@LINE+2]]:2 = (#0 - #1)
-
+  } // CHECK-NOT: Gap,File 0, [[@LINE]]:4
+//< Don't complete the last deferred region in a decl, even though it may
+//< leave some whitespace marked with the same counter as the final return.
 }
 
-// CHECK-NEXT: _Z4foooi:
+// CHECK-LABEL: _Z4foooi:
 void fooo(int x) {
   if (x == 0) {
 return;
@@ -19,7 +20,7 @@ void fooo(int x) {
 
   if (x == 1) {
 return;
-  } // CHECK: Gap,File 0, [[@LINE]]:4 -> [[@LINE+2]]:2 = ((#0 - #1) - #2)
+  } // CHECK-NOT: Gap,File 0, [[@LINE]]:4
 
 }
 
@@ -108,7 +109,7 @@ void weird_if() {
   }
 
   if (false)
-return; // CHECK: Gap,File 0, [[@LINE]]:11 -> [[@LINE+1]]:2
+return; // CHECK-NOT: Gap,File 0, [[@LINE]]:11
 }
 
 // CHECK-LABEL: _Z8for_loopv:
@@ -167,7 +168,18 @@ void gotos() {
   return; // CHECK: [[@LINE]]:3 -> [[@LINE+4]]:2 = (#0 - #1)
 
 out:
-   return; // CHECK: Gap,File 0, [[@LINE]]:8 -> [[@LINE+1]]:2 = 0
+   return; // CHECK-NOT: Gap,File 0, [[@LINE]]:8
+}
+
+// CHECK-LABEL: _Z8switchesv:
+void switches() {
+  int x;
+  switch (x) {
+case 0:
+  return;
+default:
+  return; // CHECK-NOT: Gap,File 0, [[@LINE]]
+  }
 }
 
 #include "deferred-region-helper.h"

Modified: cfe/trunk/test/CoverageMapping/label.cpp
URL: 

Re: r332720 - Move #include manipulation code to new lib/Tooling/Inclusions.

2018-05-18 Thread Vedant Kumar via cfe-commits
> On May 18, 2018, at 11:48 AM, Eric Liu  wrote:
> 
> So I have reverted this with r332751.

Thanks!


> I can't see how this introduced cyclic dependencies in module build, as the 
> dependencies should be clangTooling -> clangFormat -> clangToolingInclusions. 
> I'm wondering if there is any module configurations that I need to update to 
> make this work. Right now, module doesn't seem to make any difference between 
> clangTooling and clangToolingInclusions... I'd appreciate it if someone who 
> knows how clang module build is set up could help take a look.

+ Bruno & David who have more experience in this area than I do.


> Unfortunately, I couldn't reproduce this on my workstation as the module 
> build seemed to be broken due to other errors.

The build is dependent on having a set of modularized system headers -- perhaps 
that's the issue.


> I was seeing a lot of warnings; the clang I used to build llvm was built near 
> HEAD. Maybe my clang is too new?

This sounds a bit suspicious. Can new clang diagnostics land without clean 
stage2 builds? If so, we can look into enabling -Werror on our stage2 bots to 
catch this sort of thing earlier.

vedant

> 
> Thanks,
> Eric
> 
> On Fri, May 18, 2018 at 7:52 PM Eric Liu  > wrote:
> Sorry, I'll look into it right now. Will revert it if I can't find a quick 
> fix.
> 
> On Fri, May 18, 2018, 19:49 Amara Emerson  > wrote:
> Hi Eric,
> 
> Green dragon buildbots have started failing too, e.g.: 
> http://green.lab.llvm.org/green/job/clang-stage2-Rthinlto/10222/ 
> 
> 
> If you don’t have a quick fix can you please revert it.
> 
> Thanks,
> Amara
> 
> 
>> On May 18, 2018, at 7:46 PM, Eric Liu > > wrote:
>> 
>> Hi Vedant,
>> 
>> It seems that your build was not using cmake files in the source tree? 
>> lib/Tooling/Inclusions/ is a (new) standalone library 
>> (clangToolingInclusions, similar to clangToolingCore). You might need update 
>> your build to reflect this change. Let me know if you have any further 
>> question.
>> 
>> Thanks,
>> Eric
>> 
>> On Fri, May 18, 2018 at 6:41 PM Vedant Kumar > > wrote:
>> Hi Eric,
>> 
>> I think there might be a cyclic dependency issue here, possibly one that's 
>> only visible with LLVM_ENABLE_MODULES=On. I see:
>> 
>> While building module 'Clang_Tooling' imported from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/lib/Tooling/Execution.cpp:10: 
>> 
>> While building module 'Clang_Format' imported from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h:19:
>>
>> In file included from :1:   
>>  
>>
>> /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Format/Format.h:20:10:
>>  fatal error: cyclic dependency in module 'Clang_Tooling': Clang_Tooling $> 
>> Clang_Format -> Clang_Tooling
>> 
>> #include "clang/Tooling/Inclusions/IncludeStyle.h"
>>  ^  
>> While building module 'Clang_Tooling' imported from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:
>> In file included from :22:  
>> 
>> In file included from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringAction.h:14:
>> In file included from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h:14:
>> In file included from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h:16:
>> In file included from /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h:14:
>> /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h:19:10:
>>  fatal error: could not build module 'Clang_Format'
>> #include "clang/Format/Format.h"
>>  ^~~
>> /Users/vsk/src/llvm.org 
>> -master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:10: 
>> fatal error: could not build module 'Clang_Tooling'
>> #include "clang/Tooling/Execution.h" 
>>
>>  ^~~
>> 3 errors generated.
>> 
>> Could you take a look?
>> 
>> thanks,
>> 

Re: r332720 - Move #include manipulation code to new lib/Tooling/Inclusions.

2018-05-18 Thread Vedant Kumar via cfe-commits
I wiped my build directory, updated to r332734 and rebuilt, but hit the same 
error while building check-clang.

For completeness, I did:

$ cmake -G Ninja /Users/vsk/src/llvm.org-master/llvm -DCMAKE_BUILD_TYPE=Release 
-DLLVM_ENABLE_ASSERTIONS=On -DCLANG_ENABLE_ARCMT=Off -DCLANG_
ENABLE_STATIC_ANALYZER=Off -DLLVM_TARGETS_TO_BUILD="X86;ARM;AArch64" 
-DLLVM_ENABLE_MODULES=On
$ ninja check-clang

Are you able to reproduce the issue?

vedant

> On May 18, 2018, at 9:46 AM, Eric Liu  wrote:
> 
> Hi Vedant,
> 
> It seems that your build was not using cmake files in the source tree? 
> lib/Tooling/Inclusions/ is a (new) standalone library 
> (clangToolingInclusions, similar to clangToolingCore). You might need update 
> your build to reflect this change. Let me know if you have any further 
> question.
> 
> Thanks,
> Eric
> 
> On Fri, May 18, 2018 at 6:41 PM Vedant Kumar  wrote:
> Hi Eric,
> 
> I think there might be a cyclic dependency issue here, possibly one that's 
> only visible with LLVM_ENABLE_MODULES=On. I see:
> 
> While building module 'Clang_Tooling' imported from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/lib/Tooling/Execution.cpp:10: 
> 
> While building module 'Clang_Format' imported from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h:19:
>
> In file included from :1:
>   
>  
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Format/Format.h:20:10:
>  fatal error: cyclic dependency in module 'Clang_Tooling': Clang_Tooling $> 
> Clang_Format -> Clang_Tooling 
>
> #include "clang/Tooling/Inclusions/IncludeStyle.h"
>  ^  
> While building module 'Clang_Tooling' imported from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:
> In file included from :22:   
>
> In file included from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringAction.h:14:
> In file included from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h:14:
> In file included from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h:16:
> In file included from 
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h:14:
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h:19:10:
>  fatal error: could not build module 'Clang_Format'
> #include "clang/Format/Format.h"
>  ^~~
> /Users/vsk/src/llvm.org-master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:10:
>  fatal error: could not build module 'Clang_Tooling'
> #include "clang/Tooling/Execution.h"  
>   
>  ^~~
> 3 errors generated.
> 
> Could you take a look?
> 
> thanks,
> vedant
> 
> > On May 18, 2018, at 7:16 AM, Eric Liu via cfe-commits 
> >  wrote:
> > 
> > Author: ioeric
> > Date: Fri May 18 07:16:37 2018
> > New Revision: 332720
> > 
> > URL: http://llvm.org/viewvc/llvm-project?rev=332720=rev
> > Log:
> > Move #include manipulation code to new lib/Tooling/Inclusions.
> > 
> > Summary:
> > clangToolingCore is linked into almost everything (incl. clang), but
> > not few tools need #include manipulation at this point. So pull this into a
> > separate library in Tooling.
> > 
> > Reviewers: ilya-biryukov
> > 
> > Subscribers: klimek, mgorny, cfe-commits, thakis
> > 
> > Differential Revision: https://reviews.llvm.org/D47068
> > 
> > Added:
> >cfe/trunk/include/clang/Tooling/Inclusions/
> >cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h
> >  - copied, changed from r332717, 
> > cfe/trunk/include/clang/Tooling/Core/HeaderIncludes.h
> >cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h
> >  - copied, changed from r332717, 
> > cfe/trunk/include/clang/Tooling/Core/IncludeStyle.h
> >cfe/trunk/lib/Tooling/Inclusions/
> >cfe/trunk/lib/Tooling/Inclusions/CMakeLists.txt
> >  - copied, changed from r332717, 
> > cfe/trunk/lib/Tooling/Core/CMakeLists.txt
> >cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
> >  - copied, changed from r332717, 
> > cfe/trunk/lib/Tooling/Core/HeaderIncludes.cpp
> >cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
> >  - copied, changed from r332717, 
> > cfe/trunk/lib/Tooling/Core/IncludeStyle.cpp
> > Removed:
> >cfe/trunk/include/clang/Tooling/Core/HeaderIncludes.h
> >

Re: r332720 - Move #include manipulation code to new lib/Tooling/Inclusions.

2018-05-18 Thread Vedant Kumar via cfe-commits
Hi Eric,

I think there might be a cyclic dependency issue here, possibly one that's only 
visible with LLVM_ENABLE_MODULES=On. I see:

While building module 'Clang_Tooling' imported from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:   
  
While building module 'Clang_Format' imported from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h:19:
   
In file included from :1:  
 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Format/Format.h:20:10:
 fatal error: cyclic dependency in module 'Clang_Tooling': Clang_Tooling $> 
Clang_Format -> Clang_Tooling   
 
#include "clang/Tooling/Inclusions/IncludeStyle.h"
 ^  
While building module 'Clang_Tooling' imported from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:
In file included from :22: 
 
In file included from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringAction.h:14:
In file included from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRules.h:14:
In file included from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h:16:
In file included from 
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/RefactoringResultConsumer.h:14:
/Users/vsk/src/llvm.org-master/llvm/tools/clang/include/clang/Tooling/Refactoring/AtomicChange.h:19:10:
 fatal error: could not build module 'Clang_Format'
#include "clang/Format/Format.h"
 ^~~
/Users/vsk/src/llvm.org-master/llvm/tools/clang/lib/Tooling/Execution.cpp:10:10:
 fatal error: could not build module 'Clang_Tooling'
#include "clang/Tooling/Execution.h"
 ^~~
3 errors generated.

Could you take a look?

thanks,
vedant

> On May 18, 2018, at 7:16 AM, Eric Liu via cfe-commits 
>  wrote:
> 
> Author: ioeric
> Date: Fri May 18 07:16:37 2018
> New Revision: 332720
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=332720=rev
> Log:
> Move #include manipulation code to new lib/Tooling/Inclusions.
> 
> Summary:
> clangToolingCore is linked into almost everything (incl. clang), but
> not few tools need #include manipulation at this point. So pull this into a
> separate library in Tooling.
> 
> Reviewers: ilya-biryukov
> 
> Subscribers: klimek, mgorny, cfe-commits, thakis
> 
> Differential Revision: https://reviews.llvm.org/D47068
> 
> Added:
>cfe/trunk/include/clang/Tooling/Inclusions/
>cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h
>  - copied, changed from r332717, 
> cfe/trunk/include/clang/Tooling/Core/HeaderIncludes.h
>cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h
>  - copied, changed from r332717, 
> cfe/trunk/include/clang/Tooling/Core/IncludeStyle.h
>cfe/trunk/lib/Tooling/Inclusions/
>cfe/trunk/lib/Tooling/Inclusions/CMakeLists.txt
>  - copied, changed from r332717, cfe/trunk/lib/Tooling/Core/CMakeLists.txt
>cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
>  - copied, changed from r332717, 
> cfe/trunk/lib/Tooling/Core/HeaderIncludes.cpp
>cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
>  - copied, changed from r332717, 
> cfe/trunk/lib/Tooling/Core/IncludeStyle.cpp
> Removed:
>cfe/trunk/include/clang/Tooling/Core/HeaderIncludes.h
>cfe/trunk/include/clang/Tooling/Core/IncludeStyle.h
>cfe/trunk/lib/Tooling/Core/HeaderIncludes.cpp
>cfe/trunk/lib/Tooling/Core/IncludeStyle.cpp
> Modified:
>cfe/trunk/include/clang/Format/Format.h
>cfe/trunk/lib/Format/CMakeLists.txt
>cfe/trunk/lib/Format/Format.cpp
>cfe/trunk/lib/Tooling/CMakeLists.txt
>cfe/trunk/lib/Tooling/Core/CMakeLists.txt
>cfe/trunk/unittests/Tooling/HeaderIncludesTest.cpp
> 
> Modified: cfe/trunk/include/clang/Format/Format.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=332720=332719=332720=diff
> ==
> --- cfe/trunk/include/clang/Format/Format.h (original)
> +++ cfe/trunk/include/clang/Format/Format.h Fri May 18 07:16:37 2018
> @@ -16,8 +16,8 @@
> #define LLVM_CLANG_FORMAT_FORMAT_H
> 
> #include "clang/Basic/LangOptions.h"
> -#include "clang/Tooling/Core/IncludeStyle.h"
> #include "clang/Tooling/Core/Replacement.h"
> +#include "clang/Tooling/Inclusions/IncludeStyle.h"
> #include "llvm/ADT/ArrayRef.h"
> #include "llvm/Support/Regex.h"
> #include 
> 

Re: r330068 - [Serialization] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC).

2018-04-13 Thread Vedant Kumar via cfe-commits
I've gone ahead and reverted this in r330080.

I tested this with "./bin/lldb-dotest -p TestForwardDecl", and it no longer 
asserts, etc.

@Eugene, regarding the specifics of this commit, there are a number of 
refactors here that don't make sense. E.g there's no need to create a reference 
to a StringRef, it's already an immutable reference :).

Stepping back a bit, I'm asking you to please stop committing large refactors 
of code you don't have a deep familiarity with, or plans to work on. I've asked 
you this before, when changes you made in lib/ProfileData caused downstream 
breakage. I'm repeating the request now. These sorts of changes carry more risk 
than I'm comfortable with, without offering up much reward in return. Please, 
enough.

thanks,
vedant

> On Apr 13, 2018, at 6:42 PM, Davide Italiano <ditali...@apple.com> wrote:
> 
> The amount of churn this patches introduces is very large for a very small 
> gain.
> Other than basically causing to every downstream consumer with private clang 
> changes a large amount of pain, it also introduced a bug (which shows up only 
> on lldb bots).
> I really think we should have a policy that these commits shouldn’t be 
> encouraged. At some point I and Chandler discussed this on IRC, but I’m not 
> sure this went anywhere.
> 
> In general, large refactoring of code not properly understood is causing more 
> harm to the project than good. We’re going to revert this now, and I would 
> like to kick off a discussion about this in the future.
> 
> Thanks,
> 
> —
> Davide
> 
>> On Apr 13, 2018, at 18:36, Vedant Kumar <v...@apple.com> wrote:
>> 
>> + Davide
>> 
>>> On Apr 13, 2018, at 6:36 PM, Vedant Kumar via cfe-commits 
>>> <cfe-commits@lists.llvm.org> wrote:
>>> 
>>> This is breaking the lldb bots with assertion failures:
>>> 
>>> http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake/
>>> http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake/6341/
>>> 
>>> stderr: Assertion failed: (M && "imported decl from no module file"), 
>>> function loadPendingDeclChain, file 
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp,
>>>  line 3861.
>>> Stack dump:
>>> 0.  Program arguments: 
>>> /Users/vsk/src/builds/llvm.org-lldbsan-RA/bin/clang-7 -cc1 -triple 
>>> x86_64-apple-macosx10.13.0 -Wdeprecated-objc-isa-usage 
>>> -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free 
>>> -main-file-name main.m -mrelocation-model pic -pic-level 2 -mthread-model 
>>> posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu penryn 
>>> -dwarf-column-info -dwarf-ext-refs -fmodule-format=obj 
>>> -debug-info-kind=standalone -dwarf-version=4 -debugger-tuning=lldb 
>>> -target-linker-version 405.15 -coverage-notes-file 
>>> /Users/vsk/src/builds/llvm.org-lldbsan-RA/lldb-test-build.noindex/lang/objc/forward-decl/TestForwardDecl.test_expr_gmodules/main.gcno
>>>  -resource-dir /Users/vsk/src/builds/llvm.org-lldbsan-RA/lib/clang/7.0.0 
>>> -include 
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/../../../make/test_common.h
>>>  -isysroot 
>>> /Volumes/Xcode10A144_m18A232_i16A233_t16J228_w16R229_XcodeInternals_ASan_30GB/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk
>>>  -I 
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/../../../make/../../../../../include
>>>  -I 
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/
>>>  -I 
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/../../../make/
>>>  -O0 -fdebug-compilation-dir 
>>> /Users/vsk/src/builds/llvm.org-lldbsan-RA/lldb-test-build.noindex/lang/objc/forward-decl/TestForwardDecl.test_expr_gmodules
>>>  -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fno-builtin 
>>> -fblocks -fencode-extended-block-signature -fmodules -fimplicit-module-maps 
>>> -fmodules-cache-path=module-cache -fobjc-runtime=macosx-10.13.0 
>>> -fobjc-exceptions -fexceptions -fmax-type-align=16 
>>> -fdiagnostics-show-option -o main.o -x objective-c 
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m
>>>  
>>> 1.  
>>> /Users/vsk/src/llvm.org-lldbsan/llvm/tools/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h:10:10:
>>&

r330080 - Revert "[Serialization] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC)."

2018-04-13 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Apr 13 18:40:48 2018
New Revision: 330080

URL: http://llvm.org/viewvc/llvm-project?rev=330080=rev
Log:
Revert "[Serialization] Fix some Clang-tidy modernize and Include What You Use 
warnings; other minor fixes (NFC)."

This reverts commit r330068. It breaks the lldb bots due to assertion
failures (more details on cfe-commits).

http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake/
http://lab.llvm.org:8080/green/view/LLDB/job/lldb-cmake/6341/

stderr: Assertion failed: (M && "imported decl from no module file"), function 
loadPendingDeclChain, file 
/Users/vsk/src/llvm.org-lldbsan/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp,
 line 3861.

Modified:
cfe/trunk/lib/Serialization/ASTReader.cpp

Modified: cfe/trunk/lib/Serialization/ASTReader.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTReader.cpp?rev=330080=330079=330080=diff
==
--- cfe/trunk/lib/Serialization/ASTReader.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTReader.cpp Fri Apr 13 18:40:48 2018
@@ -71,7 +71,6 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Lex/Token.h"
-#include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/ObjCMethodList.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/Sema.h"
@@ -98,11 +97,11 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/ADT/iterator_range.h"
-#include "llvm/Bitcode/BitCodes.h"
 #include "llvm/Bitcode/BitstreamReader.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compression.h"
@@ -134,8 +133,8 @@
 #include 
 
 using namespace clang;
-using namespace serialization;
-using namespace reader;
+using namespace clang::serialization;
+using namespace clang::serialization::reader;
 using llvm::BitstreamCursor;
 
 
//===--===//
@@ -464,7 +463,7 @@ static bool checkDiagnosticGroupMappings
   // errors because of options like -Werror.
   DiagnosticsEngine *MappingSources[] = { ,  };
 
-  for (auto *MappingSource : MappingSources) {
+  for (DiagnosticsEngine *MappingSource : MappingSources) {
 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
   diag::kind DiagID = DiagIDMappingPair.first;
   Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
@@ -582,9 +581,9 @@ static void
 collectMacroDefinitions(const PreprocessorOptions ,
 MacroDefinitionsMap ,
 SmallVectorImpl *MacroNames = nullptr) {
-  for (const auto  : PPOpts.Macros) {
-StringRef Macro = I.first;
-bool IsUndef = I.second;
+  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
+StringRef Macro = PPOpts.Macros[I].first;
+bool IsUndef = PPOpts.Macros[I].second;
 
 std::pair MacroPair = Macro.split('=');
 StringRef MacroName = MacroPair.first;
@@ -635,8 +634,9 @@ static bool checkPreprocessorOptions(con
   SmallVector ExistingMacroNames;
   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, );
 
-  for (auto MacroName : ExistingMacroNames) {
+  for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
 // Dig out the macro definition in the existing preprocessor options.
+StringRef MacroName = ExistingMacroNames[I];
 std::pair Existing = ExistingMacros[MacroName];
 
 // Check whether we know anything about this macro name or not.
@@ -702,7 +702,8 @@ static bool checkPreprocessorOptions(con
   }
 
   // Compute the #include and #include_macros lines we need.
-  for (const auto  : ExistingPPOpts.Includes) {
+  for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
+StringRef File = ExistingPPOpts.Includes[I];
 if (File == ExistingPPOpts.ImplicitPCHInclude)
   continue;
 
@@ -715,7 +716,8 @@ static bool checkPreprocessorOptions(con
 SuggestedPredefines += "\"\n";
   }
 
-  for (const auto  : ExistingPPOpts.MacroIncludes) {
+  for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
+StringRef File = ExistingPPOpts.MacroIncludes[I];
 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
   File)
 != PPOpts.MacroIncludes.end())
@@ -853,14 +855,14 @@ ASTSelectorLookupTrait::ReadData(Selecto
 
   // Load instance methods
   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
-if (auto *Method = Reader.GetLocalDeclAs(
+if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs(
 F, endian::readNext(d)))
   Result.Instance.push_back(Method);
   }
 
   // Load factory methods
   for (unsigned I = 0; I != NumFactoryMethods; ++I) 

r330077 - [Driver] Export profiling symbols for -exported_symbols_list

2018-04-13 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Apr 13 16:43:59 2018
New Revision: 330077

URL: http://llvm.org/viewvc/llvm-project?rev=330077=rev
Log:
[Driver] Export profiling symbols for -exported_symbols_list

When profiling is enabled and -exported_symbols_list is specified for
the Darwin linker, export the requisite set of profiling symbols.

rdar://39427167

Modified:
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/test/Driver/darwin-ld.c

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=330077=330076=330077=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Fri Apr 13 16:43:59 2018
@@ -988,6 +988,8 @@ StringRef Darwin::getOSLibraryNameSuffix
 /// Check if the link command contains a symbol export directive.
 static bool hasExportSymbolDirective(const ArgList ) {
   for (Arg *A : Args) {
+if (A->getOption().matches(options::OPT_exported__symbols__list))
+  return true;
 if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
 !A->getOption().matches(options::OPT_Xlinker))
   continue;

Modified: cfe/trunk/test/Driver/darwin-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/darwin-ld.c?rev=330077=330076=330077=diff
==
--- cfe/trunk/test/Driver/darwin-ld.c (original)
+++ cfe/trunk/test/Driver/darwin-ld.c Fri Apr 13 16:43:59 2018
@@ -356,6 +356,8 @@
 // RUN: FileCheck -check-prefix=LINK_PROFILE_FIRST %s < %t.log
 // LINK_PROFILE_FIRST: {{ld(.exe)?"}} 
"{{[^"]+}}libclang_rt.profile_{{[a-z]+}}.a"
 
+// RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate 
-exported_symbols_list /dev/null -### %t.o 2> %t.log
+// RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate 
-Wl,-exported_symbols_list,/dev/null -### %t.o 2> %t.log
 // RUN: FileCheck -check-prefix=PROFILE_EXPORT %s < %t.log
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate 
-Wl,-exported_symbol,foo -### %t.o 2> %t.log


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


r327317 - Check that ubsan is the only supported sanitizer on OpenBSD

2018-03-12 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Mar 12 12:18:51 2018
New Revision: 327317

URL: http://llvm.org/viewvc/llvm-project?rev=327317=rev
Log:
Check that ubsan is the only supported sanitizer on OpenBSD

Patch by David Carlier!

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

Modified:
cfe/trunk/test/Driver/fsanitize.c

Modified: cfe/trunk/test/Driver/fsanitize.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fsanitize.c?rev=327317=327316=327317=diff
==
--- cfe/trunk/test/Driver/fsanitize.c (original)
+++ cfe/trunk/test/Driver/fsanitize.c Mon Mar 12 12:18:51 2018
@@ -388,6 +388,25 @@
 // RUN: %clang -target armv7-apple-ios7 -miphoneos-version-min=7.0 
-fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-IOS
 // CHECK-ASAN-IOS: -fsanitize=address
 
+// RUN %clang -target i386-pc-openbsd -fsanitize=undefined %s -### 2>&1 | 
FileCheck --check-prefix=CHECK-UBSAN-OPENBSD
+// CHECK-UBSAN-OPENBSD: -fsanitize=undefined
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=address %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-ASAN-OPENBSD
+// CHECK-ASAN-OPENBSD: unsupported option '-fsanitize=address' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-OPENBSD
+// CHECK-LSAN-OPENBSD: unsupported option '-fsanitize=leak' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-OPENBSD
+// CHECK-TSAN-OPENBSD: unsupported option '-fsanitize=thread' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=memory %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-MSAN-OPENBSD
+// CHECK-MSAN-OPENBSD: unsupported option '-fsanitize=memory' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-cache-frag %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD
+// RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-working-set %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD
+// CHECK-ESAN-OPENBSD: error: unsupported option 
'-fsanitize=efficiency-{{.*}}' for target 'i386-pc-openbsd'
+
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 


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


[libcxx] r327064 - Low-hanging fruit optimization in string::__move_assign().

2018-03-08 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Mar  8 13:15:26 2018
New Revision: 327064

URL: http://llvm.org/viewvc/llvm-project?rev=327064=rev
Log:
Low-hanging fruit optimization in string::__move_assign().

shrink_to_fit() ends up doing a lot work to get information that we
already know since we just called clear(). This change seems concise
enough to be worth the couple extra lines and my benchmarks show that it
is indeed a pretty decent win. It looks like the same thing is going on
twice in __copy_assign_alloc(), but I didn't want to go overboard since
this is my first contribution to llvm/libc++.

Patch by Timothy VanSlyke!

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

Added:

libcxx/trunk/test/libcxx/strings/basic.string/string.modifiers/clear_and_shrink_db1.pass.cpp
Modified:
libcxx/trunk/include/string

Modified: libcxx/trunk/include/string
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/string?rev=327064=327063=327064=diff
==
--- libcxx/trunk/include/string (original)
+++ libcxx/trunk/include/string Thu Mar  8 13:15:26 2018
@@ -1257,6 +1257,8 @@ public:
 
 _LIBCPP_INLINE_VISIBILITY bool __invariants() const;
 
+_LIBCPP_INLINE_VISIBILITY void __clear_and_shrink();
+
 _LIBCPP_INLINE_VISIBILITY
 bool __is_long() const _NOEXCEPT
 {return bool(__r_.first().__s.__size_ & __short_mask);}
@@ -1426,16 +1428,14 @@ private:
 {
 if (!__str.__is_long())
 {
-clear();
-shrink_to_fit();
+__clear_and_shrink();
 __alloc() = __str.__alloc();
 }
 else
 {
 allocator_type __a = __str.__alloc();
 pointer __p = __alloc_traits::allocate(__a, 
__str.__get_long_cap());
-clear();
-shrink_to_fit();
+__clear_and_shrink();
 __alloc() = _VSTD::move(__a);
 __set_long_pointer(__p);
 __set_long_cap(__str.__get_long_cap());
@@ -2125,8 +2125,7 @@ basic_string<_CharT, _Traits, _Allocator
 _NOEXCEPT_(is_nothrow_move_assignable::value)
 #endif
 {
-clear();
-shrink_to_fit();
+__clear_and_shrink();
 __r_.first() = __str.__r_.first();
 __move_assign_alloc(__str);
 __str.__zero();
@@ -3579,6 +3578,22 @@ basic_string<_CharT, _Traits, _Allocator
 return true;
 }
 
+// __clear_and_shrink
+
+template
+inline _LIBCPP_INLINE_VISIBILITY
+void 
+basic_string<_CharT, _Traits, _Allocator>::__clear_and_shrink()
+{
+clear();
+if(__is_long())
+{
+__alloc_traits::deallocate(__alloc(), __get_long_pointer(), capacity() 
+ 1);
+__set_long_cap(0);
+__set_short_size(0);
+}
+} 
+
 // operator==
 
 template

Added: 
libcxx/trunk/test/libcxx/strings/basic.string/string.modifiers/clear_and_shrink_db1.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/libcxx/strings/basic.string/string.modifiers/clear_and_shrink_db1.pass.cpp?rev=327064=auto
==
--- 
libcxx/trunk/test/libcxx/strings/basic.string/string.modifiers/clear_and_shrink_db1.pass.cpp
 (added)
+++ 
libcxx/trunk/test/libcxx/strings/basic.string/string.modifiers/clear_and_shrink_db1.pass.cpp
 Thu Mar  8 13:15:26 2018
@@ -0,0 +1,48 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// 
+
+// Call __clear_and_shrink() and ensure string invariants hold
+
+#if _LIBCPP_DEBUG >= 1
+
+#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
+
+#include 
+#include 
+
+int main()
+{
+std::string l = "Long string so that allocation definitely, for sure, 
absolutely happens. Probably.";
+std::string s = "short";
+
+assert(l.__invariants());
+assert(s.__invariants());
+
+s.__clear_and_shrink();
+assert(s.__invariants());
+assert(s.size() == 0);
+
+{ 
+std::string::size_type cap = l.capacity();
+l.__clear_and_shrink();
+assert(l.__invariants());
+assert(l.size() == 0);
+assert(l.capacity() < cap);
+}
+}
+
+#else
+
+int main()
+{
+}
+
+#endif


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


r325319 - [Coverage] Handle break/continue outside of loop bodies

2018-02-16 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Feb 15 23:59:43 2018
New Revision: 325319

URL: http://llvm.org/viewvc/llvm-project?rev=325319=rev
Log:
[Coverage] Handle break/continue outside of loop bodies

Teach the coverage mapping logic to handle break or continue statements
within for loop increments.

Fixes llvm.org/PR36406.

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/break.c

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=325319=325318=325319=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Thu Feb 15 23:59:43 2018
@@ -982,20 +982,28 @@ struct CounterCoverageMappingBuilder
 Counter ParentCount = getRegion().getCounter();
 Counter BodyCount = getRegionCounter(S);
 
+// The loop increment may contain a break or continue.
+if (S->getInc())
+  BreakContinueStack.emplace_back();
+
 // Handle the body first so that we can get the backedge count.
-BreakContinueStack.push_back(BreakContinue());
+BreakContinueStack.emplace_back();
 extendRegion(S->getBody());
 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
-BreakContinue BC = BreakContinueStack.pop_back_val();
+BreakContinue BodyBC = BreakContinueStack.pop_back_val();
 
 // The increment is essentially part of the body but it needs to include
 // the count for all the continue statements.
-if (const Stmt *Inc = S->getInc())
-  propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
+BreakContinue IncrementBC;
+if (const Stmt *Inc = S->getInc()) {
+  propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
+  IncrementBC = BreakContinueStack.pop_back_val();
+}
 
 // Go back to handle the condition.
-Counter CondCount =
-addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
+Counter CondCount = addCounters(
+addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
+IncrementBC.ContinueCount);
 if (const Expr *Cond = S->getCond()) {
   propagateCounts(CondCount, Cond);
   adjustForOutOfOrderTraversal(getEnd(S));
@@ -1007,8 +1015,8 @@ struct CounterCoverageMappingBuilder
 if (Gap)
   fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
 
-Counter OutCount =
-addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
+Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
+   subtractCounters(CondCount, BodyCount));
 if (OutCount != ParentCount)
   pushRegion(OutCount);
   }

Modified: cfe/trunk/test/CoverageMapping/break.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/break.c?rev=325319=325318=325319=diff
==
--- cfe/trunk/test/CoverageMapping/break.c (original)
+++ cfe/trunk/test/CoverageMapping/break.c Thu Feb 15 23:59:43 2018
@@ -31,3 +31,14 @@ int main() { // CHECK: File 0, [
 ++cnt;
   }
 }
+
+// CHECK-LABEL: break_continue_in_increment:
+// CHECK:  [[@LINE+6]]:11 -> [[@LINE+6]]:45 = #1
+// CHECK:  [[@LINE+5]]:18 -> [[@LINE+5]]:19 = #1
+// CHECK:  [[@LINE+4]]:21 -> [[@LINE+4]]:26 = #2
+// CHECK:  [[@LINE+3]]:33 -> [[@LINE+3]]:41 = (#1 - #2)
+// CHECK:  [[@LINE+3]]:5 -> [[@LINE+3]]:6 = #1
+void break_continue_in_increment(int x) {
+  for (;; ({ if (x) break; else continue; }))
+;
+}


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


r324527 - [clang-import-test] Run clang-format, NFC

2018-02-07 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Feb  7 13:17:22 2018
New Revision: 324527

URL: http://llvm.org/viewvc/llvm-project?rev=324527=rev
Log:
[clang-import-test] Run clang-format, NFC

I ran across clang-import-test while looking into testing for lldb.
There shouldn't be any harm in running clang-format over it.

Modified:
cfe/trunk/tools/clang-import-test/clang-import-test.cpp

Modified: cfe/trunk/tools/clang-import-test/clang-import-test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-import-test/clang-import-test.cpp?rev=324527=324526=324527=diff
==
--- cfe/trunk/tools/clang-import-test/clang-import-test.cpp (original)
+++ cfe/trunk/tools/clang-import-test/clang-import-test.cpp Wed Feb  7 13:17:22 
2018
@@ -50,9 +50,10 @@ static llvm::cl::opt
 Direct("direct", llvm::cl::Optional,
llvm::cl::desc("Use the parsed declarations without indirection"));
 
-static llvm::cl::opt
-UseOrigins("use-origins", llvm::cl::Optional,
-   llvm::cl::desc("Use DeclContext origin information for more 
accurate lookups"));  
+static llvm::cl::opt UseOrigins(
+"use-origins", llvm::cl::Optional,
+llvm::cl::desc(
+"Use DeclContext origin information for more accurate lookups"));
 
 static llvm::cl::list
 ClangArgs("Xcc", llvm::cl::ZeroOrMore,
@@ -225,7 +226,7 @@ std::unique_ptr BuildCode
   CI.getDiagnostics(), ModuleName, CI.getHeaderSearchOpts(),
   CI.getPreprocessorOpts(), CI.getCodeGenOpts(), LLVMCtx));
 }
-} // end namespace
+} // namespace init_convenience
 
 namespace {
 
@@ -261,8 +262,8 @@ void AddExternalSource(CIAndOrigins ,
   {CI.getASTContext(), CI.getFileManager()});
   llvm::SmallVector Sources;
   for (CIAndOrigins  : Imports)
-Sources.push_back(
-{Import.getASTContext(), Import.getFileManager(), 
Import.getOriginMap()});
+Sources.push_back({Import.getASTContext(), Import.getFileManager(),
+   Import.getOriginMap()});
   auto ES = llvm::make_unique(Target, Sources);
   CI.getASTContext().setExternalSource(ES.release());
   CI.getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage();
@@ -334,8 +335,8 @@ llvm::Expected Parse(const
 void Forget(CIAndOrigins , llvm::MutableArrayRef Imports) {
   llvm::SmallVector Sources;
   for (CIAndOrigins  : Imports)
-Sources.push_back(
-{Import.getASTContext(), Import.getFileManager(), 
Import.getOriginMap()});
+Sources.push_back({Import.getASTContext(), Import.getFileManager(),
+   Import.getOriginMap()});
   ExternalASTSource *Source = CI.CI->getASTContext().getExternalSource();
   auto *Merger = static_cast(Source);
   Merger->RemoveSources(Sources);


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


Re: [PATCH] D35338: Add the -fdestroy-globals flag

2018-01-26 Thread Vedant Kumar via cfe-commits
Yeah, I think we have internal users who would be happy to use this flag as 
well.

Stepping back a bit. It's been a while since I followed the discussion on 
cfe-dev, but I don't recall there being any objections to the flag name or to 
using it for particular targets.

IIRC the objections are about deviating from the language standard. I'm not 
sure where I stand on the issue. I think if there's evidence -fdestroy-globals 
gives significant space savings, I'm happy to defer to users.

vedant

> On Jan 26, 2018, at 1:10 PM, Nico Weber via cfe-commits 
>  wrote:
> 
> I'd love to use this flag in non-firmware code FWIW.
> 
> On Fri, Jan 26, 2018 at 4:07 PM, Ian Tessier via Phabricator via cfe-commits 
> > wrote:
> itessier added a comment.
> 
> > That seems like a nice win and I like the convenience of this approach. 
> > That said I've just remembered that there's a thread on cfe-dev about this:
> > [RFC] Suppress C++ static destructor registration
> > I don't think a consensus was reached. From what I gather, some people 
> > think that the convenience of this flag makes it worth adding to clang, 
> > while others think that adding a non-standard compiler-specific flag is 
> > asking for trouble.
> 
> Given that firmware is a much different (or controlled) environment than a 
> binary running on a full blown OS, would it be acceptable to name the flag 
> -fbaremetal-destroy-globals, and only allow its use if the target triple's OS 
> is set to none (e.g.: arm-**none**-eabi)?
> 
> 
> https://reviews.llvm.org/D35338 
> 
> 
> 
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org 
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits 
> 
> 
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

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


r322729 - [Parse] Forward brace locations to TypeConstructExpr

2018-01-17 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Jan 17 10:53:51 2018
New Revision: 322729

URL: http://llvm.org/viewvc/llvm-project?rev=322729=rev
Log:
[Parse] Forward brace locations to TypeConstructExpr

When parsing C++ type construction expressions with list initialization,
forward the locations of the braces to Sema.

Without these locations, the code coverage pass crashes on the given test
case, because the pass relies on getLocEnd() returning a valid location.

Here is what this patch does in more detail:

  - Forwards init-list brace locations to Sema (ParseExprCXX),
  - Builds an InitializationKind with these locations (SemaExprCXX), and
  - Uses these locations for constructor initialization (SemaInit).

The remaining changes fall out of introducing a new overload for
creating direct-list InitializationKinds.

Testing: check-clang, and a stage2 coverage-enabled build of clang with
asserts enabled.

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

Modified:
cfe/trunk/include/clang/AST/ExprCXX.h
cfe/trunk/include/clang/Sema/Initialization.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/lib/Parse/ParseExprCXX.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/lib/Sema/TreeTransform.h
cfe/trunk/test/CoverageMapping/classtemplate.cpp
cfe/trunk/test/SemaCXX/sourceranges.cpp

Modified: cfe/trunk/include/clang/AST/ExprCXX.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ExprCXX.h?rev=322729=322728=322729=diff
==
--- cfe/trunk/include/clang/AST/ExprCXX.h (original)
+++ cfe/trunk/include/clang/AST/ExprCXX.h Wed Jan 17 10:53:51 2018
@@ -1504,6 +1504,9 @@ public:
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
 
+  /// Determine whether this expression models list-initialization.
+  bool isListInitialization() const { return LParenLoc.isInvalid(); }
+
   SourceLocation getLocStart() const LLVM_READONLY;
   SourceLocation getLocEnd() const LLVM_READONLY;
 

Modified: cfe/trunk/include/clang/Sema/Initialization.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Initialization.h?rev=322729=322728=322729=diff
==
--- cfe/trunk/include/clang/Sema/Initialization.h (original)
+++ cfe/trunk/include/clang/Sema/Initialization.h Wed Jan 17 10:53:51 2018
@@ -539,8 +539,15 @@ public:
   }
 
   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
-return InitializationKind(IK_DirectList, IC_Normal,
-  InitLoc, InitLoc, InitLoc);
+return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc,
+  InitLoc);
+  }
+
+  static InitializationKind CreateDirectList(SourceLocation InitLoc,
+ SourceLocation LBraceLoc,
+ SourceLocation RBraceLoc) {
+return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc,
+  RBraceLoc);
   }
 
   /// \brief Create a direct initialization due to a cast that isn't a C-style 
@@ -598,7 +605,8 @@ public:
   Expr *Init) {
 if (!Init) return CreateDefault(Loc);
 if (!DirectInit) return CreateCopy(Loc, Init->getLocStart());
-if (isa(Init)) return CreateDirectList(Loc);
+if (isa(Init))
+  return CreateDirectList(Loc, Init->getLocStart(), Init->getLocEnd());
 return CreateDirect(Loc, Init->getLocStart(), Init->getLocEnd());
   }
   
@@ -660,12 +668,20 @@ public:
   bool allowExplicitConversionFunctionsInRefBinding() const {
 return !isCopyInit() || Context == IC_ExplicitConvs;
   }
+
+  /// Determine whether this initialization has a source range containing the
+  /// locations of open and closing parentheses or braces.
+  bool hasParenOrBraceRange() const {
+return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList;
+  }
   
   /// \brief Retrieve the source range containing the locations of the open
-  /// and closing parentheses for value and direct initializations.
-  SourceRange getParenRange() const {
-assert((Kind == IK_Direct || Kind == IK_Value) &&
-   "Only direct- and value-initialization have parentheses");
+  /// and closing parentheses or braces for value, direct, and direct list
+  /// initializations.
+  SourceRange getParenOrBraceRange() const {
+assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "
+ "initialization have parentheses or "
+ "braces");
 return SourceRange(Locations[1], Locations[2]);
   }
 };

Modified: 

Re: [analyzer] Add support for __builtin_constant_p to BuiltinFunctionChecker

2018-01-16 Thread Vedant Kumar via cfe-commits
+ Devin and George

> On Jan 14, 2018, at 10:44 AM, Felix Kostenzer via cfe-commits 
>  wrote:
> 
> 
> Hi,
> 
> Added evaluation of __builtin_constant_p to the dedicated StaticAnalyzer 
> checker
> along with a regression test.
> 
> 'make clang-test' results:
> 
> Testing Time: 335.63s
>  Expected Passes : 11769
>  Expected Failures : 19
>  Unsupported Tests : 50
> 
> - 
> felix<0001-analyzer-add-builtin_constant_p-support.patch>___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

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


r321771 - [CGBuiltin] Handle unsigned mul overflow properly (PR35750)

2018-01-03 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Jan  3 15:11:32 2018
New Revision: 321771

URL: http://llvm.org/viewvc/llvm-project?rev=321771=rev
Log:
[CGBuiltin] Handle unsigned mul overflow properly (PR35750)

r320902 fixed the IRGen for some types of checked multiplications. It
did not handle unsigned overflow correctly in the case where the signed
operand is negative (PR35750).

Eli pointed out that on overflow, the result must be equal to the unique
value that is equivalent to the mathematically-correct result modulo two
raised to the k power, where k is the number of bits in the result type.

This patch fixes the specialized IRGen from r320902 accordingly.

Testing: Apart from check-clang, I modified the test harness from
r320902 to validate the results of all multiplications -- not just the
ones which don't overflow:

  https://gist.github.com/vedantk/3eb9c88f82e5c32f2e590555b4af5081

llvm.org/PR35750, rdar://34963321

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

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/builtins-overflow.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=321771=321770=321771=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Wed Jan  3 15:11:32 2018
@@ -915,7 +915,11 @@ EmitCheckedMixedSignMultiply(CodeGenFunc
   Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
 }
 
-Result = CGF.Builder.CreateTrunc(UnsignedResult, ResTy);
+// Negate the product if it would be negative in infinite precision.
+Result = CGF.Builder.CreateSelect(
+IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
+
+Result = CGF.Builder.CreateTrunc(Result, ResTy);
   }
   assert(Overflow && Result && "Missing overflow or result");
 

Modified: cfe/trunk/test/CodeGen/builtins-overflow.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtins-overflow.c?rev=321771=321770=321771=diff
==
--- cfe/trunk/test/CodeGen/builtins-overflow.c (original)
+++ cfe/trunk/test/CodeGen/builtins-overflow.c Wed Jan  3 15:11:32 2018
@@ -373,7 +373,9 @@ int test_mixed_sign_mull_overflow_unsign
 // CHECK-NEXT:  [[NotNull:%.*]] = icmp ne i32 [[UnsignedResult]], 0
 // CHECK-NEXT:  [[Underflow:%.*]] = and i1 [[IsNeg]], [[NotNull]]
 // CHECK-NEXT:  [[OFlow:%.*]] = or i1 [[UnsignedOFlow]], [[Underflow]]
-// CHECK-NEXT:  store i32 [[UnsignedResult]], i32* %{{.*}}, align 4
+// CHECK-NEXT:  [[NegatedResult:%.*]] = sub i32 0, [[UnsignedResult]]
+// CHECK-NEXT:  [[Result:%.*]] = select i1 [[IsNeg]], i32 [[NegatedResult]], 
i32 [[UnsignedResult]]
+// CHECK-NEXT:  store i32 [[Result]], i32* %{{.*}}, align 4
 // CHECK:   br i1 [[OFlow]]
 
   unsigned result;
@@ -432,7 +434,9 @@ long long test_mixed_sign_mulll_overflow
 // CHECK-NEXT:  [[OVERFLOW_PRE_TRUNC:%.*]] = or i1 {{.*}}, [[UNDERFLOW]]
 // CHECK-NEXT:  [[TRUNC_OVERFLOW:%.*]] = icmp ugt i64 [[UNSIGNED_RESULT]], 
4294967295
 // CHECK-NEXT:  [[OVERFLOW:%.*]] = or i1 [[OVERFLOW_PRE_TRUNC]], 
[[TRUNC_OVERFLOW]]
-// CHECK-NEXT:  trunc i64 [[UNSIGNED_RESULT]] to i32
+// CHECK-NEXT:  [[NEGATED:%.*]] = sub i64 0, [[UNSIGNED_RESULT]]
+// CHECK-NEXT:  [[RESULT:%.*]] = select i1 {{.*}}, i64 [[NEGATED]], i64 
[[UNSIGNED_RESULT]]
+// CHECK-NEXT:  trunc i64 [[RESULT]] to i32
 // CHECK-NEXT:  store
   unsigned result;
   if (__builtin_mul_overflow(y, x, ))


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


Re: r321395 - [ODRHash] Support ODR violation detection in functions.

2018-01-03 Thread Vedant Kumar via cfe-commits
Oops, the build log was too big to attach. Resending with just the bot link, 
then:
http://lab.llvm.org:8080/green/view/Experimental/job/clang-stage2-coverage-R/2193/consoleText
 


vedant

> On Jan 3, 2018, at 11:09 AM, Vedant Kumar  wrote:
> 
> Hi Richard,
> 
> This commit is causing an unexpected build failure in the stage2 
> modules-enabled coverage bot. I've attached the build log. Here's the error:
> 
> [3685/3899] 
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/host-compiler/bin/clang++
>-DGTEST_HAS_RTTI=0 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS 
> -D__STDC_LIMIT_MACROS -Itools/lld/COFF 
> -I/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF
>  
> -I/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/include
>  -Itools/lld/include -I/usr/include/libxml2 -Iinclude 
> -I/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include 
> -fPIC -fvisibility-inlines-hidden -Werror=date-time 
> -Werror=unguarded-availability-new -std=c++11 -fmodules 
> -fmodules-cache-path=/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/clang-build/module.cache
>  -fcxx-modules -Wall -W -Wno-unused-parameter -Wwrite-strings -Wcast-qual 
> -Wmissing-field-initializers -pedantic -Wno-long-long 
> -Wcovered-switch-default -Wnon-virtual-dtor -Wdelete-non-virtual-dtor 
> -Wstring-conversion -fcolor-diagnostics 
> -fprofile-instr-generate='/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/clang-build/profiles/%6m.profraw'
>  -fcoverage-mapping -O3 -DNDEBUG-fno-exceptions -fno-rtti -MMD -MT 
> tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o -MF 
> tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o.d -o 
> tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o -c 
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/PDB.cpp
> FAILED: tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o 
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/host-compiler/bin/clang++
>-DGTEST_HAS_RTTI=0 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS 
> -D__STDC_LIMIT_MACROS -Itools/lld/COFF 
> -I/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF
>  
> -I/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/include
>  -Itools/lld/include -I/usr/include/libxml2 -Iinclude 
> -I/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include 
> -fPIC -fvisibility-inlines-hidden -Werror=date-time 
> -Werror=unguarded-availability-new -std=c++11 -fmodules 
> -fmodules-cache-path=/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/clang-build/module.cache
>  -fcxx-modules -Wall -W -Wno-unused-parameter -Wwrite-strings -Wcast-qual 
> -Wmissing-field-initializers -pedantic -Wno-long-long 
> -Wcovered-switch-default -Wnon-virtual-dtor -Wdelete-non-virtual-dtor 
> -Wstring-conversion -fcolor-diagnostics 
> -fprofile-instr-generate='/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/clang-build/profiles/%6m.profraw'
>  -fcoverage-mapping -O3 -DNDEBUG-fno-exceptions -fno-rtti -MMD -MT 
> tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o -MF 
> tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o.d -o 
> tools/lld/COFF/CMakeFiles/lldCOFF.dir/PDB.cpp.o -c 
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/PDB.cpp
> In module 'std' imported from 
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/Config.h:16:
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/host-compiler/include/c++/v1/list:389:10:
>  error: 'std::__1::operator==' has different definitions in different 
> modules; definition in module 'std.list' first difference is function body
> bool operator==(const __list_iterator& __x, const __list_iterator& __y)
> ~^~
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/host-compiler/include/c++/v1/list:389:10:
>  note: but in 'std.list' found a different body
> bool operator==(const __list_iterator& __x, const __list_iterator& __y)
> ~^~
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/host-compiler/include/c++/v1/list:394:11:
>  error: 'std::__1::operator!=' has different definitions in different 
> modules; definition in module 'std.list' first difference is function body
>  bool operator!=(const __list_iterator& __x, const __list_iterator& __y)
>  ~^~
> /Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/host-compiler/include/c++/v1/list:394:11:
>  note: but in 'std.list' found a different body
>  bool operator!=(const __list_iterator& __x, const __list_iterator& __y)
>  

r321230 - [Driver] Ensure no overlap between trapping & recoverable sanitizers. NFC.

2017-12-20 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Dec 20 16:10:24 2017
New Revision: 321230

URL: http://llvm.org/viewvc/llvm-project?rev=321230=rev
Log:
[Driver] Ensure no overlap between trapping & recoverable sanitizers. NFC.

This is NFC because in EmitCheck(), -fsanitize-trap=X overrides
-fsanitize-recover=X.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp
cfe/trunk/test/Driver/fsanitize.c

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=321230=321229=321230=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Wed Dec 20 16:10:24 2017
@@ -440,6 +440,7 @@ SanitizerArgs::SanitizerArgs(const ToolC
   RecoverableKinds &= ~Unrecoverable;
 
   TrappingKinds &= Kinds;
+  RecoverableKinds &= ~TrappingKinds;
 
   // Setup blacklist files.
   // Add default blacklist from resource directory.
@@ -683,6 +684,8 @@ SanitizerArgs::SanitizerArgs(const ToolC
   Sanitizers.Mask |= Kinds;
   RecoverableSanitizers.Mask |= RecoverableKinds;
   TrapSanitizers.Mask |= TrappingKinds;
+  assert(!(RecoverableKinds & TrappingKinds) &&
+ "Overlap between recoverable and trapping sanitizers");
 }
 
 static std::string toString(const clang::SanitizerSet ) {

Modified: cfe/trunk/test/Driver/fsanitize.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fsanitize.c?rev=321230=321229=321230=diff
==
--- cfe/trunk/test/Driver/fsanitize.c (original)
+++ cfe/trunk/test/Driver/fsanitize.c Wed Dec 20 16:10:24 2017
@@ -3,6 +3,7 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined 
-fsanitize-undefined-trap-on-error %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-UNDEFINED-TRAP
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined-trap 
-fsanitize-undefined-trap-on-error %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-UNDEFINED-TRAP
 // RUN: %clang -target x86_64-linux-gnu -fsanitize-undefined-trap-on-error 
-fsanitize=undefined-trap %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-UNDEFINED-TRAP
+// CHECK-UNDEFINED-TRAP-NOT: -fsanitize-recover
 // CHECK-UNDEFINED-TRAP: 
"-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|pointer-overflow|float-cast-overflow|array-bounds|enum|bool|builtin|returns-nonnull-attribute|nonnull-attribute|function),?){19}"}}
 // CHECK-UNDEFINED-TRAP: 
"-fsanitize-trap=alignment,array-bounds,bool,builtin,enum,float-cast-overflow,float-divide-by-zero,function,integer-divide-by-zero,nonnull-attribute,null,pointer-overflow,return,returns-nonnull-attribute,shift-base,shift-exponent,signed-integer-overflow,unreachable,vla-bound"
 // CHECK-UNDEFINED-TRAP2: 
"-fsanitize-trap=alignment,array-bounds,bool,builtin,enum,float-cast-overflow,float-divide-by-zero,function,integer-divide-by-zero,nonnull-attribute,null,pointer-overflow,return,returns-nonnull-attribute,shift-base,shift-exponent,unreachable,vla-bound"


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


r321231 - [ubsan] Diagnose noreturn functions which return

2017-12-20 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Dec 20 16:10:25 2017
New Revision: 321231

URL: http://llvm.org/viewvc/llvm-project?rev=321231=rev
Log:
[ubsan] Diagnose noreturn functions which return

Diagnose 'unreachable' UB when a noreturn function returns.

  1. Insert a check at the end of functions marked noreturn.

  2. A decl may be marked noreturn in the caller TU, but not marked in
 the TU where it's defined. To diagnose this scenario, strip away the
 noreturn attribute on the callee and insert check after calls to it.

Testing: check-clang, check-ubsan, check-ubsan-minimal, D40700

rdar://33660464

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

Added:
cfe/trunk/test/CodeGen/ubsan-noreturn.c
cfe/trunk/test/CodeGenCXX/ubsan-unreachable.cpp
Modified:
cfe/trunk/docs/UndefinedBehaviorSanitizer.rst
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/CodeGen/CGExprCXX.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h

Modified: cfe/trunk/docs/UndefinedBehaviorSanitizer.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/UndefinedBehaviorSanitizer.rst?rev=321231=321230=321231=diff
==
--- cfe/trunk/docs/UndefinedBehaviorSanitizer.rst (original)
+++ cfe/trunk/docs/UndefinedBehaviorSanitizer.rst Wed Dec 20 16:10:25 2017
@@ -124,8 +124,8 @@ Available checks are:
   -  ``-fsanitize=signed-integer-overflow``: Signed integer overflow,
  including all the checks added by ``-ftrapv``, and checking for
  overflow in signed division (``INT_MIN / -1``).
-  -  ``-fsanitize=unreachable``: If control flow reaches
- ``__builtin_unreachable``.
+  -  ``-fsanitize=unreachable``: If control flow reaches an unreachable
+ program point.
   -  ``-fsanitize=unsigned-integer-overflow``: Unsigned integer
  overflows. Note that unlike signed integer overflow, unsigned integer
  is not undefined behavior. However, while it has well-defined semantics,

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=321231=321230=321231=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Wed Dec 20 16:10:25 2017
@@ -1432,14 +1432,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(
   case Builtin::BI__debugbreak:
 return RValue::get(EmitTrapCall(Intrinsic::debugtrap));
   case Builtin::BI__builtin_unreachable: {
-if (SanOpts.has(SanitizerKind::Unreachable)) {
-  SanitizerScope SanScope(this);
-  EmitCheck(std::make_pair(static_cast(Builder.getFalse()),
-   SanitizerKind::Unreachable),
-SanitizerHandler::BuiltinUnreachable,
-EmitCheckSourceLocation(E->getExprLoc()), None);
-} else
-  Builder.CreateUnreachable();
+EmitUnreachable(E->getExprLoc());
 
 // We do need to preserve an insertion point.
 EmitBlock(createBasicBlock("unreachable.cont"));

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=321231=321230=321231=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Dec 20 16:10:25 2017
@@ -2758,6 +2758,12 @@ static llvm::StoreInst *findDominatingSt
 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo ,
  bool EmitRetDbgLoc,
  SourceLocation EndLoc) {
+  if (FI.isNoReturn()) {
+// Noreturn functions don't return.
+EmitUnreachable(EndLoc);
+return;
+  }
+
   if (CurCodeDecl && CurCodeDecl->hasAttr()) {
 // Naked functions don't have epilogues.
 Builder.CreateUnreachable();
@@ -3718,7 +3724,8 @@ RValue CodeGenFunction::EmitCall(const C
  const CGCallee ,
  ReturnValueSlot ReturnValue,
  const CallArgList ,
- llvm::Instruction **callOrInvoke) {
+ llvm::Instruction **callOrInvoke,
+ SourceLocation Loc) {
   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
 
   assert(Callee.isOrdinary());
@@ -4241,7 +4248,15 @@ RValue CodeGenFunction::EmitCall(const C
   EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
   SRetPtr.getPointer());
 
-Builder.CreateUnreachable();
+// Strip away the noreturn attribute to better diagnose unreachable UB.
+if (SanOpts.has(SanitizerKind::Unreachable)) {
+  if (auto *F = CS.getCalledFunction())
+F->removeFnAttr(llvm::Attribute::NoReturn);
+  

r320902 - [CodeGen] Specialize mixed-sign mul-with-overflow (fix PR34920)

2017-12-15 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Dec 15 17:28:25 2017
New Revision: 320902

URL: http://llvm.org/viewvc/llvm-project?rev=320902=rev
Log:
[CodeGen] Specialize mixed-sign mul-with-overflow (fix PR34920)

This patch introduces a specialized way to lower overflow-checked
multiplications with mixed-sign operands. This fixes link failures and
ICEs on code like this:

  void mul(int64_t a, uint64_t b) {
int64_t res;
__builtin_mul_overflow(a, b, );
  }

The generic checked-binop irgen would use a 65-bit multiplication
intrinsic here, which requires runtime support for _muloti4 (128-bit
multiplication), and therefore fails to link on i386. To get an ICE
on x86_64, change the example to use __int128_t / __uint128_t.

Adding runtime and backend support for 65-bit or 129-bit checked
multiplication on all of our supported targets is infeasible.

This patch solves the problem by using simpler, specialized irgen for
the mixed-sign case.

llvm.org/PR34920, rdar://34963321

Testing: Apart from check-clang, I compared the output from this fairly
comprehensive test driver using unpatched & patched clangs:
https://gist.github.com/vedantk/3eb9c88f82e5c32f2e590555b4af5081

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

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/builtins-overflow.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=320902=320901=320902=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Fri Dec 15 17:28:25 2017
@@ -839,6 +839,93 @@ RValue CodeGenFunction::emitBuiltinOSLog
   return RValue::get(BufAddr.getPointer());
 }
 
+/// Determine if a binop is a checked mixed-sign multiply we can specialize.
+static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
+   WidthAndSignedness Op1Info,
+   WidthAndSignedness Op2Info,
+   WidthAndSignedness ResultInfo) {
+  return BuiltinID == Builtin::BI__builtin_mul_overflow &&
+ Op1Info.Width == Op2Info.Width && Op1Info.Width >= ResultInfo.Width &&
+ Op1Info.Signed != Op2Info.Signed;
+}
+
+/// Emit a checked mixed-sign multiply. This is a cheaper specialization of
+/// the generic checked-binop irgen.
+static RValue
+EmitCheckedMixedSignMultiply(CodeGenFunction , const clang::Expr *Op1,
+ WidthAndSignedness Op1Info, const clang::Expr 
*Op2,
+ WidthAndSignedness Op2Info,
+ const clang::Expr *ResultArg, QualType ResultQTy,
+ WidthAndSignedness ResultInfo) {
+  assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,
+Op2Info, ResultInfo) &&
+ "Not a mixed-sign multipliction we can specialize");
+
+  // Emit the signed and unsigned operands.
+  const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
+  const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
+  llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
+  llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
+
+  llvm::Type *OpTy = Signed->getType();
+  llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
+  Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
+  llvm::Type *ResTy = ResultPtr.getElementType();
+
+  // Take the absolute value of the signed operand.
+  llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
+  llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
+  llvm::Value *AbsSigned =
+  CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
+
+  // Perform a checked unsigned multiplication.
+  llvm::Value *UnsignedOverflow;
+  llvm::Value *UnsignedResult =
+  EmitOverflowIntrinsic(CGF, llvm::Intrinsic::umul_with_overflow, 
AbsSigned,
+Unsigned, UnsignedOverflow);
+
+  llvm::Value *Overflow, *Result;
+  if (ResultInfo.Signed) {
+// Signed overflow occurs if the result is greater than INT_MAX or lesser
+// than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
+auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width)
+  .zextOrSelf(Op1Info.Width);
+llvm::Value *MaxResult =
+CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
+  CGF.Builder.CreateZExt(IsNegative, OpTy));
+llvm::Value *SignedOverflow =
+CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
+Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
+
+// Prepare the signed result (possibly by negating it).
+llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
+llvm::Value *SignedResult =
+CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
+Result 

r320185 - [ubsan] array-bounds: Ignore params with constant size

2017-12-08 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Dec  8 11:51:42 2017
New Revision: 320185

URL: http://llvm.org/viewvc/llvm-project?rev=320185=rev
Log:
[ubsan] array-bounds: Ignore params with constant size

This is a follow-up to r320128. Eli pointed out that there is some gray
area in the language standard about whether the constant size is exact,
or a lower bound.

https://reviews.llvm.org/D40940

Modified:
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/test/CodeGen/ubsan-pass-object-size.c

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=320185=320184=320185=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Fri Dec  8 11:51:42 2017
@@ -829,14 +829,6 @@ llvm::Value *CodeGenFunction::LoadPassed
   if (!ParamDecl)
 return nullptr;
 
-  // Arrays don't have pass_object_size attributes, but if they have a constant
-  // size modifier it's the array size (C99 6.5.7.2p1).
-  if (auto *DecayedArrayTy = dyn_cast(ParamDecl->getType()))
-if (auto *ArrayTy =
-dyn_cast(DecayedArrayTy->getOriginalType()))
-  return llvm::ConstantInt::get(SizeTy,
-ArrayTy->getSize().getLimitedValue());
-
   auto *POSAttr = ParamDecl->getAttr();
   if (!POSAttr)
 return nullptr;

Modified: cfe/trunk/test/CodeGen/ubsan-pass-object-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/ubsan-pass-object-size.c?rev=320185=320184=320185=diff
==
--- cfe/trunk/test/CodeGen/ubsan-pass-object-size.c (original)
+++ cfe/trunk/test/CodeGen/ubsan-pass-object-size.c Fri Dec  8 11:51:42 2017
@@ -55,8 +55,7 @@ int pat(int *const p __attribute__((pass
 
 // CHECK-LABEL: define i32 @cat(
 int cat(int p[static 10], int n) {
-  // CHECK: icmp ult i64 {{.*}}, 10, !nosanitize
-  // CHECK: __ubsan_handle_out_of_bounds
+  // CHECK-NOT: __ubsan_handle_out_of_bounds
   // CHECK: ret i32
   return p[n];
 }


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


r320132 - [Blocks] Inherit sanitizer options from parent decl

2017-12-07 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Dec  7 18:47:58 2017
New Revision: 320132

URL: http://llvm.org/viewvc/llvm-project?rev=320132=rev
Log:
[Blocks] Inherit sanitizer options from parent decl

There is no way to apply sanitizer suppressions to ObjC blocks. A
reasonable default is to have blocks inherit their parent's sanitizer
options.

rdar://32769634

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

Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp
cfe/trunk/test/CodeGenObjC/no-sanitize.m

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=320132=320131=320132=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Thu Dec  7 18:47:58 2017
@@ -784,7 +784,9 @@ llvm::Value *CodeGenFunction::EmitBlockL
   8);
   // Using the computed layout, generate the actual block function.
   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
-  auto *InvokeFn = CodeGenFunction(CGM, true).GenerateBlockFunction(
+  CodeGenFunction BlockCGF{CGM, true};
+  BlockCGF.SanOpts = SanOpts;
+  auto *InvokeFn = BlockCGF.GenerateBlockFunction(
   CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
   if (InvokeF)
 *InvokeF = InvokeFn;

Modified: cfe/trunk/test/CodeGenObjC/no-sanitize.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/no-sanitize.m?rev=320132=320131=320132=diff
==
--- cfe/trunk/test/CodeGenObjC/no-sanitize.m (original)
+++ cfe/trunk/test/CodeGenObjC/no-sanitize.m Thu Dec  7 18:47:58 2017
@@ -1,8 +1,9 @@
-// RUN: %clang_cc1 %s -emit-llvm -fsanitize=address -o - | FileCheck %s
+// RUN: %clang_cc1 %s -emit-llvm -fsanitize=address -fblocks -o - | FileCheck 
%s
 
 @interface I0 @end
 @implementation I0
 // CHECK-NOT: sanitize_address
 - (void) im0: (int) a0 __attribute__((no_sanitize("address"))) {
+  int (^blockName)() = ^int() { return 0; };
 }
 @end


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


r320128 - [ubsan] Use pass_object_size info in bounds checks

2017-12-07 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Dec  7 17:51:47 2017
New Revision: 320128

URL: http://llvm.org/viewvc/llvm-project?rev=320128=rev
Log:
[ubsan] Use pass_object_size info in bounds checks

Teach UBSan's bounds check to opportunistically use pass_object_size
information to check array accesses.

rdar://33272922

Added:
cfe/trunk/test/CodeGen/ubsan-pass-object-size.c
Modified:
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=320128=320127=320128=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Thu Dec  7 17:51:47 2017
@@ -814,6 +814,53 @@ static bool isFlexibleArrayMemberExpr(co
   return false;
 }
 
+llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
+   QualType EltTy) {
+  ASTContext  = getContext();
+  uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
+  if (!EltSize)
+return nullptr;
+
+  auto *ArrayDeclRef = dyn_cast(E->IgnoreParenImpCasts());
+  if (!ArrayDeclRef)
+return nullptr;
+
+  auto *ParamDecl = dyn_cast(ArrayDeclRef->getDecl());
+  if (!ParamDecl)
+return nullptr;
+
+  // Arrays don't have pass_object_size attributes, but if they have a constant
+  // size modifier it's the array size (C99 6.5.7.2p1).
+  if (auto *DecayedArrayTy = dyn_cast(ParamDecl->getType()))
+if (auto *ArrayTy =
+dyn_cast(DecayedArrayTy->getOriginalType()))
+  return llvm::ConstantInt::get(SizeTy,
+ArrayTy->getSize().getLimitedValue());
+
+  auto *POSAttr = ParamDecl->getAttr();
+  if (!POSAttr)
+return nullptr;
+
+  // Don't load the size if it's a lower bound.
+  int POSType = POSAttr->getType();
+  if (POSType != 0 && POSType != 1)
+return nullptr;
+
+  // Find the implicit size parameter.
+  auto PassedSizeIt = SizeArguments.find(ParamDecl);
+  if (PassedSizeIt == SizeArguments.end())
+return nullptr;
+
+  const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
+  assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
+  Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
+  llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
+  C.getSizeType(), 
E->getExprLoc());
+  llvm::Value *SizeOfElement =
+  llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
+  return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
+}
+
 /// If Base is known to point to the start of an array, return the length of
 /// that array. Return 0 if the length cannot be determined.
 static llvm::Value *getArrayIndexingBound(
@@ -835,9 +882,16 @@ static llvm::Value *getArrayIndexingBoun
 return CGF.Builder.getInt(CAT->getSize());
   else if (const auto *VAT = dyn_cast(AT))
 return CGF.getVLASize(VAT).first;
+  // Ignore pass_object_size here. It's not applicable on decayed pointers.
 }
   }
 
+  QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
+  if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
+IndexedType = Base->getType();
+return POS;
+  }
+
   return nullptr;
 }
 

Modified: cfe/trunk/lib/CodeGen/CodeGenFunction.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenFunction.h?rev=320128=320127=320128=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenFunction.h (original)
+++ cfe/trunk/lib/CodeGen/CodeGenFunction.h Thu Dec  7 17:51:47 2017
@@ -3927,6 +3927,11 @@ public:
LValueBaseInfo *BaseInfo = nullptr,
TBAAAccessInfo *TBAAInfo = nullptr);
 
+  /// If \p E references a parameter with pass_object_size info or a constant
+  /// array size modifier, emit the object size divided by the size of \p 
EltTy.
+  /// Otherwise return null.
+  llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
+
   void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
 
 private:

Added: cfe/trunk/test/CodeGen/ubsan-pass-object-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/ubsan-pass-object-size.c?rev=320128=auto
==
--- cfe/trunk/test/CodeGen/ubsan-pass-object-size.c (added)
+++ cfe/trunk/test/CodeGen/ubsan-pass-object-size.c Thu Dec  7 17:51:47 2017
@@ -0,0 +1,69 @@
+// RUN: %clang_cc1 %s -emit-llvm -w -triple x86_64-apple-darwin10 
-fsanitize=array-bounds -o - | FileCheck %s
+
+// CHECK-LABEL: define i32 @foo(
+int foo(int *const p __attribute__((pass_object_size(0))), int n) {
+  int x = (p)[n];
+
+  // CHECK: [[SIZE_ALLOCA:%.*]] = alloca i64, align 8
+  // CHECK: store i64 %{{.*}}, i64* 

r319373 - [Coverage] Emit gap areas in braces-optional statements (PR35387)

2017-11-29 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Nov 29 14:25:14 2017
New Revision: 319373

URL: http://llvm.org/viewvc/llvm-project?rev=319373=rev
Log:
[Coverage] Emit gap areas in braces-optional statements (PR35387)

Emit a gap area starting after the r-paren location and ending at the
start of the body for the braces-optional statements (for, for-each,
while, etc). The count for the gap area equal to the body's count. This
extends the fix in r317758.

Fixes PR35387, rdar://35570345

Testing: stage2 coverage-enabled build of clang, check-clang

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/break.c
cfe/trunk/test/CoverageMapping/continue.c
cfe/trunk/test/CoverageMapping/if.cpp
cfe/trunk/test/CoverageMapping/includehell.cpp
cfe/trunk/test/CoverageMapping/label.cpp
cfe/trunk/test/CoverageMapping/loops.cpp
cfe/trunk/test/CoverageMapping/macro-expressions.cpp
cfe/trunk/test/CoverageMapping/macros.c
cfe/trunk/test/CoverageMapping/objc.m
cfe/trunk/test/CoverageMapping/return.c
cfe/trunk/test/CoverageMapping/test.c
cfe/trunk/test/CoverageMapping/while.c

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=319373=319372=319373=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Wed Nov 29 14:25:14 2017
@@ -112,6 +112,9 @@ struct SpellingRegion {
 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
   }
 
+  SpellingRegion(SourceManager , SourceMappingRegion )
+  : SpellingRegion(SM, R.getStartLoc(), R.getEndLoc()) {}
+
   /// Check if the start and end locations appear in source order, i.e
   /// top->bottom, left->right.
   bool isInSourceOrder() const {
@@ -583,6 +586,7 @@ struct CounterCoverageMappingBuilder
   MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
 
 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
+assert(SpellingRegion(SM, Region).isInSourceOrder());
 SourceRegions.push_back(Region);
 
 if (ParentOfDeferredRegion) {
@@ -718,9 +722,11 @@ struct CounterCoverageMappingBuilder
   SourceLocation Loc = MostRecentLocation;
   while (isNestedIn(Loc, ParentFile)) {
 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
-if (StartLocs.insert(FileStart).second)
+if (StartLocs.insert(FileStart).second) {
   SourceRegions.emplace_back(*ParentCounter, FileStart,
  getEndOfFileOrMacro(Loc));
+  assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
+}
 Loc = getIncludeOrExpansionLoc(Loc);
   }
 }
@@ -753,12 +759,31 @@ struct CounterCoverageMappingBuilder
 LastTerminatedRegion = {EndLoc, RegionStack.size()};
   }
 
+  /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
+  Optional findGapAreaBetween(SourceLocation AfterLoc,
+   SourceLocation BeforeLoc) {
+// If the start and end locations of the gap are both within the same macro
+// file, the range may not be in source order.
+if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
+  return None;
+if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
+  return None;
+return {{AfterLoc, BeforeLoc}};
+  }
+
+  /// Find the source range after \p AfterStmt and before \p BeforeStmt.
+  Optional findGapAreaBetween(const Stmt *AfterStmt,
+   const Stmt *BeforeStmt) {
+return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
+  getStart(BeforeStmt));
+  }
+
   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
 Counter Count) {
-if (StartLoc == EndLoc || StartLoc.isMacroID() || EndLoc.isMacroID() ||
-!SM.isWrittenInSameFile(StartLoc, EndLoc))
+if (StartLoc == EndLoc)
   return;
+assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
 handleFileExit(StartLoc);
 size_t Index = pushRegion(Count, StartLoc, EndLoc);
 getRegion().setGap(true);
@@ -914,6 +939,11 @@ struct CounterCoverageMappingBuilder
 propagateCounts(CondCount, S->getCond());
 adjustForOutOfOrderTraversal(getEnd(S));
 
+// The body count applies to the area immediately after the increment.
+auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
+if (Gap)
+  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
+
 Counter OutCount =
 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
 if (OutCount != ParentCount)
@@ -968,6 +998,12 @@ struct CounterCoverageMappingBuilder
   adjustForOutOfOrderTraversal(getEnd(S));
 }
 

r318229 - [PGO] Detect more structural changes with the stable hash

2017-11-14 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Nov 14 15:56:53 2017
New Revision: 318229

URL: http://llvm.org/viewvc/llvm-project?rev=318229=rev
Log:
[PGO] Detect more structural changes with the stable hash

Lifting from Bob Wilson's notes: The hash value that we compute and
store in PGO profile data to detect out-of-date profiles does not
include enough information. This means that many significant changes to
the source will not cause compiler warnings about the profile being out
of date, and worse, we may continue to use the outdated profile data to
make bad optimization decisions.  There is some tension here because
some source changes won't affect PGO and we don't want to invalidate the
profile unnecessarily.

This patch adds a new hashing scheme which is more sensitive to loop
nesting, conditions, and out-of-order control flow. Here are examples
which show snippets which get the same hash under the current scheme,
and different hashes under the new scheme:

Loop Nesting Example


  // Snippet 1
  while (foo()) {
while (bar()) {}
  }

  // Snippet 2
  while (foo()) {}
  while (bar()) {}

Condition Example
-

  // Snippet 1
  if (foo())
bar();
  baz();

  // Snippet 2
  if (foo())
bar();
  else
baz();

Out-of-order Control Flow Example
-

  // Snippet 1
  while (foo()) {
if (bar()) {}
baz();
  }

  // Snippet 2
  while (foo()) {
if (bar())
  continue;
baz();
  }

In each of these cases, it's useful to differentiate between the
snippets because swapping their profiles gives bad optimization hints.

The new hashing scheme considers some logical operators in an effort to
detect more changes in conditions. This isn't a perfect scheme. E.g, it
does not produce the same hash for these equivalent snippets:

  // Snippet 1
  bool c = !a || b;
  if (d && e) {}

  // Snippet 2
  bool f = d && e;
  bool c = !a || b;
  if (f) {}

This would require an expensive data flow analysis. Short of that, the
new hashing scheme looks reasonably complete, based on a scan over the
statements we place counters on.

Profiles which use the old version of the PGO hash remain valid and can
be used without issue (there are tests in tree which check this).

rdar://17068282

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

Added:
cfe/trunk/test/Profile/Inputs/cxx-hash-v2.profdata.v5
cfe/trunk/test/Profile/Inputs/cxx-hash-v2.proftext
cfe/trunk/test/Profile/cxx-hash-v2.cpp
Modified:
cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
cfe/trunk/test/Frontend/Inputs/optimization-remark-with-hotness.proftext
cfe/trunk/test/Profile/Inputs/c-captured.proftext
cfe/trunk/test/Profile/Inputs/c-counter-overflows.proftext
cfe/trunk/test/Profile/Inputs/c-general.proftext
cfe/trunk/test/Profile/Inputs/c-unprofiled-blocks.proftext
cfe/trunk/test/Profile/Inputs/cxx-class.proftext
cfe/trunk/test/Profile/Inputs/cxx-lambda.proftext
cfe/trunk/test/Profile/Inputs/cxx-rangefor.proftext
cfe/trunk/test/Profile/Inputs/cxx-templates.proftext
cfe/trunk/test/Profile/Inputs/cxx-throws.proftext
cfe/trunk/test/Profile/Inputs/func-entry.proftext
cfe/trunk/test/Profile/Inputs/gcc-flag-compatibility.proftext
cfe/trunk/test/Profile/Inputs/objc-general.proftext
cfe/trunk/test/Profile/c-outdated-data.c
cfe/trunk/test/Profile/objc-general.m

Modified: cfe/trunk/lib/CodeGen/CodeGenPGO.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenPGO.cpp?rev=318229=318228=318229=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenPGO.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenPGO.cpp Tue Nov 14 15:56:53 2017
@@ -47,6 +47,15 @@ void CodeGenPGO::setFuncName(llvm::Funct
   llvm::createPGOFuncNameMetadata(*Fn, FuncName);
 }
 
+/// The version of the PGO hash algorithm.
+enum PGOHashVersion : unsigned {
+  PGO_HASH_V1,
+  PGO_HASH_V2,
+
+  // Keep this set to the latest hash version.
+  PGO_HASH_LATEST = PGO_HASH_V2
+};
+
 namespace {
 /// \brief Stable hasher for PGO region counters.
 ///
@@ -61,6 +70,7 @@ namespace {
 class PGOHash {
   uint64_t Working;
   unsigned Count;
+  PGOHashVersion HashVersion;
   llvm::MD5 MD5;
 
   static const int NumBitsPerType = 6;
@@ -93,24 +103,53 @@ public:
 BinaryOperatorLAnd,
 BinaryOperatorLOr,
 BinaryConditionalOperator,
+// The preceding values are available with PGO_HASH_V1.
+
+EndOfScope,
+IfThenBranch,
+IfElseBranch,
+GotoStmt,
+IndirectGotoStmt,
+BreakStmt,
+ContinueStmt,
+ReturnStmt,
+ThrowExpr,
+UnaryOperatorLNot,
+BinaryOperatorLT,
+BinaryOperatorGT,
+BinaryOperatorLE,
+BinaryOperatorGE,
+BinaryOperatorEQ,
+BinaryOperatorNE,
+// The preceding values are available with PGO_HASH_V2.
 
 // Keep this last.  It's for the static assert that follows.
 LastHashType
   };
   static_assert(LastHashType <= TooBig, "Too 

r317759 - [Coverage] Complete top-level deferred regions before labels

2017-11-08 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Nov  8 18:33:39 2017
New Revision: 317759

URL: http://llvm.org/viewvc/llvm-project?rev=317759=rev
Log:
[Coverage] Complete top-level deferred regions before labels

The area immediately after a terminated region in the function top-level
should have the same count as the label it precedes.

This solves another problem with wrapped segments. Consider:

  1| a:
  2|   return 0;
  3| b:
  4|   return 1;

Without a gap area starting after the first return, the wrapped segment
from line 2 would make it look like line 3 is executed, when it's not.

rdar://35373009

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/label.cpp
cfe/trunk/test/CoverageMapping/switchmacro.c

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=317759=317758=317759=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Wed Nov  8 18:33:39 2017
@@ -445,6 +445,9 @@ struct CounterCoverageMappingBuilder
   /// expressions cross file or macro boundaries.
   SourceLocation MostRecentLocation;
 
+  /// Location of the last terminated region.
+  Optional> LastTerminatedRegion;
+
   /// \brief Return a counter for the subtraction of \c RHS from \c LHS
   Counter subtractCounters(Counter LHS, Counter RHS) {
 return Builder.subtract(LHS, RHS);
@@ -520,6 +523,27 @@ struct CounterCoverageMappingBuilder
 return Index;
   }
 
+  /// Complete a deferred region created after a terminated region at the
+  /// top-level.
+  void completeTopLevelDeferredRegion(Counter Count,
+  SourceLocation DeferredEndLoc) {
+if (DeferredRegion || !LastTerminatedRegion)
+  return;
+
+if (LastTerminatedRegion->second != RegionStack.size())
+  return;
+
+SourceLocation Start = LastTerminatedRegion->first;
+if (SM.getFileID(Start) != SM.getMainFileID())
+  return;
+
+SourceMappingRegion DR = RegionStack.back();
+DR.setStartLoc(Start);
+DR.setDeferred(false);
+DeferredRegion = DR;
+completeDeferred(Count, DeferredEndLoc);
+  }
+
   /// \brief Pop regions from the stack into the function's list of regions.
   ///
   /// Adds all regions from \c ParentIndex to the top of the stack to the
@@ -576,6 +600,12 @@ struct CounterCoverageMappingBuilder
 ParentOfDeferredRegion = true;
   }
   RegionStack.pop_back();
+
+  // If the zero region pushed after the last terminated region no longer
+  // exists, clear its cached information.
+  if (LastTerminatedRegion &&
+  RegionStack.size() < LastTerminatedRegion->second)
+LastTerminatedRegion = None;
 }
 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
   }
@@ -712,10 +742,13 @@ struct CounterCoverageMappingBuilder
   void terminateRegion(const Stmt *S) {
 extendRegion(S);
 SourceMappingRegion  = getRegion();
+SourceLocation EndLoc = getEnd(S);
 if (!Region.hasEndLoc())
-  Region.setEndLoc(getEnd(S));
+  Region.setEndLoc(EndLoc);
 pushRegion(Counter::getZero());
-getRegion().setDeferred(true);
+auto  = getRegion();
+ZeroRegion.setDeferred(true);
+LastTerminatedRegion = {EndLoc, RegionStack.size()};
   }
 
   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
@@ -826,10 +859,12 @@ struct CounterCoverageMappingBuilder
   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
 
   void VisitLabelStmt(const LabelStmt *S) {
+Counter LabelCount = getRegionCounter(S);
 SourceLocation Start = getStart(S);
+completeTopLevelDeferredRegion(LabelCount, Start);
 // We can't extendRegion here or we risk overlapping with our new region.
 handleFileExit(Start);
-pushRegion(getRegionCounter(S), Start);
+pushRegion(LabelCount, Start);
 Visit(S->getSubStmt());
   }
 

Modified: cfe/trunk/test/CoverageMapping/label.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/label.cpp?rev=317759=317758=317759=diff
==
--- cfe/trunk/test/CoverageMapping/label.cpp (original)
+++ cfe/trunk/test/CoverageMapping/label.cpp Wed Nov  8 18:33:39 2017
@@ -28,8 +28,8 @@ void test1(int x) {  // CHECK-NE
   if(x == 0) // CHECK-NEXT: File 0, [[@LINE]]:6 -> 
[[@LINE]]:12 = #0
 goto a;  // CHECK: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #1
  // CHECK-NEXT: File 0, [[@LINE-1]]:11 -> 
[[@LINE+1]]:3 = (#0 - #1)
-  goto b;// CHECK-NEXT: File 0, [[@LINE]]:3 -> 
[[@LINE+5]]:2 = (#0 - #1)
- // CHECK-NEXT: File 0, [[@LINE-1]]:3 -> 
[[@LINE+4]]:2 = #3
+  goto b;  

r317760 - [Coverage] Emit deferred regions in headers

2017-11-08 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Nov  8 18:33:40 2017
New Revision: 317760

URL: http://llvm.org/viewvc/llvm-project?rev=317760=rev
Log:
[Coverage] Emit deferred regions in headers

There are some limitations with emitting regions in macro expansions
because we don't gather file IDs within the expansions. Fix the check
that prevents us from emitting deferred regions in expansions to make an
exception for headers, which is something we can handle.

rdar://35373009

Added:
cfe/trunk/test/CoverageMapping/Inputs/deferred-region-helper.h
Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/deferred-region.cpp

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=317760=317759=317760=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Wed Nov  8 18:33:40 2017
@@ -496,12 +496,14 @@ struct CounterCoverageMappingBuilder
 DeferredRegion = None;
 
 // If the region ends in an expansion, find the expansion site.
-if (SM.getFileID(DeferredEndLoc) != SM.getMainFileID()) {
-  FileID StartFile = SM.getFileID(DR.getStartLoc());
+FileID StartFile = SM.getFileID(DR.getStartLoc());
+if (SM.getFileID(DeferredEndLoc) != StartFile) {
   if (isNestedIn(DeferredEndLoc, StartFile)) {
 do {
   DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
 } while (StartFile != SM.getFileID(DeferredEndLoc));
+  } else {
+return Index;
   }
 }
 
@@ -591,7 +593,7 @@ struct CounterCoverageMappingBuilder
   if (!DeferredRegion.hasValue() &&
   // File IDs aren't gathered within macro expansions, so it isn't
   // useful to try and create a deferred region inside of one.
-  (SM.getFileID(EndLoc) == SM.getMainFileID()))
+  !EndLoc.isMacroID())
 DeferredRegion =
 SourceMappingRegion(Counter::getZero(), EndLoc, None);
 }

Added: cfe/trunk/test/CoverageMapping/Inputs/deferred-region-helper.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/Inputs/deferred-region-helper.h?rev=317760=auto
==
--- cfe/trunk/test/CoverageMapping/Inputs/deferred-region-helper.h (added)
+++ cfe/trunk/test/CoverageMapping/Inputs/deferred-region-helper.h Wed Nov  8 
18:33:40 2017
@@ -0,0 +1,5 @@
+void included_func() {
+  if (false)
+return;
+  return;
+}

Modified: cfe/trunk/test/CoverageMapping/deferred-region.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/deferred-region.cpp?rev=317760=317759=317760=diff
==
--- cfe/trunk/test/CoverageMapping/deferred-region.cpp (original)
+++ cfe/trunk/test/CoverageMapping/deferred-region.cpp Wed Nov  8 18:33:40 2017
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++11 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fexceptions -fcxx-exceptions -emit-llvm-only -triple 
%itanium_abi_triple -main-file-name deferred-region.cpp %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fexceptions -fcxx-exceptions -emit-llvm-only -triple 
%itanium_abi_triple -main-file-name deferred-region.cpp -I %S/Inputs %s | 
FileCheck %s
 
 #define IF if
 #define STMT(S) S
@@ -170,6 +170,16 @@ out:
return; // CHECK: Gap,File 0, [[@LINE]]:8 -> [[@LINE+1]]:2 = 0
 }
 
+#include "deferred-region-helper.h"
+// CHECK-LABEL: _Z13included_funcv:
+// CHECK:  Gap,File 0, 2:13 -> 3:5 = #1
+// CHECK:  Gap,File 0, 3:11 -> 4:3 = (#0 - #1)
+
+// CHECK-LABEL: _Z7includev:
+void include() {
+  included_func();
+}
+
 int main() {
   foo(0);
   foo(1);
@@ -189,5 +199,6 @@ int main() {
   for_loop();
   while_loop();
   gotos();
+  include();
   return 0;
 }


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


r317758 - [Coverage] Emit a gap area after if conditions

2017-11-08 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Nov  8 18:33:38 2017
New Revision: 317758

URL: http://llvm.org/viewvc/llvm-project?rev=317758=rev
Log:
[Coverage] Emit a gap area after if conditions

The area immediately after the closing right-paren of an if condition
should have a count equal to the 'then' block's count. Use a gap region
to set this count, so that region highlighting for the 'then' block
remains precise.

This solves a problem we have with wrapped segments. Consider:

  1| if (false)
  2|   foo();

Without a gap area starting after the condition, the wrapped segment
from line 1 would make it look like line 2 is executed, when it's not.

rdar://35373009

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/break.c
cfe/trunk/test/CoverageMapping/casts.c
cfe/trunk/test/CoverageMapping/continue.c
cfe/trunk/test/CoverageMapping/if.cpp
cfe/trunk/test/CoverageMapping/includehell.cpp
cfe/trunk/test/CoverageMapping/label.cpp
cfe/trunk/test/CoverageMapping/macro-expansion.c
cfe/trunk/test/CoverageMapping/macro-expressions.cpp
cfe/trunk/test/CoverageMapping/macroscopes.cpp
cfe/trunk/test/CoverageMapping/moremacros.c
cfe/trunk/test/CoverageMapping/objc.m
cfe/trunk/test/CoverageMapping/preprocessor.c
cfe/trunk/test/CoverageMapping/return.c
cfe/trunk/test/CoverageMapping/switch.cpp
cfe/trunk/test/CoverageMapping/switchmacro.c
cfe/trunk/test/CoverageMapping/test.c
cfe/trunk/test/CoverageMapping/trycatch.cpp

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=317758=317757=317758=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Wed Nov  8 18:33:38 2017
@@ -718,6 +718,19 @@ struct CounterCoverageMappingBuilder
 getRegion().setDeferred(true);
   }
 
+  /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
+  void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
+Counter Count) {
+if (StartLoc == EndLoc || StartLoc.isMacroID() || EndLoc.isMacroID() ||
+!SM.isWrittenInSameFile(StartLoc, EndLoc))
+  return;
+handleFileExit(StartLoc);
+size_t Index = pushRegion(Count, StartLoc, EndLoc);
+getRegion().setGap(true);
+handleFileExit(EndLoc);
+popRegions(Index);
+  }
+
   /// \brief Keep counts of breaks and continues inside loops.
   struct BreakContinue {
 Counter BreakCount;
@@ -1048,12 +1061,19 @@ struct CounterCoverageMappingBuilder
 // counter for the body when looking at the coverage.
 propagateCounts(ParentCount, S->getCond());
 
+// The 'then' count applies to the area immediately after the condition.
+fillGapAreaWithCount(getPreciseTokenLocEnd(getEnd(S->getCond())),
+ getStart(S->getThen()), ThenCount);
+
 extendRegion(S->getThen());
 Counter OutCount = propagateCounts(ThenCount, S->getThen());
 
 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
 if (const Stmt *Else = S->getElse()) {
-  extendRegion(S->getElse());
+  // The 'else' count applies to the area immediately after the 'then'.
+  fillGapAreaWithCount(getPreciseTokenLocEnd(getEnd(S->getThen())),
+   getStart(Else), ElseCount);
+  extendRegion(Else);
   OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
 } else
   OutCount = addCounters(OutCount, ElseCount);
@@ -1090,9 +1110,14 @@ struct CounterCoverageMappingBuilder
 Visit(E->getCond());
 
 if (!isa(E)) {
+  // The 'then' count applies to the area immediately after the condition.
+  fillGapAreaWithCount(E->getQuestionLoc(), getStart(E->getTrueExpr()),
+   TrueCount);
+
   extendRegion(E->getTrueExpr());
   propagateCounts(TrueCount, E->getTrueExpr());
 }
+
 extendRegion(E->getFalseExpr());
 propagateCounts(subtractCounters(ParentCount, TrueCount),
 E->getFalseExpr());

Modified: cfe/trunk/test/CoverageMapping/break.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/break.c?rev=317758=317757=317758=diff
==
--- cfe/trunk/test/CoverageMapping/break.c (original)
+++ cfe/trunk/test/CoverageMapping/break.c Wed Nov  8 18:33:38 2017
@@ -15,7 +15,7 @@ int main() { // CHECK: File 0, [
   }  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = 
((#0 + #3) - #4)
   while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+7]]:4 = #3
  // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:16 = 
#3
-if(cnt == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+3]]:6 = #4
+if(cnt == 0) {   // CHECK: File 

r316704 - [CGBlocks] Improve line info in backtraces containing *_helper_block

2017-10-26 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Thu Oct 26 14:27:24 2017
New Revision: 316704

URL: http://llvm.org/viewvc/llvm-project?rev=316704=rev
Log:
[CGBlocks] Improve line info in backtraces containing *_helper_block

Instead of only setting a non-zero debug location on the return
instruction in *_helper_block functions, set a proper location on all
instructions within these functions. Pick the start location of the
block literal expr for maximum clarity.

The debugger does not step into *_helper_block functions during normal
single-stepping because we mark their parameters as artificial. This is
what we want (the functions are implicitly generated and uninteresting
to most users). The stepping behavior is unchanged by this patch.

rdar://32907581

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

Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp
cfe/trunk/test/CodeGenObjC/debug-info-blocks.m

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=316704=316703=316704=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Thu Oct 26 14:27:24 2017
@@ -1644,10 +1644,8 @@ CodeGenFunction::GenerateCopyHelperFunct
 
   CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
 
-  auto NL = ApplyDebugLocation::CreateEmpty(*this);
   StartFunction(FD, C.VoidTy, Fn, FI, args);
-  // Create a scope with an artificial location for the body of this function.
-  auto AL = ApplyDebugLocation::CreateArtificial(*this);
+  ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
 
   Address src = GetAddrOfLocalVar();
@@ -1816,10 +1814,8 @@ CodeGenFunction::GenerateDestroyHelperFu
 
   CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
 
-  // Create a scope with an artificial location for the body of this function.
-  auto NL = ApplyDebugLocation::CreateEmpty(*this);
   StartFunction(FD, C.VoidTy, Fn, FI, args);
-  auto AL = ApplyDebugLocation::CreateArtificial(*this);
+  ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
 
   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
 

Modified: cfe/trunk/test/CodeGenObjC/debug-info-blocks.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/debug-info-blocks.m?rev=316704=316703=316704=diff
==
--- cfe/trunk/test/CodeGenObjC/debug-info-blocks.m (original)
+++ cfe/trunk/test/CodeGenObjC/debug-info-blocks.m Thu Oct 26 14:27:24 2017
@@ -10,23 +10,20 @@
 // CHECK-NEXT: call void @llvm.dbg.declare(metadata <{ i8*, i32, i32, i8*, 
%struct.__block_descriptor*, %0* }>** %[[ALLOCA]], metadata ![[SELF:[0-9]+]], 
metadata !{{.*}})
 // CHECK-NEXT: call void @llvm.dbg.declare(metadata %1** %d, metadata 
![[D:[0-9]+]], metadata !{{.*}})
 
-// rdar://problem/14386148
-// Test that we don't emit bogus line numbers for the helper functions.
-// Test that we do emit scope info for the helper functions.
+// Test that we do emit scope info for the helper functions, and that the
+// parameters to these functions are marked as artificial (so the debugger
+// doesn't accidentally step into the function).
 // CHECK: define {{.*}} @__copy_helper_block_{{.*}}(i8*, i8*)
 // CHECK-NOT: ret
 // CHECK: call {{.*}}, !dbg ![[DBG_LINE:[0-9]+]]
 // CHECK-NOT: ret
 // CHECK: load {{.*}}, !dbg ![[COPY_LINE:[0-9]+]]
+// CHECK: ret void, !dbg ![[COPY_LINE]]
 // CHECK: define {{.*}} @__destroy_helper_block_{{.*}}(i8*)
 // CHECK-NOT: ret
 // CHECK: load {{.*}}, !dbg ![[DESTROY_LINE:[0-9]+]]
+// CHECK: ret void, !dbg ![[DESTROY_LINE]]
 
-// CHECK-DAG: [[DBG_LINE]] = !DILocation(line: 0, scope: ![[COPY_SP:[0-9]+]])
-// CHECK-DAG: [[COPY_LINE]] = !DILocation(line: 0, scope: ![[COPY_SP:[0-9]+]])
-// CHECK-DAG: [[COPY_SP]] = distinct !DISubprogram(name: "__copy_helper_block_"
-// CHECK-DAG: [[DESTROY_LINE]] = !DILocation(line: 0, scope: 
![[DESTROY_SP:[0-9]+]])
-// CHECK-DAG: [[DESTROY_SP]] = distinct !DISubprogram(name: 
"__destroy_helper_block_"
 typedef unsigned int NSUInteger;
 
 @protocol NSObject
@@ -60,6 +57,14 @@ static void run(void (^block)(void))
 - (id)init
 {
 if ((self = [super init])) {
+  // CHECK-DAG: [[DBG_LINE]] = !DILocation(line: 0, scope: 
![[COPY_SP:[0-9]+]])
+  // CHECK-DAG: [[COPY_LINE]] = !DILocation(line: [[@LINE+7]], scope: 
![[COPY_SP:[0-9]+]])
+  // CHECK-DAG: [[COPY_SP]] = distinct !DISubprogram(name: 
"__copy_helper_block_"
+  // CHECK-DAG: [[DESTROY_LINE]] = !DILocation(line: [[@LINE+5]], scope: 
![[DESTROY_SP:[0-9]+]])
+  // CHECK-DAG: [[DESTROY_SP]] = distinct !DISubprogram(name: 
"__destroy_helper_block_"
+  // CHECK-DAG: !DILocalVariable(arg: 1, scope: ![[COPY_SP]], {{.*}}, 
flags: DIFlagArtificial)
+  // CHECK-DAG: !DILocalVariable(arg: 2, scope: ![[COPY_SP]], {{.*}}, 

r315982 - [Coverage] Discard deferred region in closing if-else

2017-10-17 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Tue Oct 17 00:47:39 2017
New Revision: 315982

URL: http://llvm.org/viewvc/llvm-project?rev=315982=rev
Log:
[Coverage] Discard deferred region in closing if-else

A trailing deferred region isn't necessary in a function that ends with
this pattern:

  ...
  else {
...
return;
  }

Special-case this pattern so that the closing curly brace of the
function isn't marked as uncovered. This issue came up in PR34962.

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/deferred-region.cpp

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=315982=315981=315982=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Tue Oct 17 00:47:39 2017
@@ -758,6 +758,22 @@ struct CounterCoverageMappingBuilder
 handleFileExit(getEnd(S));
   }
 
+  /// Determine whether the final deferred region emitted in \p Body should be
+  /// discarded.
+  static bool discardFinalDeferredRegionInDecl(Stmt *Body) {
+if (auto *CS = dyn_cast(Body)) {
+  Stmt *LastStmt = CS->body_back();
+  if (auto *IfElse = dyn_cast(LastStmt)) {
+if (auto *Else = dyn_cast_or_null(IfElse->getElse()))
+  LastStmt = Else->body_back();
+else
+  LastStmt = IfElse->getElse();
+  }
+  return dyn_cast_or_null(LastStmt);
+}
+return false;
+  }
+
   void VisitDecl(const Decl *D) {
 assert(!DeferredRegion && "Deferred region never completed");
 
@@ -770,14 +786,14 @@ struct CounterCoverageMappingBuilder
 Counter ExitCount = propagateCounts(getRegionCounter(Body), Body);
 assert(RegionStack.empty() && "Regions entered but never exited");
 
-// Special case: if the last statement is a return, throw away the
-// deferred region. This allows the closing brace to have a count.
-if (auto *CS = dyn_cast_or_null(Body))
-  if (dyn_cast_or_null(CS->body_back()))
+if (DeferredRegion) {
+  // Complete (or discard) any deferred regions introduced by the last
+  // statement.
+  if (discardFinalDeferredRegionInDecl(Body))
 DeferredRegion = None;
-
-// Complete any deferred regions introduced by the last statement.
-popRegions(completeDeferred(ExitCount, getEnd(Body)));
+  else
+popRegions(completeDeferred(ExitCount, getEnd(Body)));
+}
   }
 
   void VisitReturnStmt(const ReturnStmt *S) {

Modified: cfe/trunk/test/CoverageMapping/deferred-region.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/deferred-region.cpp?rev=315982=315981=315982=diff
==
--- cfe/trunk/test/CoverageMapping/deferred-region.cpp (original)
+++ cfe/trunk/test/CoverageMapping/deferred-region.cpp Tue Oct 17 00:47:39 2017
@@ -31,11 +31,28 @@ void baz() { // CHECK: [[@LINE]]:12 -> [
 // CHECK-LABEL: _Z3mazv:
 void maz() {
   if (true)
-return; // CHECK: Gap,File 0, [[@LINE]]:11 -> 36:3 = (#0 - #1)
+return; // CHECK: Gap,File 0, [[@LINE]]:11 -> [[@LINE+2]]:3 = (#0 - #1)
 
   return; // CHECK-NOT: Gap
 }
 
+// CHECK-LABEL: _Z4maazv:
+void maaz() {
+  if (true)
+return; // CHECK: Gap,File 0, [[@LINE]]:11
+  else
+return; // CHECK-NOT: Gap,File 0, [[@LINE]]
+}
+
+// CHECK-LABEL: _Z5maaazv:
+void maaaz() {
+  if (true) {
+return;
+  } else {  // CHECK: Gap,File 0, [[@LINE]]:4 -> [[@LINE]]:10
+return; // CHECK-NOT: Gap,File 0, [[@LINE]]
+  }
+}
+
 // CHECK-LABEL: _Z3bari:
 void bar(int x) {
   IF (x)
@@ -158,6 +175,9 @@ int main() {
   foo(1);
   fooo(0);
   fooo(1);
+  maz();
+  maaz();
+  maaaz();
   baz();
   bar(0);
   bar(1);


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


r315979 - [Coverage] Explicitly mark the l.h.s of && and || (fixes PR33465)

2017-10-17 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Mon Oct 16 23:51:54 2017
New Revision: 315979

URL: http://llvm.org/viewvc/llvm-project?rev=315979=rev
Log:
[Coverage] Explicitly mark the l.h.s of && and || (fixes PR33465)

This makes it possible to view sub-line region counts for the l.h.s of
&& and || expressions in coverage reports.

It also fixes PR33465, which shows an example of incorrect coverage
output for an assignment statement containing '||'.

Modified:
cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
cfe/trunk/test/CoverageMapping/logical.cpp
cfe/trunk/test/CoverageMapping/macro-expansion.c

Modified: cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp?rev=315979=315978=315979=diff
==
--- cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp (original)
+++ cfe/trunk/lib/CodeGen/CoverageMappingGen.cpp Mon Oct 16 23:51:54 2017
@@ -1083,16 +1083,18 @@ struct CounterCoverageMappingBuilder
   }
 
   void VisitBinLAnd(const BinaryOperator *E) {
-extendRegion(E);
-Visit(E->getLHS());
+extendRegion(E->getLHS());
+propagateCounts(getRegion().getCounter(), E->getLHS());
+handleFileExit(getEnd(E->getLHS()));
 
 extendRegion(E->getRHS());
 propagateCounts(getRegionCounter(E), E->getRHS());
   }
 
   void VisitBinLOr(const BinaryOperator *E) {
-extendRegion(E);
-Visit(E->getLHS());
+extendRegion(E->getLHS());
+propagateCounts(getRegion().getCounter(), E->getLHS());
+handleFileExit(getEnd(E->getLHS()));
 
 extendRegion(E->getRHS());
 propagateCounts(getRegionCounter(E), E->getRHS());

Modified: cfe/trunk/test/CoverageMapping/logical.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/logical.cpp?rev=315979=315978=315979=diff
==
--- cfe/trunk/test/CoverageMapping/logical.cpp (original)
+++ cfe/trunk/test/CoverageMapping/logical.cpp Mon Oct 16 23:51:54 2017
@@ -1,13 +1,18 @@
 // RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -emit-llvm-only -main-file-name logical.cpp %s | 
FileCheck %s
 
-int main() {// CHECK: File 0, [[@LINE]]:12 -> 
[[@LINE+10]]:2 = #0
+int main() {// CHECK: File 0, [[@LINE]]:12 -> 
[[@LINE+15]]:2 = #0
   bool bt = true;
   bool bf = false;
-  bool a = bt && bf;// CHECK-NEXT: File 0, [[@LINE]]:18 -> 
[[@LINE]]:20 = #1
-  a = bt &&
+  bool a = bt && bf;// CHECK-NEXT: File 0, [[@LINE]]:12 -> 
[[@LINE]]:14 = #0
+// CHECK-NEXT: File 0, [[@LINE-1]]:18 -> 
[[@LINE-1]]:20 = #1
+
+  a = bt && // CHECK-NEXT: File 0, [[@LINE]]:7 -> 
[[@LINE]]:9 = #0
   bf;   // CHECK-NEXT: File 0, [[@LINE]]:7 -> 
[[@LINE]]:9 = #2
-  a = bf || bt; // CHECK-NEXT: File 0, [[@LINE]]:13 -> 
[[@LINE]]:15 = #3
-  a = bf ||
+
+  a = bf || bt; // CHECK-NEXT: File 0, [[@LINE]]:7 -> 
[[@LINE]]:9 = #0
+// CHECK-NEXT: File 0, [[@LINE-1]]:13 -> 
[[@LINE-1]]:15 = #3
+
+  a = bf || // CHECK-NEXT: File 0, [[@LINE]]:7 -> 
[[@LINE]]:9 = #0
   bt;   // CHECK-NEXT: File 0, [[@LINE]]:7 -> 
[[@LINE]]:9 = #4
   return 0;
 }

Modified: cfe/trunk/test/CoverageMapping/macro-expansion.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CoverageMapping/macro-expansion.c?rev=315979=315978=315979=diff
==
--- cfe/trunk/test/CoverageMapping/macro-expansion.c (original)
+++ cfe/trunk/test/CoverageMapping/macro-expansion.c Mon Oct 16 23:51:54 2017
@@ -23,10 +23,12 @@
 // CHECK-NEXT: Expansion,File 4, [[@LINE+2]]:20 -> [[@LINE+2]]:22 = (#0 + #8)
 // CHECK-NEXT: File 4, [[@LINE+1]]:36 -> [[@LINE+1]]:37 = (#0 + #8)
 #define M3(x) do { M2(x); } while (0)
-// CHECK-NEXT: File 5, [[@LINE+2]]:15 -> [[@LINE+2]]:27 = #0
+// CHECK-NEXT: File 5, [[@LINE+3]]:15 -> [[@LINE+3]]:27 = #0
+// CHECK-NEXT: File 5, [[@LINE+2]]:16 -> [[@LINE+2]]:19 = #0
 // CHECK-NEXT: File 5, [[@LINE+1]]:23 -> [[@LINE+1]]:26 = #12
 #define M4(x) ((x) && (x))
-// CHECK-NEXT: File 6, [[@LINE+2]]:15 -> [[@LINE+2]]:27 = #0
+// CHECK-NEXT: File 6, [[@LINE+3]]:15 -> [[@LINE+3]]:27 = #0
+// CHECK-NEXT: File 6, [[@LINE+2]]:16 -> [[@LINE+2]]:19 = #0
 // CHECK-NEXT: File 6, [[@LINE+1]]:23 -> [[@LINE+1]]:26 = #14
 #define M5(x) ((x) || (x))
 // CHECK-NEXT: File 7, [[@LINE+1]]:15 -> [[@LINE+1]]:26 = #0


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


Re: r313096 - [ubsan] Function Sanitizer: Don't require writable text segments

2017-10-13 Thread Vedant Kumar via cfe-commits
 but I don't know how we'd ever get there. Consider:
>> 
>> ---
>> class A {
>> public:
>>   virtual int f() = 0;
>> };
>> 
>> class B : public A {
>>   int f() { return 42; }
>> };
>> 
>> struct C {
>>   void g() {}
>>   static void h() {}
>> };
>> 
>> int main() {
>>   auto h = ::h;
>>   h(); // type checked
>> 
>>   C c;
>>   void (C::*g)() = ::g;
>>   (c.*g)(); // not checked
>> 
>>   int (A::*f)() = ::f;
>>   A *a = new B;
>>   return (a->*f)(); // not checked
>> }
>> ---
>> 
>> So, I'm not sure how we would get into a situation where we compute 
>> "_ZTv0_n24_N1B1fEz + (@0 -_ZN1B1fEz)".
>> 
>> Right, my point was that we wouldn't get into such a situation. I'm sorry if 
>> I was unclear.
> 
> Oh, in that case were you suggesting that simply storing "(@0 -_ZN1B1fEz)" in 
> the prologue for _ZTv0_n24_N1B1fEz would cause the backend error ("Cannot 
> represent a difference...")?
> 
> Yes, exactly. The basic problem is that object format relocations generally 
> cannot represent the difference between two arbitrary symbols, but they can 
> represent the difference between a symbol and the current address (i.e. in 
> this case, the address of the offset in the prologue data), plus a constant 
> addend (this is known as a PC-relative relocation). So if the RHS of the 
> subtraction can be resolved to the current address (or an address with an 
> assembler-constant offset from the current address), the reference can be 
> represented using a PC-relative relocation (with the offset from the start of 
> the prologue data being used as the addend). In this case, the difference 
> between the symbols _ZTv0_n24_N1B1fEz and _ZN1B1fEz is not known to the 
> assembler if -ffunction-sections is enabled because the symbols are defined 
> in different sections and the linker is free to put them at any location 
> relative to each other, so a constant addend cannot be computed and the 
> assembler errors out.

Thank you, that makes total sense.

vedant

> 
> Peter
> 
> Sorry, I haven't fully worked out the root cause of that failure.
> 
>>  
>> In the last code example I posted, there are also no calls to the function 
>> type check handler.
>> 
>> At any rate, I implemented your idea to not emit signatures for virtual 
>> methods:
>> https://reviews.llvm.org/D38913 <https://reviews.llvm.org/D38913>
>> 
>> It's at least good for a code size savings, and it might fix the issue Eric 
>> and Han are seeing. I'd appreciate any feedback.
>> 
>> Thanks, I will take a look.
> 
> Thanks for the review!
> 
> vedant
> 
>> 
>> Peter
>> 
>> 
>> thanks,
>> vedant
>> 
>> 
>>> 
>>> Peter
>>> 
>>> 
>>> vedant
>>> 
>>>> 
>>>> Peter
>>>> 
>>>> On Fri, Oct 13, 2017 at 3:06 PM, Vedant Kumar <v...@apple.com 
>>>> <mailto:v...@apple.com>> wrote:
>>>> 
>>>>> On Oct 13, 2017, at 2:52 PM, Eric Christopher <echri...@gmail.com 
>>>>> <mailto:echri...@gmail.com>> wrote:
>>>>> 
>>>>> 
>>>>> 
>>>>> On Fri, Oct 13, 2017 at 2:50 PM Vedant Kumar <v...@apple.com 
>>>>> <mailto:v...@apple.com>> wrote:
>>>>>> On Oct 13, 2017, at 1:44 PM, Eric Christopher <echri...@gmail.com 
>>>>>> <mailto:echri...@gmail.com>> wrote:
>>>>>> 
>>>>>> 
>>>>>> 
>>>>>> On Fri, Oct 13, 2017 at 1:42 PM Vedant Kumar <v...@apple.com 
>>>>>> <mailto:v...@apple.com>> wrote:
>>>>>>> On Oct 13, 2017, at 1:39 PM, Vedant Kumar <v...@apple.com 
>>>>>>> <mailto:v...@apple.com>> wrote:
>>>>>>> 
>>>>>>> Hey Eric,
>>>>>>> 
>>>>>>> I'm sorry for the breakage. I made sure to check the run-time tests in 
>>>>>>> compiler-rt but we could have missing coverage there.
>>>>>>> 
>>>>>>> The original version of this patch restricted the prologue data changes 
>>>>>>> to Darwin only. We can switch back to that easily, just let me know.
>>>>>> 
>>>>>> Actually I'll go ahead and work a patch up.
>>>>>> 
>>>>>> 
>>>>>> Appreciated :)

r315786 - [ubsan] Don't emit function signatures for non-static member functions

2017-10-13 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Fri Oct 13 18:23:30 2017
New Revision: 315786

URL: http://llvm.org/viewvc/llvm-project?rev=315786=rev
Log:
[ubsan] Don't emit function signatures for non-static member functions

The function sanitizer only checks indirect calls through function
pointers. This excludes all non-static member functions (constructor
calls, calls through thunks, etc. all use a separate code path). Don't
emit function signatures for functions that won't be checked.

Apart from cutting down on code size, this should fix a regression on
Linux caused by r313096. For context, see the mailing list discussion:

r313096 - [ubsan] Function Sanitizer: Don't require writable text segments

Testing: check-clang, check-ubsan

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

Modified:
cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp

Modified: cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenFunction.cpp?rev=315786=315785=315786=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenFunction.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenFunction.cpp Fri Oct 13 18:23:30 2017
@@ -789,6 +789,15 @@ static bool matchesStlAllocatorFn(const
   return true;
 }
 
+/// Return the UBSan prologue signature for \p FD if one is available.
+static llvm::Constant *getPrologueSignature(CodeGenModule ,
+const FunctionDecl *FD) {
+  if (const auto *MD = dyn_cast(FD))
+if (!MD->isStatic())
+  return nullptr;
+  return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
+}
+
 void CodeGenFunction::StartFunction(GlobalDecl GD,
 QualType RetTy,
 llvm::Function *Fn,
@@ -908,8 +917,7 @@ void CodeGenFunction::StartFunction(Glob
   // prologue data.
   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
 if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
-  if (llvm::Constant *PrologueSig =
-  CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
+  if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
 llvm::Constant *FTRTTIConst =
 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
 llvm::Constant *FTRTTIConstEncoded =

Modified: cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp?rev=315786=315785=315786=diff
==
--- cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp Fri Oct 13 18:23:30 2017
@@ -426,6 +426,66 @@ void indirect_function_call(void (*p)(in
   p(42);
 }
 
+namespace FunctionSanitizerVirtualCalls {
+struct A {
+  virtual void f() {}
+  virtual void g() {}
+  void h() {}
+};
+
+struct B : virtual A {
+  virtual void b() {}
+  virtual void f();
+  void g() final {}
+  static void q() {}
+};
+
+void B::f() {}
+
+void force_irgen() {
+  A a;
+  a.g();
+  a.h();
+
+  B b;
+  b.f();
+  b.b();
+  b.g();
+  B::q();
+}
+
+// CHECK-LABEL: define void @_ZN29FunctionSanitizerVirtualCalls1B1fEv
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define void @_ZTv0_n24_N29FunctionSanitizerVirtualCalls1B1fEv
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define void 
@_ZN29FunctionSanitizerVirtualCalls11force_irgenEv()
+// CHECK: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1AC1Ev
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1A1gEv
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1A1hEv
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1BC1Ev
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1B1bEv
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1B1gEv
+// CHECK-NOT: prologue
+//
+// CHECK-LABEL: define linkonce_odr void 
@_ZN29FunctionSanitizerVirtualCalls1B1qEv
+// CHECK: prologue
+
+}
+
 namespace UpcastPointerTest {
 struct S {};
 struct T : S { double d; };


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


Re: r313096 - [ubsan] Function Sanitizer: Don't require writable text segments

2017-10-13 Thread Vedant Kumar via cfe-commits
oint was that we wouldn't get into such a situation. I'm sorry if 
> I was unclear.

Oh, in that case were you suggesting that simply storing "(@0 -_ZN1B1fEz)" in 
the prologue for _ZTv0_n24_N1B1fEz would cause the backend error ("Cannot 
represent a difference...")?

Sorry, I haven't fully worked out the root cause of that failure.

>  
> In the last code example I posted, there are also no calls to the function 
> type check handler.
> 
> At any rate, I implemented your idea to not emit signatures for virtual 
> methods:
> https://reviews.llvm.org/D38913 <https://reviews.llvm.org/D38913>
> 
> It's at least good for a code size savings, and it might fix the issue Eric 
> and Han are seeing. I'd appreciate any feedback.
> 
> Thanks, I will take a look.

Thanks for the review!

vedant

> 
> Peter
> 
> 
> thanks,
> vedant
> 
> 
>> 
>> Peter
>> 
>> 
>> vedant
>> 
>>> 
>>> Peter
>>> 
>>> On Fri, Oct 13, 2017 at 3:06 PM, Vedant Kumar <v...@apple.com 
>>> <mailto:v...@apple.com>> wrote:
>>> 
>>>> On Oct 13, 2017, at 2:52 PM, Eric Christopher <echri...@gmail.com 
>>>> <mailto:echri...@gmail.com>> wrote:
>>>> 
>>>> 
>>>> 
>>>> On Fri, Oct 13, 2017 at 2:50 PM Vedant Kumar <v...@apple.com 
>>>> <mailto:v...@apple.com>> wrote:
>>>>> On Oct 13, 2017, at 1:44 PM, Eric Christopher <echri...@gmail.com 
>>>>> <mailto:echri...@gmail.com>> wrote:
>>>>> 
>>>>> 
>>>>> 
>>>>> On Fri, Oct 13, 2017 at 1:42 PM Vedant Kumar <v...@apple.com 
>>>>> <mailto:v...@apple.com>> wrote:
>>>>>> On Oct 13, 2017, at 1:39 PM, Vedant Kumar <v...@apple.com 
>>>>>> <mailto:v...@apple.com>> wrote:
>>>>>> 
>>>>>> Hey Eric,
>>>>>> 
>>>>>> I'm sorry for the breakage. I made sure to check the run-time tests in 
>>>>>> compiler-rt but we could have missing coverage there.
>>>>>> 
>>>>>> The original version of this patch restricted the prologue data changes 
>>>>>> to Darwin only. We can switch back to that easily, just let me know.
>>>>> 
>>>>> Actually I'll go ahead and work a patch up.
>>>>> 
>>>>> 
>>>>> Appreciated :)
>>>>> 
>>>>> Basically we were getting an error of:
>>>>> 
>>>>> error: Cannot represent a difference across sections
>>>>> 
>>>>> trying to compile things with the current code.
>>>> 
>>>> Oh I see.. well, we started using a difference between the address of a 
>>>> function and the address of a global, so the error makes sense.
>>>> 
>>>> I'd be interested in any factors that could narrow the problem down (e.g 
>>>> using a specific linker, using -ffunction-sections, using data-sections, 
>>>> etc). Basically I'm not sure why this would work on some Linux setups but 
>>>> not others.
>>>> 
>>>> 
>>>> Definitely using the latter two options and gold as a linker. I'll see 
>>>> what Han can come up with.
>>> 
>>> Gotcha. Well, -ffunction-sections appears to be untested in 
>>> compiler-rt/test/ubsan, at least.
>>> 
>>> There's a test somewhere in there called function.cpp -- it would be great 
>>> if we could cover the *-sections options there. I'm not sure whether that's 
>>> what caused the failure, but the extra coverage couldn't hurt :). I would 
>>> do it myself but I don't have a Linux machine to test on.
>>> 
>>> vedant
>>> 
>>>>  
>>>> While we figure that out here's a patch to limit the impact on non-Darwin 
>>>> platforms:
>>>> https://reviews.llvm.org/D38903 <https://reviews.llvm.org/D38903>
>>>> 
>>>> *goes a looking*
>>>> 
>>>> Thanks!
>>>> 
>>>> -eric 
>>>> 
>>>> vedant
>>>> 
>>>>> 
>>>>> Thanks!
>>>>> 
>>>>> -eric
>>>>>  
>>>>> vedant
>>>>> 
>>>>>> 
>>>>>> vedant
>>>>>> 
>>>>>> 
>>>>>>> On Oct 13, 2017, at 1:33 PM, Eric Christopher <echri...@gmail.com 

Re: r313096 - [ubsan] Function Sanitizer: Don't require writable text segments

2017-10-13 Thread Vedant Kumar via cfe-commits
50 PM Vedant Kumar <v...@apple.com 
>>> <mailto:v...@apple.com>> wrote:
>>>> On Oct 13, 2017, at 1:44 PM, Eric Christopher <echri...@gmail.com 
>>>> <mailto:echri...@gmail.com>> wrote:
>>>> 
>>>> 
>>>> 
>>>> On Fri, Oct 13, 2017 at 1:42 PM Vedant Kumar <v...@apple.com 
>>>> <mailto:v...@apple.com>> wrote:
>>>>> On Oct 13, 2017, at 1:39 PM, Vedant Kumar <v...@apple.com 
>>>>> <mailto:v...@apple.com>> wrote:
>>>>> 
>>>>> Hey Eric,
>>>>> 
>>>>> I'm sorry for the breakage. I made sure to check the run-time tests in 
>>>>> compiler-rt but we could have missing coverage there.
>>>>> 
>>>>> The original version of this patch restricted the prologue data changes 
>>>>> to Darwin only. We can switch back to that easily, just let me know.
>>>> 
>>>> Actually I'll go ahead and work a patch up.
>>>> 
>>>> 
>>>> Appreciated :)
>>>> 
>>>> Basically we were getting an error of:
>>>> 
>>>> error: Cannot represent a difference across sections
>>>> 
>>>> trying to compile things with the current code.
>>> 
>>> Oh I see.. well, we started using a difference between the address of a 
>>> function and the address of a global, so the error makes sense.
>>> 
>>> I'd be interested in any factors that could narrow the problem down (e.g 
>>> using a specific linker, using -ffunction-sections, using data-sections, 
>>> etc). Basically I'm not sure why this would work on some Linux setups but 
>>> not others.
>>> 
>>> 
>>> Definitely using the latter two options and gold as a linker. I'll see what 
>>> Han can come up with.
>> 
>> Gotcha. Well, -ffunction-sections appears to be untested in 
>> compiler-rt/test/ubsan, at least.
>> 
>> There's a test somewhere in there called function.cpp -- it would be great 
>> if we could cover the *-sections options there. I'm not sure whether that's 
>> what caused the failure, but the extra coverage couldn't hurt :). I would do 
>> it myself but I don't have a Linux machine to test on.
>> 
>> vedant
>> 
>>>  
>>> While we figure that out here's a patch to limit the impact on non-Darwin 
>>> platforms:
>>> https://reviews.llvm.org/D38903 <https://reviews.llvm.org/D38903>
>>> 
>>> *goes a looking*
>>> 
>>> Thanks!
>>> 
>>> -eric 
>>> 
>>> vedant
>>> 
>>>> 
>>>> Thanks!
>>>> 
>>>> -eric
>>>>  
>>>> vedant
>>>> 
>>>>> 
>>>>> vedant
>>>>> 
>>>>> 
>>>>>> On Oct 13, 2017, at 1:33 PM, Eric Christopher <echri...@gmail.com 
>>>>>> <mailto:echri...@gmail.com>> wrote:
>>>>>> 
>>>>>> Hi Vedant,
>>>>>> 
>>>>>> So this actually broke -fsanitize=function on linux. Han is working up a 
>>>>>> testcase for it, but letting you know for now that we'll probably need 
>>>>>> some change here.
>>>>>> 
>>>>>> -eric
>>>>>> 
>>>>>> On Tue, Sep 12, 2017 at 5:05 PM Vedant Kumar via cfe-commits 
>>>>>> <cfe-commits@lists.llvm.org <mailto:cfe-commits@lists.llvm.org>> wrote:
>>>>>> Author: vedantk
>>>>>> Date: Tue Sep 12 17:04:35 2017
>>>>>> New Revision: 313096
>>>>>> 
>>>>>> URL: http://llvm.org/viewvc/llvm-project?rev=313096=rev 
>>>>>> <http://llvm.org/viewvc/llvm-project?rev=313096=rev>
>>>>>> Log:
>>>>>> [ubsan] Function Sanitizer: Don't require writable text segments
>>>>>> 
>>>>>> This change will make it possible to use -fsanitize=function on Darwin 
>>>>>> and
>>>>>> possibly on other platforms. It fixes an issue with the way RTTI is 
>>>>>> stored into
>>>>>> function prologue data.
>>>>>> 
>>>>>> On Darwin, addresses stored in prologue data can't require run-time 
>>>>>> fixups and
>>>>>> must be PC-relative. Run-time fixups are undesirable because they 
>>>>>> necessitate
>&g

Re: r313096 - [ubsan] Function Sanitizer: Don't require writable text segments

2017-10-13 Thread Vedant Kumar via cfe-commits

> On Oct 13, 2017, at 4:08 PM, Peter Collingbourne <pe...@pcc.me.uk> wrote:
> 
> On Fri, Oct 13, 2017 at 4:06 PM, Peter Collingbourne <pe...@pcc.me.uk 
> <mailto:pe...@pcc.me.uk>> wrote:
> Here's a small reproducer.
> 
> struct A {
>   virtual void f(...);
> };
> 
> struct B : virtual A {
>   virtual void b();
>   virtual void f(...);
> };
> 
> void B::f(...) {}
> 
> $ clang++ -fsanitize=function fsan.cpp -ffunction-sections -fdata-sections -c 
> -o /dev/null
> fatal error: error in backend: Cannot represent a difference across sections
> 
> Looking at the IR I see this function definition:
> define void @_ZTv0_n24_N1B1fEz(%struct.B* %this, ...) unnamed_addr #0 align 2 
> prologue <{ i32, i32 }> <{ i32 846595819, i32 trunc (i64 sub (i64 ptrtoint 
> (i8** @0 to i64), i64 ptrtoint (void (%struct.B*, ...)* @_ZN1B1fEz to i64)) 
> to i32) }> {
> which appears to cause the error.
> 
> I get basically the same IR if I use a Darwin target triple, so this isn't a 
> Linux-specific issue. (On Darwin we end up successfully creating an object 
> file, but the embedded offset in the text section will presumably be 
> incorrect.)
> 
> Note that we're emitting prologue data on virtual functions, which is 
> unnecessary because -fsanitize=function only checks indirect calls via 
> function pointers. So I imagine that one way to solve the problem would be to 
> turn off prologue data emission on non-virtual functions.
> 
> Sorry, I meant "limit prologue data emission to non-virtual functions".

That's independently a great idea :).

I don't see a problem in the IR you've showed above, however. Why do you expect 
the embedded offset to be incorrect? This program links and runs fine on Darwin:

---
struct A {
  virtual void f(...) {}
};

struct B : virtual A {
  virtual void b() {}
  virtual void f(...);
};

void B::f(...) {}

int main() {
  A a;
  a.f();

  B b;
  b.f();
  b.b();
  return 0;
}
---

The "Cannot represent difference..." error appears limited to ELF and Wasm, 
afaik.

vedant

> 
> Peter
> 
> On Fri, Oct 13, 2017 at 3:06 PM, Vedant Kumar <v...@apple.com 
> <mailto:v...@apple.com>> wrote:
> 
>> On Oct 13, 2017, at 2:52 PM, Eric Christopher <echri...@gmail.com 
>> <mailto:echri...@gmail.com>> wrote:
>> 
>> 
>> 
>> On Fri, Oct 13, 2017 at 2:50 PM Vedant Kumar <v...@apple.com 
>> <mailto:v...@apple.com>> wrote:
>>> On Oct 13, 2017, at 1:44 PM, Eric Christopher <echri...@gmail.com 
>>> <mailto:echri...@gmail.com>> wrote:
>>> 
>>> 
>>> 
>>> On Fri, Oct 13, 2017 at 1:42 PM Vedant Kumar <v...@apple.com 
>>> <mailto:v...@apple.com>> wrote:
>>>> On Oct 13, 2017, at 1:39 PM, Vedant Kumar <v...@apple.com 
>>>> <mailto:v...@apple.com>> wrote:
>>>> 
>>>> Hey Eric,
>>>> 
>>>> I'm sorry for the breakage. I made sure to check the run-time tests in 
>>>> compiler-rt but we could have missing coverage there.
>>>> 
>>>> The original version of this patch restricted the prologue data changes to 
>>>> Darwin only. We can switch back to that easily, just let me know.
>>> 
>>> Actually I'll go ahead and work a patch up.
>>> 
>>> 
>>> Appreciated :)
>>> 
>>> Basically we were getting an error of:
>>> 
>>> error: Cannot represent a difference across sections
>>> 
>>> trying to compile things with the current code.
>> 
>> Oh I see.. well, we started using a difference between the address of a 
>> function and the address of a global, so the error makes sense.
>> 
>> I'd be interested in any factors that could narrow the problem down (e.g 
>> using a specific linker, using -ffunction-sections, using data-sections, 
>> etc). Basically I'm not sure why this would work on some Linux setups but 
>> not others.
>> 
>> 
>> Definitely using the latter two options and gold as a linker. I'll see what 
>> Han can come up with.
> 
> Gotcha. Well, -ffunction-sections appears to be untested in 
> compiler-rt/test/ubsan, at least.
> 
> There's a test somewhere in there called function.cpp -- it would be great if 
> we could cover the *-sections options there. I'm not sure whether that's what 
> caused the failure, but the extra coverage couldn't hurt :). I would do it 
> myself but I don't have a Linux machine to test on.
> 
> vedant
> 
>>  
>> While we figure that out here's a patch to limit the impact on non-Darwin 
>> platforms:
>> https://r

  1   2   3   4   5   6   >