Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/tools/driver/cc1_main.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This is the entry point to the clang -cc1 functionality, which implements the
10
// core compiler functionality along with a number of additional tools for
11
// demonstration and testing purposes.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "clang/Basic/Stack.h"
16
#include "clang/Basic/TargetOptions.h"
17
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
18
#include "clang/Config/config.h"
19
#include "clang/Driver/DriverDiagnostic.h"
20
#include "clang/Driver/Options.h"
21
#include "clang/Frontend/CompilerInstance.h"
22
#include "clang/Frontend/CompilerInvocation.h"
23
#include "clang/Frontend/FrontendDiagnostic.h"
24
#include "clang/Frontend/TextDiagnosticBuffer.h"
25
#include "clang/Frontend/TextDiagnosticPrinter.h"
26
#include "clang/Frontend/Utils.h"
27
#include "clang/FrontendTool/Utils.h"
28
#include "llvm/ADT/Statistic.h"
29
#include "llvm/Config/llvm-config.h"
30
#include "llvm/LinkAllPasses.h"
31
#include "llvm/Option/Arg.h"
32
#include "llvm/Option/ArgList.h"
33
#include "llvm/Option/OptTable.h"
34
#include "llvm/Support/BuryPointer.h"
35
#include "llvm/Support/Compiler.h"
36
#include "llvm/Support/ErrorHandling.h"
37
#include "llvm/Support/ManagedStatic.h"
38
#include "llvm/Support/Path.h"
39
#include "llvm/Support/Signals.h"
40
#include "llvm/Support/TargetRegistry.h"
41
#include "llvm/Support/TargetSelect.h"
42
#include "llvm/Support/TimeProfiler.h"
43
#include "llvm/Support/Timer.h"
44
#include "llvm/Support/raw_ostream.h"
45
#include "llvm/Target/TargetMachine.h"
46
#include <cstdio>
47
48
#ifdef CLANG_HAVE_RLIMITS
49
#include <sys/resource.h>
50
#endif
51
52
using namespace clang;
53
using namespace llvm::opt;
54
55
//===----------------------------------------------------------------------===//
56
// Main driver
57
//===----------------------------------------------------------------------===//
58
59
static void LLVMErrorHandler(void *UserData, const std::string &Message,
60
0
                             bool GenCrashDiag) {
61
0
  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
62
0
63
0
  Diags.Report(diag::err_fe_error_backend) << Message;
64
0
65
0
  // Run the interrupt handlers to make sure any special cleanups get done, in
66
0
  // particular that we remove files registered with RemoveFileOnSignal.
67
0
  llvm::sys::RunInterruptHandlers();
68
0
69
0
  // We cannot recover from llvm errors.  When reporting a fatal error, exit
70
0
  // with status 70 to generate crash diagnostics.  For BSD systems this is
71
0
  // defined as an internal software error.  Otherwise, exit with status 1.
72
0
  exit(GenCrashDiag ? 70 : 1);
73
0
}
74
75
#ifdef LINK_POLLY_INTO_TOOLS
76
namespace polly {
77
void initializePollyPasses(llvm::PassRegistry &Registry);
78
}
79
#endif
80
81
#ifdef CLANG_HAVE_RLIMITS
82
#if defined(__linux__) && defined(__PIE__)
83
static size_t getCurrentStackAllocation() {
84
  // If we can't compute the current stack usage, allow for 512K of command
85
  // line arguments and environment.
86
  size_t Usage = 512 * 1024;
87
  if (FILE *StatFile = fopen("/proc/self/stat", "r")) {
88
    // We assume that the stack extends from its current address to the end of
89
    // the environment space. In reality, there is another string literal (the
90
    // program name) after the environment, but this is close enough (we only
91
    // need to be within 100K or so).
92
    unsigned long StackPtr, EnvEnd;
93
    // Disable silly GCC -Wformat warning that complains about length
94
    // modifiers on ignored format specifiers. We want to retain these
95
    // for documentation purposes even though they have no effect.
96
#if defined(__GNUC__) && !defined(__clang__)
97
#pragma GCC diagnostic push
98
#pragma GCC diagnostic ignored "-Wformat"
99
#endif
100
    if (fscanf(StatFile,
101
               "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
102
               "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
103
               "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
104
               "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
105
               &StackPtr, &EnvEnd) == 2) {
106
#if defined(__GNUC__) && !defined(__clang__)
107
#pragma GCC diagnostic pop
108
#endif
109
      Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
110
    }
111
    fclose(StatFile);
112
  }
113
  return Usage;
114
}
115
116
#include <alloca.h>
117
118
LLVM_ATTRIBUTE_NOINLINE
119
static void ensureStackAddressSpace() {
120
  // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
121
  // relatively close to the stack (they are only guaranteed to be 128MiB
122
  // apart). This results in crashes if we happen to heap-allocate more than
123
  // 128MiB before we reach our stack high-water mark.
124
  //
125
  // To avoid these crashes, ensure that we have sufficient virtual memory
126
  // pages allocated before we start running.
127
  size_t Curr = getCurrentStackAllocation();
128
  const int kTargetStack = DesiredStackSize - 256 * 1024;
129
  if (Curr < kTargetStack) {
130
    volatile char *volatile Alloc =
131
        static_cast<volatile char *>(alloca(kTargetStack - Curr));
132
    Alloc[0] = 0;
133
    Alloc[kTargetStack - Curr - 1] = 0;
134
  }
135
}
136
#else
137
37.1k
static void ensureStackAddressSpace() {}
138
#endif
139
140
/// Attempt to ensure that we have at least 8MiB of usable stack space.
141
37.1k
static void ensureSufficientStack() {
142
37.1k
  struct rlimit rlim;
143
37.1k
  if (getrlimit(RLIMIT_STACK, &rlim) != 0)
144
0
    return;
145
37.1k
146
37.1k
  // Increase the soft stack limit to our desired level, if necessary and
147
37.1k
  // possible.
148
37.1k
  if (rlim.rlim_cur != RLIM_INFINITY &&
149
37.1k
      rlim.rlim_cur < rlim_t(DesiredStackSize)) {
150
0
    // Try to allocate sufficient stack.
151
0
    if (rlim.rlim_max == RLIM_INFINITY ||
152
0
        rlim.rlim_max >= rlim_t(DesiredStackSize))
153
0
      rlim.rlim_cur = DesiredStackSize;
154
0
    else if (rlim.rlim_cur == rlim.rlim_max)
155
0
      return;
156
0
    else
157
0
      rlim.rlim_cur = rlim.rlim_max;
158
0
159
0
    if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
160
0
        rlim.rlim_cur != DesiredStackSize)
161
0
      return;
162
37.1k
  }
163
37.1k
164
37.1k
  // We should now have a stack of size at least DesiredStackSize. Ensure
165
37.1k
  // that we can actually use that much, if necessary.
166
37.1k
  ensureStackAddressSpace();
167
37.1k
}
168
#else
169
static void ensureSufficientStack() {}
170
#endif
171
172
/// Print supported cpus of the given target.
173
4
static int PrintSupportedCPUs(std::string TargetStr) {
174
4
  std::string Error;
175
4
  const llvm::Target *TheTarget =
176
4
      llvm::TargetRegistry::lookupTarget(TargetStr, Error);
177
4
  if (!TheTarget) {
178
0
    llvm::errs() << Error;
179
0
    return 1;
180
0
  }
181
4
182
4
  // the target machine will handle the mcpu printing
183
4
  llvm::TargetOptions Options;
184
4
  std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
185
4
      TheTarget->createTargetMachine(TargetStr, "", "+cpuHelp", Options, None));
186
4
  return 0;
187
4
}
188
189
37.1k
int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
190
37.1k
  ensureSufficientStack();
191
37.1k
192
37.1k
  std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
193
37.1k
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
194
37.1k
195
37.1k
  // Register the support for object-file-wrapped Clang modules.
196
37.1k
  auto PCHOps = Clang->getPCHContainerOperations();
197
37.1k
  PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>());
198
37.1k
  PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
199
37.1k
200
37.1k
  // Initialize targets first, so that --version shows registered targets.
201
37.1k
  llvm::InitializeAllTargets();
202
37.1k
  llvm::InitializeAllTargetMCs();
203
37.1k
  llvm::InitializeAllAsmPrinters();
204
37.1k
  llvm::InitializeAllAsmParsers();
205
37.1k
206
37.1k
#ifdef LINK_POLLY_INTO_TOOLS
207
37.1k
  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
208
37.1k
  polly::initializePollyPasses(Registry);
209
37.1k
#endif
210
37.1k
211
37.1k
  // Buffer diagnostics from argument parsing so that we can output them using a
212
37.1k
  // well formed diagnostic object.
213
37.1k
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
214
37.1k
  TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
215
37.1k
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
216
37.1k
  bool Success = CompilerInvocation::CreateFromArgs(
217
37.1k
      Clang->getInvocation(), Argv.begin(), Argv.end(), Diags);
218
37.1k
219
37.1k
  if (Clang->getFrontendOpts().TimeTrace)
220
1
    llvm::timeTraceProfilerInitialize();
221
37.1k
222
37.1k
  // --print-supported-cpus takes priority over the actual compilation.
223
37.1k
  if (Clang->getFrontendOpts().PrintSupportedCPUs)
224
4
    return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
225
37.1k
226
37.1k
  // Infer the builtin include path if unspecified.
227
37.1k
  if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
228
37.1k
      
Clang->getHeaderSearchOpts().ResourceDir.empty()37.1k
)
229
22.7k
    Clang->getHeaderSearchOpts().ResourceDir =
230
22.7k
      CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
231
37.1k
232
37.1k
  // Create the actual diagnostics engine.
233
37.1k
  Clang->createDiagnostics();
234
37.1k
  if (!Clang->hasDiagnostics())
235
0
    return 1;
236
37.1k
237
37.1k
  // Set an error handler, so that any LLVM backend diagnostics go through our
238
37.1k
  // error handler.
239
37.1k
  llvm::install_fatal_error_handler(LLVMErrorHandler,
240
37.1k
                                  static_cast<void*>(&Clang->getDiagnostics()));
241
37.1k
242
37.1k
  DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
243
37.1k
  if (!Success)
244
12
    return 1;
245
37.1k
246
37.1k
  // Execute the frontend actions.
247
37.1k
  {
248
37.1k
    llvm::TimeTraceScope TimeScope("ExecuteCompiler", StringRef(""));
249
37.1k
    Success = ExecuteCompilerInvocation(Clang.get());
250
37.1k
  }
251
37.1k
252
37.1k
  // If any timers were active but haven't been destroyed yet, print their
253
37.1k
  // results now.  This happens in -disable-free mode.
254
37.1k
  llvm::TimerGroup::printAll(llvm::errs());
255
37.1k
256
37.1k
  if (llvm::timeTraceProfilerEnabled()) {
257
1
    SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
258
1
    llvm::sys::path::replace_extension(Path, "json");
259
1
    auto profilerOutput =
260
1
        Clang->createOutputFile(Path.str(),
261
1
                                /*Binary=*/false,
262
1
                                /*RemoveFileOnSignal=*/false, "",
263
1
                                /*Extension=*/"json",
264
1
                                /*useTemporary=*/false);
265
1
266
1
    llvm::timeTraceProfilerWrite(*profilerOutput);
267
1
    // FIXME(ibiryukov): make profilerOutput flush in destructor instead.
268
1
    profilerOutput->flush();
269
1
    llvm::timeTraceProfilerCleanup();
270
1
271
1
    llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
272
1
    llvm::errs()
273
1
        << "Use chrome://tracing or Speedscope App "
274
1
           "(https://www.speedscope.app) for flamegraph visualization\n";
275
1
  }
276
37.1k
277
37.1k
  // Our error handler depends on the Diagnostics object, which we're
278
37.1k
  // potentially about to delete. Uninstall the handler now so that any
279
37.1k
  // later errors use the default handling behavior instead.
280
37.1k
  llvm::remove_fatal_error_handler();
281
37.1k
282
37.1k
  // When running with -disable-free, don't do any destruction or shutdown.
283
37.1k
  if (Clang->getFrontendOpts().DisableFree) {
284
14.4k
    llvm::BuryPointer(std::move(Clang));
285
14.4k
    return !Success;
286
14.4k
  }
287
22.7k
288
22.7k
  return !Success;
289
22.7k
}