blob: 95d23f584e2518f60d19d142c396bc2b236f7e98 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- 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
14#include "clang.h"
15#include "clang/CodeGen/ModuleBuilder.h"
16#include "clang/Sema/ASTStreamer.h"
17#include "clang/AST/AST.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/Diagnostic.h"
20#include "llvm/Module.h"
21#include <iostream>
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// LLVM Emission
26//===----------------------------------------------------------------------===//
27
28void clang::EmitLLVMFromASTs(Preprocessor &PP, unsigned MainFileID,
29 bool PrintStats) {
30 Diagnostic &Diags = PP.getDiagnostics();
31 // Create the streamer to read the file.
Chris Lattner409dfd12007-09-13 01:14:03 +000032 ASTContext Context(PP.getSourceManager(), PP.getTargetInfo(),
33 PP.getIdentifierTable());
Chris Lattner4b009652007-07-25 00:24:17 +000034 ASTStreamerTy *Streamer = ASTStreamer_Init(PP, Context, MainFileID);
35
36 // Create the module to codegen into.
37 llvm::Module M("foo");
38
39 CodeGen::BuilderTy *Builder = CodeGen::Init(Context, M);
40
41 while (Decl *D = ASTStreamer_ReadTopLevelDecl(Streamer)) {
42 // If an error occurred, stop code generation, but continue parsing and
43 // semantic analysis (to ensure all warnings and errors are emitted).
44 if (Diags.hasErrorOccurred())
45 continue;
46
47 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
48 CodeGen::CodeGenFunction(Builder, FD);
49 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
50 CodeGen::CodeGenGlobalVar(Builder, FVD);
51 } else {
52 assert(isa<TypedefDecl>(D) && "Only expected typedefs here");
53 // don't codegen for now, eventually pass down for debug info.
54 //std::cerr << "Read top-level typedef decl: '" << D->getName() << "'\n";
55 }
56 }
57
58 if (PrintStats) {
59 std::cerr << "\nSTATISTICS:\n";
60 CodeGen::PrintStats(Builder);
61 ASTStreamer_PrintStats(Streamer);
62 Context.PrintStats();
63 }
64
65 CodeGen::Terminate(Builder);
66 ASTStreamer_Terminate(Streamer);
67
68 // Print the generated code.
69 M.print(std::cout);
70}
71