CodeGenAction.cpp 16 KB

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