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