CodeGenAction.cpp 15 KB

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