-
Notifications
You must be signed in to change notification settings - Fork 59
/
ObjGen.cpp
72 lines (55 loc) · 1.98 KB
/
ObjGen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// Created by cs on 2017/5/30.
//
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/ADT/Optional.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/IR/LegacyPassManager.h>
#include "CodeGen.h"
#include "ObjGen.h"
using namespace llvm;
void ObjGen(CodeGenContext & context, const string& filename){
// Initialize the target registry etc.
InitializeAllTargetInfos();
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmParsers();
InitializeAllAsmPrinters();
auto targetTriple = sys::getDefaultTargetTriple();
context.theModule->setTargetTriple(targetTriple);
std::string error;
auto Target = TargetRegistry::lookupTarget(targetTriple, error);
if( !Target ){
errs() << error;
return;
}
auto CPU = "generic";
auto features = "";
TargetOptions opt;
auto RM = Optional<Reloc::Model>();
auto theTargetMachine = Target->createTargetMachine(targetTriple, CPU, features, opt, RM);
context.theModule->setDataLayout(theTargetMachine->createDataLayout());
context.theModule->setTargetTriple(targetTriple);
std::error_code EC;
raw_fd_ostream dest(filename.c_str(), EC, sys::fs::F_None);
// raw_fd_ostream dest(filename.c_str(), EC, sys::fs::F_None);
// formatted_raw_ostream formattedRawOstream(dest);
legacy::PassManager pass;
auto fileType = TargetMachine::CGFT_ObjectFile;
if( theTargetMachine->addPassesToEmitFile(pass, dest, fileType) ){
errs() << "theTargetMachine can't emit a file of this type";
return;
}
pass.run(*context.theModule.get());
dest.flush();
outs() << "Object code wrote to " << filename.c_str() << "\n";
return;
}