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/Config/llvm-config.h" 30 #include "llvm/LinkAllPasses.h" 31 #include "llvm/Option/ArgList.h" 32 #include "llvm/Option/OptTable.h" 33 #include "llvm/Support/Compiler.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/ManagedStatic.h" 36 #include "llvm/Support/Signals.h" 37 #include "llvm/Support/TargetSelect.h" 38 #include "llvm/Support/Timer.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <cstdio> 41 42 #ifdef CLANG_HAVE_RLIMITS 43 #include <sys/resource.h> 44 #endif 45 46 using namespace clang; 47 using namespace llvm::opt; 48 49 //===----------------------------------------------------------------------===// 50 // Main driver 51 //===----------------------------------------------------------------------===// 52 53 static void LLVMErrorHandler(void *UserData, const std::string &Message, 54 bool GenCrashDiag) { 55 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); 56 57 Diags.Report(diag::err_fe_error_backend) << Message; 58 59 // Run the interrupt handlers to make sure any special cleanups get done, in 60 // particular that we remove files registered with RemoveFileOnSignal. 61 llvm::sys::RunInterruptHandlers(); 62 63 // We cannot recover from llvm errors. When reporting a fatal error, exit 64 // with status 70 to generate crash diagnostics. For BSD systems this is 65 // defined as an internal software error. Otherwise, exit with status 1. 66 exit(GenCrashDiag ? 70 : 1); 67 } 68 69 #ifdef LINK_POLLY_INTO_TOOLS 70 namespace polly { 71 void initializePollyPasses(llvm::PassRegistry &Registry); 72 } 73 #endif 74 75 #ifdef CLANG_HAVE_RLIMITS 76 // The amount of stack we think is "sufficient". If less than this much is 77 // available, we may be unable to reach our template instantiation depth 78 // limit and other similar limits. 79 // FIXME: Unify this with the stack we request when spawning a thread to build 80 // a module. 81 static const int kSufficientStack = 8 << 20; 82 83 #if defined(__linux__) && defined(__PIE__) 84 static size_t getCurrentStackAllocation() { 85 // If we can't compute the current stack usage, allow for 512K of command 86 // line arguments and environment. 87 size_t Usage = 512 * 1024; 88 if (FILE *StatFile = fopen("/proc/self/stat", "r")) { 89 // We assume that the stack extends from its current address to the end of 90 // the environment space. In reality, there is another string literal (the 91 // program name) after the environment, but this is close enough (we only 92 // need to be within 100K or so). 93 unsigned long StackPtr, EnvEnd; 94 // Disable silly GCC -Wformat warning that complains about length 95 // modifiers on ignored format specifiers. We want to retain these 96 // for documentation purposes even though they have no effect. 97 #if defined(__GNUC__) && !defined(__clang__) 98 #pragma GCC diagnostic push 99 #pragma GCC diagnostic ignored "-Wformat" 100 #endif 101 if (fscanf(StatFile, 102 "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu " 103 "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu " 104 "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d " 105 "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d", 106 &StackPtr, &EnvEnd) == 2) { 107 #if defined(__GNUC__) && !defined(__clang__) 108 #pragma GCC diagnostic pop 109 #endif 110 Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd; 111 } 112 fclose(StatFile); 113 } 114 return Usage; 115 } 116 117 #include <alloca.h> 118 119 LLVM_ATTRIBUTE_NOINLINE 120 static void ensureStackAddressSpace(int ExtraChunks = 0) { 121 // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary 122 // relatively close to the stack (they are only guaranteed to be 128MiB 123 // apart). This results in crashes if we happen to heap-allocate more than 124 // 128MiB before we reach our stack high-water mark. 125 // 126 // To avoid these crashes, ensure that we have sufficient virtual memory 127 // pages allocated before we start running. 128 size_t Curr = getCurrentStackAllocation(); 129 const int kTargetStack = kSufficientStack - 256 * 1024; 130 if (Curr < kTargetStack) { 131 volatile char *volatile Alloc = 132 static_cast<volatile char *>(alloca(kTargetStack - Curr)); 133 Alloc[0] = 0; 134 Alloc[kTargetStack - Curr - 1] = 0; 135 } 136 } 137 #else 138 static void ensureStackAddressSpace() {} 139 #endif 140 141 /// Attempt to ensure that we have at least 8MiB of usable stack space. 142 static void ensureSufficientStack() { 143 struct rlimit rlim; 144 if (getrlimit(RLIMIT_STACK, &rlim) != 0) 145 return; 146 147 // Increase the soft stack limit to our desired level, if necessary and 148 // possible. 149 if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < kSufficientStack) { 150 // Try to allocate sufficient stack. 151 if (rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max >= kSufficientStack) 152 rlim.rlim_cur = kSufficientStack; 153 else if (rlim.rlim_cur == rlim.rlim_max) 154 return; 155 else 156 rlim.rlim_cur = rlim.rlim_max; 157 158 if (setrlimit(RLIMIT_STACK, &rlim) != 0 || 159 rlim.rlim_cur != kSufficientStack) 160 return; 161 } 162 163 // We should now have a stack of size at least kSufficientStack. Ensure 164 // that we can actually use that much, if necessary. 165 ensureStackAddressSpace(); 166 } 167 #else 168 static void ensureSufficientStack() {} 169 #endif 170 171 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { 172 ensureSufficientStack(); 173 174 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); 175 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 176 177 // Register the support for object-file-wrapped Clang modules. 178 auto PCHOps = Clang->getPCHContainerOperations(); 179 PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>()); 180 PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>()); 181 182 // Initialize targets first, so that --version shows registered targets. 183 llvm::InitializeAllTargets(); 184 llvm::InitializeAllTargetMCs(); 185 llvm::InitializeAllAsmPrinters(); 186 llvm::InitializeAllAsmParsers(); 187 188 #ifdef LINK_POLLY_INTO_TOOLS 189 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); 190 polly::initializePollyPasses(Registry); 191 #endif 192 193 // Buffer diagnostics from argument parsing so that we can output them using a 194 // well formed diagnostic object. 195 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 196 TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; 197 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); 198 bool Success = CompilerInvocation::CreateFromArgs( 199 Clang->getInvocation(), Argv.begin(), Argv.end(), Diags); 200 201 // Infer the builtin include path if unspecified. 202 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && 203 Clang->getHeaderSearchOpts().ResourceDir.empty()) 204 Clang->getHeaderSearchOpts().ResourceDir = 205 CompilerInvocation::GetResourcesPath(Argv0, MainAddr); 206 207 // Create the actual diagnostics engine. 208 Clang->createDiagnostics(); 209 if (!Clang->hasDiagnostics()) 210 return 1; 211 212 // Set an error handler, so that any LLVM backend diagnostics go through our 213 // error handler. 214 llvm::install_fatal_error_handler(LLVMErrorHandler, 215 static_cast<void*>(&Clang->getDiagnostics())); 216 217 DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics()); 218 if (!Success) 219 return 1; 220 221 // Execute the frontend actions. 222 Success = ExecuteCompilerInvocation(Clang.get()); 223 224 // If any timers were active but haven't been destroyed yet, print their 225 // results now. This happens in -disable-free mode. 226 llvm::TimerGroup::printAll(llvm::errs()); 227 228 // Our error handler depends on the Diagnostics object, which we're 229 // potentially about to delete. Uninstall the handler now so that any 230 // later errors use the default handling behavior instead. 231 llvm::remove_fatal_error_handler(); 232 233 // When running with -disable-free, don't do any destruction or shutdown. 234 if (Clang->getFrontendOpts().DisableFree) { 235 BuryPointer(std::move(Clang)); 236 return !Success; 237 } 238 239 return !Success; 240 } 241