CodeGenAction.cpp 15 KB

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