CodeGenAction.cpp 15 KB

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