LLVMCodegen.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //===--- LLVMCodegen.cpp - Emit LLVM Code from ASTs -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This builds an AST and converts it to LLVM Code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang.h"
  14. #include "clang/CodeGen/ModuleBuilder.h"
  15. #include "clang/Sema/ASTStreamer.h"
  16. #include "clang/AST/AST.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "llvm/Module.h"
  20. #include <iostream>
  21. using namespace clang;
  22. //===----------------------------------------------------------------------===//
  23. // LLVM Emission
  24. //===----------------------------------------------------------------------===//
  25. void clang::EmitLLVMFromASTs(Preprocessor &PP, unsigned MainFileID,
  26. bool PrintStats) {
  27. Diagnostic &Diags = PP.getDiagnostics();
  28. // Create the streamer to read the file.
  29. ASTContext Context(PP.getTargetInfo(), PP.getIdentifierTable());
  30. ASTStreamerTy *Streamer = ASTStreamer_Init(PP, Context, MainFileID);
  31. // Create the module to codegen into.
  32. llvm::Module M("foo");
  33. CodeGen::BuilderTy *Builder = CodeGen::Init(Context, M);
  34. while (Decl *D = ASTStreamer_ReadTopLevelDecl(Streamer)) {
  35. // If an error occurred, stop code generation, but continue parsing and
  36. // semantic analysis (to ensure all warnings and errors are emitted).
  37. if (Diags.hasErrorOccurred())
  38. continue;
  39. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  40. CodeGen::CodeGenFunction(Builder, FD);
  41. } else if (isa<TypedefDecl>(D)) {
  42. std::cerr << "Read top-level typedef decl: '" << D->getName() << "'\n";
  43. } else {
  44. std::cerr << "Read top-level variable decl: '" << D->getName() << "'\n";
  45. }
  46. }
  47. if (PrintStats) {
  48. std::cerr << "\nSTATISTICS:\n";
  49. CodeGen::PrintStats(Builder);
  50. ASTStreamer_PrintStats(Streamer);
  51. Context.PrintStats();
  52. }
  53. CodeGen::Terminate(Builder);
  54. ASTStreamer_Terminate(Streamer);
  55. // Print the generated code.
  56. M.print(std::cout);
  57. }