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