blob: b969ff81cad659ba7c2d7971e11206f7d0d6d981 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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.
32 ASTContext Context(PP.getTargetInfo(), PP.getIdentifierTable());
33 ASTStreamerTy *Streamer = ASTStreamer_Init(PP, Context, MainFileID);
34
35 // Create the module to codegen into.
36 llvm::Module M("foo");
37
38 CodeGen::BuilderTy *Builder = CodeGen::Init(Context, M);
39
40 while (Decl *D = ASTStreamer_ReadTopLevelDecl(Streamer)) {
41 // If an error occurred, stop code generation, but continue parsing and
42 // semantic analysis (to ensure all warnings and errors are emitted).
43 if (Diags.hasErrorOccurred())
44 continue;
45
46 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
47 CodeGen::CodeGenFunction(Builder, FD);
Chris Lattner88a69ad2007-07-13 05:13:43 +000048 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
49 CodeGen::CodeGenGlobalVar(Builder, FVD);
Reid Spencer5f016e22007-07-11 17:01:13 +000050 } else {
Chris Lattner88a69ad2007-07-13 05:13:43 +000051 assert(isa<TypedefDecl>(D) && "Only expected typedefs here");
52 // don't codegen for now, eventually pass down for debug info.
53 //std::cerr << "Read top-level typedef decl: '" << D->getName() << "'\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000054 }
55 }
56
57 if (PrintStats) {
58 std::cerr << "\nSTATISTICS:\n";
59 CodeGen::PrintStats(Builder);
60 ASTStreamer_PrintStats(Streamer);
61 Context.PrintStats();
62 }
63
64 CodeGen::Terminate(Builder);
65 ASTStreamer_Terminate(Streamer);
66
67 // Print the generated code.
68 M.print(std::cout);
69}
70