1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===// 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 #include "clang/CodeGen/CodeGenAction.h" 11 #include "clang/Basic/FileManager.h" 12 #include "clang/Basic/SourceManager.h" 13 #include "clang/Basic/TargetInfo.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclGroup.h" 17 #include "clang/CodeGen/BackendUtil.h" 18 #include "clang/CodeGen/ModuleBuilder.h" 19 #include "clang/Frontend/CompilerInstance.h" 20 #include "clang/Frontend/FrontendDiagnostic.h" 21 #include "llvm/LLVMContext.h" 22 #include "llvm/Linker.h" 23 #include "llvm/Module.h" 24 #include "llvm/Pass.h" 25 #include "llvm/ADT/OwningPtr.h" 26 #include "llvm/Bitcode/ReaderWriter.h" 27 #include "llvm/Support/IRReader.h" 28 #include "llvm/Support/MemoryBuffer.h" 29 #include "llvm/Support/SourceMgr.h" 30 #include "llvm/Support/Timer.h" 31 using namespace clang; 32 using namespace llvm; 33 34 namespace clang { 35 class BackendConsumer : public ASTConsumer { 36 virtual void anchor(); 37 DiagnosticsEngine &Diags; 38 BackendAction Action; 39 const CodeGenOptions &CodeGenOpts; 40 const TargetOptions &TargetOpts; 41 const LangOptions &LangOpts; 42 raw_ostream *AsmOutStream; 43 ASTContext *Context; 44 45 Timer LLVMIRGeneration; 46 47 OwningPtr<CodeGenerator> Gen; 48 49 OwningPtr<llvm::Module> TheModule, LinkModule; 50 51 public: 52 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags, 53 const CodeGenOptions &compopts, 54 const TargetOptions &targetopts, 55 const LangOptions &langopts, 56 bool TimePasses, 57 const std::string &infile, 58 llvm::Module *LinkModule, 59 raw_ostream *OS, 60 LLVMContext &C) : 61 Diags(_Diags), 62 Action(action), 63 CodeGenOpts(compopts), 64 TargetOpts(targetopts), 65 LangOpts(langopts), 66 AsmOutStream(OS), 67 LLVMIRGeneration("LLVM IR Generation Time"), 68 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)), 69 LinkModule(LinkModule) { 70 llvm::TimePassesIsEnabled = TimePasses; 71 } 72 73 llvm::Module *takeModule() { return TheModule.take(); } 74 llvm::Module *takeLinkModule() { return LinkModule.take(); } 75 76 virtual void Initialize(ASTContext &Ctx) { 77 Context = &Ctx; 78 79 if (llvm::TimePassesIsEnabled) 80 LLVMIRGeneration.startTimer(); 81 82 Gen->Initialize(Ctx); 83 84 TheModule.reset(Gen->GetModule()); 85 86 if (llvm::TimePassesIsEnabled) 87 LLVMIRGeneration.stopTimer(); 88 } 89 90 virtual bool HandleTopLevelDecl(DeclGroupRef D) { 91 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), 92 Context->getSourceManager(), 93 "LLVM IR generation of declaration"); 94 95 if (llvm::TimePassesIsEnabled) 96 LLVMIRGeneration.startTimer(); 97 98 Gen->HandleTopLevelDecl(D); 99 100 if (llvm::TimePassesIsEnabled) 101 LLVMIRGeneration.stopTimer(); 102 103 return true; 104 } 105 106 virtual void HandleTranslationUnit(ASTContext &C) { 107 { 108 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); 109 if (llvm::TimePassesIsEnabled) 110 LLVMIRGeneration.startTimer(); 111 112 Gen->HandleTranslationUnit(C); 113 114 if (llvm::TimePassesIsEnabled) 115 LLVMIRGeneration.stopTimer(); 116 } 117 118 // Silently ignore if we weren't initialized for some reason. 119 if (!TheModule) 120 return; 121 122 // Make sure IR generation is happy with the module. This is released by 123 // the module provider. 124 llvm::Module *M = Gen->ReleaseModule(); 125 if (!M) { 126 // The module has been released by IR gen on failures, do not double 127 // free. 128 TheModule.take(); 129 return; 130 } 131 132 assert(TheModule.get() == M && 133 "Unexpected module change during IR generation"); 134 135 // Link LinkModule into this module if present, preserving its validity. 136 if (LinkModule) { 137 std::string ErrorMsg; 138 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource, 139 &ErrorMsg)) { 140 Diags.Report(diag::err_fe_cannot_link_module) 141 << LinkModule->getModuleIdentifier() << ErrorMsg; 142 return; 143 } 144 } 145 146 // Install an inline asm handler so that diagnostics get printed through 147 // our diagnostics hooks. 148 LLVMContext &Ctx = TheModule->getContext(); 149 LLVMContext::InlineAsmDiagHandlerTy OldHandler = 150 Ctx.getInlineAsmDiagnosticHandler(); 151 void *OldContext = Ctx.getInlineAsmDiagnosticContext(); 152 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this); 153 154 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, 155 TheModule.get(), Action, AsmOutStream); 156 157 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext); 158 } 159 160 virtual void HandleTagDeclDefinition(TagDecl *D) { 161 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 162 Context->getSourceManager(), 163 "LLVM IR generation of declaration"); 164 Gen->HandleTagDeclDefinition(D); 165 } 166 167 virtual void CompleteTentativeDefinition(VarDecl *D) { 168 Gen->CompleteTentativeDefinition(D); 169 } 170 171 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) { 172 Gen->HandleVTable(RD, DefinitionRequired); 173 } 174 175 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context, 176 unsigned LocCookie) { 177 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie); 178 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc); 179 } 180 181 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, 182 SourceLocation LocCookie); 183 }; 184 185 void BackendConsumer::anchor() {} 186 } 187 188 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr 189 /// buffer to be a valid FullSourceLoc. 190 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, 191 SourceManager &CSM) { 192 // Get both the clang and llvm source managers. The location is relative to 193 // a memory buffer that the LLVM Source Manager is handling, we need to add 194 // a copy to the Clang source manager. 195 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 196 197 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr 198 // already owns its one and clang::SourceManager wants to own its one. 199 const MemoryBuffer *LBuf = 200 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 201 202 // Create the copy and transfer ownership to clang::SourceManager. 203 llvm::MemoryBuffer *CBuf = 204 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), 205 LBuf->getBufferIdentifier()); 206 FileID FID = CSM.createFileIDForMemBuffer(CBuf); 207 208 // Translate the offset into the file. 209 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 210 SourceLocation NewLoc = 211 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); 212 return FullSourceLoc(NewLoc, CSM); 213 } 214 215 216 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an 217 /// error parsing inline asm. The SMDiagnostic indicates the error relative to 218 /// the temporary memory buffer that the inline asm parser has set up. 219 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D, 220 SourceLocation LocCookie) { 221 // There are a couple of different kinds of errors we could get here. First, 222 // we re-format the SMDiagnostic in terms of a clang diagnostic. 223 224 // Strip "error: " off the start of the message string. 225 StringRef Message = D.getMessage(); 226 if (Message.startswith("error: ")) 227 Message = Message.substr(7); 228 229 // If the SMDiagnostic has an inline asm source location, translate it. 230 FullSourceLoc Loc; 231 if (D.getLoc() != SMLoc()) 232 Loc = ConvertBackendLocation(D, Context->getSourceManager()); 233 234 235 // If this problem has clang-level source location information, report the 236 // issue as being an error in the source with a note showing the instantiated 237 // code. 238 if (LocCookie.isValid()) { 239 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message); 240 241 if (D.getLoc().isValid()) { 242 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here); 243 // Convert the SMDiagnostic ranges into SourceRange and attach them 244 // to the diagnostic. 245 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) { 246 std::pair<unsigned, unsigned> Range = D.getRanges()[i]; 247 unsigned Column = D.getColumnNo(); 248 B << SourceRange(Loc.getLocWithOffset(Range.first - Column), 249 Loc.getLocWithOffset(Range.second - Column)); 250 } 251 } 252 return; 253 } 254 255 // Otherwise, report the backend error as occurring in the generated .s file. 256 // If Loc is invalid, we still need to report the error, it just gets no 257 // location info. 258 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message); 259 } 260 261 // 262 263 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 264 : Act(_Act), LinkModule(0), 265 VMContext(_VMContext ? _VMContext : new LLVMContext), 266 OwnsVMContext(!_VMContext) {} 267 268 CodeGenAction::~CodeGenAction() { 269 TheModule.reset(); 270 if (OwnsVMContext) 271 delete VMContext; 272 } 273 274 bool CodeGenAction::hasIRSupport() const { return true; } 275 276 void CodeGenAction::EndSourceFileAction() { 277 // If the consumer creation failed, do nothing. 278 if (!getCompilerInstance().hasASTConsumer()) 279 return; 280 281 // If we were given a link module, release consumer's ownership of it. 282 if (LinkModule) 283 BEConsumer->takeLinkModule(); 284 285 // Steal the module from the consumer. 286 TheModule.reset(BEConsumer->takeModule()); 287 } 288 289 llvm::Module *CodeGenAction::takeModule() { 290 return TheModule.take(); 291 } 292 293 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 294 OwnsVMContext = false; 295 return VMContext; 296 } 297 298 static raw_ostream *GetOutputStream(CompilerInstance &CI, 299 StringRef InFile, 300 BackendAction Action) { 301 switch (Action) { 302 case Backend_EmitAssembly: 303 return CI.createDefaultOutputFile(false, InFile, "s"); 304 case Backend_EmitLL: 305 return CI.createDefaultOutputFile(false, InFile, "ll"); 306 case Backend_EmitBC: 307 return CI.createDefaultOutputFile(true, InFile, "bc"); 308 case Backend_EmitNothing: 309 return 0; 310 case Backend_EmitMCNull: 311 case Backend_EmitObj: 312 return CI.createDefaultOutputFile(true, InFile, "o"); 313 } 314 315 llvm_unreachable("Invalid action!"); 316 } 317 318 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI, 319 StringRef InFile) { 320 BackendAction BA = static_cast<BackendAction>(Act); 321 OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA)); 322 if (BA != Backend_EmitNothing && !OS) 323 return 0; 324 325 llvm::Module *LinkModuleToUse = LinkModule; 326 327 // If we were not given a link module, and the user requested that one be 328 // loaded from bitcode, do so now. 329 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile; 330 if (!LinkModuleToUse && !LinkBCFile.empty()) { 331 std::string ErrorStr; 332 333 llvm::MemoryBuffer *BCBuf = 334 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr); 335 if (!BCBuf) { 336 CI.getDiagnostics().Report(diag::err_cannot_open_file) 337 << LinkBCFile << ErrorStr; 338 return 0; 339 } 340 341 LinkModuleToUse = getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr); 342 if (!LinkModuleToUse) { 343 CI.getDiagnostics().Report(diag::err_cannot_open_file) 344 << LinkBCFile << ErrorStr; 345 return 0; 346 } 347 } 348 349 BEConsumer = 350 new BackendConsumer(BA, CI.getDiagnostics(), 351 CI.getCodeGenOpts(), CI.getTargetOpts(), 352 CI.getLangOpts(), 353 CI.getFrontendOpts().ShowTimers, InFile, 354 LinkModuleToUse, OS.take(), *VMContext); 355 return BEConsumer; 356 } 357 358 void CodeGenAction::ExecuteAction() { 359 // If this is an IR file, we have to treat it specially. 360 if (getCurrentFileKind() == IK_LLVM_IR) { 361 BackendAction BA = static_cast<BackendAction>(Act); 362 CompilerInstance &CI = getCompilerInstance(); 363 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA); 364 if (BA != Backend_EmitNothing && !OS) 365 return; 366 367 bool Invalid; 368 SourceManager &SM = CI.getSourceManager(); 369 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(), 370 &Invalid); 371 if (Invalid) 372 return; 373 374 // FIXME: This is stupid, IRReader shouldn't take ownership. 375 llvm::MemoryBuffer *MainFileCopy = 376 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(), 377 getCurrentFile().c_str()); 378 379 llvm::SMDiagnostic Err; 380 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext)); 381 if (!TheModule) { 382 // Translate from the diagnostic info to the SourceManager location. 383 SourceLocation Loc = SM.translateFileLineCol( 384 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(), 385 Err.getColumnNo() + 1); 386 387 // Get a custom diagnostic for the error. We strip off a leading 388 // diagnostic code if there is one. 389 StringRef Msg = Err.getMessage(); 390 if (Msg.startswith("error: ")) 391 Msg = Msg.substr(7); 392 unsigned DiagID = CI.getDiagnostics().getCustomDiagID( 393 DiagnosticsEngine::Error, Msg); 394 395 CI.getDiagnostics().Report(Loc, DiagID); 396 return; 397 } 398 399 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), 400 CI.getTargetOpts(), CI.getLangOpts(), 401 TheModule.get(), 402 BA, OS); 403 return; 404 } 405 406 // Otherwise follow the normal AST path. 407 this->ASTFrontendAction::ExecuteAction(); 408 } 409 410 // 411 412 void EmitAssemblyAction::anchor() { } 413 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 414 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 415 416 void EmitBCAction::anchor() { } 417 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 418 : CodeGenAction(Backend_EmitBC, _VMContext) {} 419 420 void EmitLLVMAction::anchor() { } 421 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 422 : CodeGenAction(Backend_EmitLL, _VMContext) {} 423 424 void EmitLLVMOnlyAction::anchor() { } 425 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 426 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 427 428 void EmitCodeGenOnlyAction::anchor() { } 429 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 430 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 431 432 void EmitObjAction::anchor() { } 433 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 434 : CodeGenAction(Backend_EmitObj, _VMContext) {} 435