CodeGenAction.cpp 14 KB

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