cc1_main.cpp revision 314564
1//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This is the entry point to the clang -cc1 functionality, which implements the 11// core compiler functionality along with a number of additional tools for 12// demonstration and testing purposes. 13// 14//===----------------------------------------------------------------------===// 15 16#include "llvm/Option/Arg.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/LinkAllPasses.h" 30#include "llvm/Option/ArgList.h" 31#include "llvm/Option/OptTable.h" 32#include "llvm/Support/Compiler.h" 33#include "llvm/Support/ErrorHandling.h" 34#include "llvm/Support/ManagedStatic.h" 35#include "llvm/Support/Signals.h" 36#include "llvm/Support/TargetSelect.h" 37#include "llvm/Support/Timer.h" 38#include "llvm/Support/raw_ostream.h" 39#include <cstdio> 40 41#ifdef CLANG_HAVE_RLIMITS 42#include <sys/resource.h> 43#endif 44 45using namespace clang; 46using namespace llvm::opt; 47 48//===----------------------------------------------------------------------===// 49// Main driver 50//===----------------------------------------------------------------------===// 51 52static void LLVMErrorHandler(void *UserData, const std::string &Message, 53 bool GenCrashDiag) { 54 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); 55 56 Diags.Report(diag::err_fe_error_backend) << Message; 57 58 // Run the interrupt handlers to make sure any special cleanups get done, in 59 // particular that we remove files registered with RemoveFileOnSignal. 60 llvm::sys::RunInterruptHandlers(); 61 62 // We cannot recover from llvm errors. When reporting a fatal error, exit 63 // with status 70 to generate crash diagnostics. For BSD systems this is 64 // defined as an internal software error. Otherwise, exit with status 1. 65 exit(GenCrashDiag ? 70 : 1); 66} 67 68#ifdef LINK_POLLY_INTO_TOOLS 69namespace polly { 70void initializePollyPasses(llvm::PassRegistry &Registry); 71} 72#endif 73 74#ifdef CLANG_HAVE_RLIMITS 75// The amount of stack we think is "sufficient". If less than this much is 76// available, we may be unable to reach our template instantiation depth 77// limit and other similar limits. 78// FIXME: Unify this with the stack we request when spawning a thread to build 79// a module. 80static const int kSufficientStack = 8 << 20; 81 82#if defined(__linux__) && defined(__PIE__) 83static 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 118LLVM_ATTRIBUTE_NOINLINE 119static void ensureStackAddressSpace(int ExtraChunks = 0) { 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 = kSufficientStack - 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 137static void ensureStackAddressSpace() {} 138#endif 139 140/// Attempt to ensure that we have at least 8MiB of usable stack space. 141static void ensureSufficientStack() { 142 struct rlimit rlim; 143 if (getrlimit(RLIMIT_STACK, &rlim) != 0) 144 return; 145 146 // Increase the soft stack limit to our desired level, if necessary and 147 // possible. 148 if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < kSufficientStack) { 149 // Try to allocate sufficient stack. 150 if (rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max >= kSufficientStack) 151 rlim.rlim_cur = kSufficientStack; 152 else if (rlim.rlim_cur == rlim.rlim_max) 153 return; 154 else 155 rlim.rlim_cur = rlim.rlim_max; 156 157 if (setrlimit(RLIMIT_STACK, &rlim) != 0 || 158 rlim.rlim_cur != kSufficientStack) 159 return; 160 } 161 162 // We should now have a stack of size at least kSufficientStack. Ensure 163 // that we can actually use that much, if necessary. 164 ensureStackAddressSpace(); 165} 166#else 167static void ensureSufficientStack() {} 168#endif 169 170int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { 171 ensureSufficientStack(); 172 173 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); 174 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 175 176 // Register the support for object-file-wrapped Clang modules. 177 auto PCHOps = Clang->getPCHContainerOperations(); 178 PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>()); 179 PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>()); 180 181 // Initialize targets first, so that --version shows registered targets. 182 llvm::InitializeAllTargets(); 183 llvm::InitializeAllTargetMCs(); 184 llvm::InitializeAllAsmPrinters(); 185 llvm::InitializeAllAsmParsers(); 186 187#ifdef LINK_POLLY_INTO_TOOLS 188 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); 189 polly::initializePollyPasses(Registry); 190#endif 191 192 // Buffer diagnostics from argument parsing so that we can output them using a 193 // well formed diagnostic object. 194 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 195 TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; 196 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); 197 bool Success = CompilerInvocation::CreateFromArgs( 198 Clang->getInvocation(), Argv.begin(), Argv.end(), Diags); 199 200 // Infer the builtin include path if unspecified. 201 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && 202 Clang->getHeaderSearchOpts().ResourceDir.empty()) 203 Clang->getHeaderSearchOpts().ResourceDir = 204 CompilerInvocation::GetResourcesPath(Argv0, MainAddr); 205 206 // Create the actual diagnostics engine. 207 Clang->createDiagnostics(); 208 if (!Clang->hasDiagnostics()) 209 return 1; 210 211 // Set an error handler, so that any LLVM backend diagnostics go through our 212 // error handler. 213 llvm::install_fatal_error_handler(LLVMErrorHandler, 214 static_cast<void*>(&Clang->getDiagnostics())); 215 216 DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics()); 217 if (!Success) 218 return 1; 219 220 // Execute the frontend actions. 221 Success = ExecuteCompilerInvocation(Clang.get()); 222 223 // If any timers were active but haven't been destroyed yet, print their 224 // results now. This happens in -disable-free mode. 225 llvm::TimerGroup::printAll(llvm::errs()); 226 227 // Our error handler depends on the Diagnostics object, which we're 228 // potentially about to delete. Uninstall the handler now so that any 229 // later errors use the default handling behavior instead. 230 llvm::remove_fatal_error_handler(); 231 232 // When running with -disable-free, don't do any destruction or shutdown. 233 if (Clang->getFrontendOpts().DisableFree) { 234 BuryPointer(std::move(Clang)); 235 return !Success; 236 } 237 238 return !Success; 239} 240