CodeGenAction.cpp 12 KB

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