File: CJitFuncClang.cpp

package info (click to toggle)
freemat 4.2%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 142,116 kB
  • sloc: ansic: 126,788; cpp: 62,015; python: 2,080; perl: 1,255; sh: 1,146; yacc: 1,019; lex: 239; makefile: 107
file content (231 lines) | stat: -rw-r--r-- 6,918 bytes parent folder | download | duplicates (2)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#ifdef HAVE_LLVM
#include "CJitFuncClang.hpp"
#include "CArray.hpp"
#include <iostream>
#include <fstream>
#include <memory>

#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/CompilerInstance.h"

//#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"

#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ErrorHandling.h"

#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetOptions.h"

#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
//#include "llvm/ExecutionEngine/JIT.h"
//#include "llvm/ExecutionEngine/Interpreter.h"




#include <QTemporaryFile>
#include <QDir>

using namespace clang;
using namespace clang::driver;


CJitFuncClang::CJitFuncClang(Interpreter* eval)
{
  m_eval = eval;
  ctxt = new llvm::LLVMContext;
}

CJitFuncClang::~CJitFuncClang()
{
  delete EE;
  delete comp;
}
QString GetRootPath();

bool CJitFuncClang::compile(const std::string &filename, 
			    const std::string &funcname) 
{
  llvm::InitializeNativeTarget();

  llvm::IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  TextDiagnosticPrinter *DiagClient =
    new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);

  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
  Driver TheDriver("", llvm::sys::getDefaultTargetTriple(),
                   Diags);
  TheDriver.setTitle("FreeMat JIT");
  llvm::SmallVector<const char *, 16> Args;
  Args.push_back("FreeMat");
  Args.push_back(filename.c_str());
  Args.push_back("-fsyntax-only");
  Args.push_back("-O3");
  Args.push_back("-v");
  Args.push_back("-fno-exceptions");
  std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
  if (!C) return false;
  const driver::JobList &Jobs = C->getJobs();
  if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
    llvm::SmallString<256> Msg;
    llvm::raw_svector_ostream OS(Msg);
    Jobs.Print(OS, "; ", true);
    Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
    return false;
  }
  const driver::Command Cmd = cast<driver::Command>(*Jobs.begin());
  if (llvm::StringRef(Cmd.getCreator().getName()) != "clang") {
    Diags.Report(diag::err_fe_expected_clang_command);
    return false;
  }
  // Initialize a compiler invocation object from the clang (-cc1) arguments.
  const driver::ArgStringList &CCArgs = Cmd.getArguments();
  std::unique_ptr<CompilerInvocation> CI(new CompilerInvocation);
  CompilerInvocation::CreateFromArgs(*CI,
                                     const_cast<const char **>(CCArgs.data()),
                                     const_cast<const char **>(CCArgs.data()) +
                                       CCArgs.size(),
                                     Diags);
  QString path = GetRootPath() + "/toolbox/jit";
  //CI->getHeaderSearchOpts().AddPath(path.toStdString().c_str(),frontend::Quoted,true,false,false);

  // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
  // Create a compiler instance to handle the actual work.
  comp = new clang::CompilerInstance;
  comp->setInvocation(CI.get());
  // Create the compilers actual diagnostics engine.
  DiagnosticConsumer ClientDia;
  comp->createDiagnostics(&ClientDia);
  if (!comp->hasDiagnostics()) return false;
  // Create and execute the frontend to generate an LLVM bitcode module.
  // Pass the LLVM context to the code gen action.  Otherwise, the action
  // creates a new context and then promptly deletes it when it goes out
  // of scope. :P
  std::unique_ptr<CodeGenAction> Act(new EmitLLVMOnlyAction(ctxt));
  if (!comp->ExecuteAction(*Act)) return false;
  std::cout << "Compilation complete...";
  
  std::unique_ptr<llvm::Module> Module (Act->takeModule().get());
  if (Module)
    {
      llvm::outs() << *Module;
      std::string Error;
      EE = llvm::EngineBuilder(move(Module)).create();
      if (!EE) return false;
      func =  Module->getFunction(funcname);
      return true;
    }
  return false;
}

bool CJitFuncClang::compile(const Tree & t, JITControlFlag flag)
{
  m_flag = flag;
  CJitFunc mcomp;
  mcomp.set_interpreter(m_eval);
  mcomp.compile_tree(t,std::string("testfunc"));
  if (m_flag == JITOn)
    {
      QTemporaryFile file(QDir::tempPath()+"/jitXXXXXX.cpp");
      file.open();
      std::string codename = file.fileName().toStdString();
      mcomp.writeCode(codename);
      return compile(codename,"testfunc");
    }
  if (m_flag == JITTrace)
    {
      QString name = QDir::tempPath()+"/jittrace.cpp";
      std::string codename = name.toStdString();
      mcomp.writeCode(codename);
      return compile(codename,"testfunc");
    }
}

int CJitFuncClang::run()
{
    std::vector<llvm::GenericValue> args(1);
    args[0].PointerVal = m_eval;
    int retval;
    llvm::GenericValue ret = EE->runFunction(func,args);
    retval = ret.IntVal.getSExtValue();

    if (retval == CJIT_Runfail)
        throw Exception(m_eval->getLastErrorString());

    return retval;
}

void force_linkage()
{
  carray_empty();
  carray_scalar(0,0);
  carray_create(0,0,0,0,0);
  carray_download_scalar(0,0,0,0);
  carray_download_array(0,0,0,0);
  carray_download_function(0,0,0);
  carray_upload_scalar(0,0,0,0);
  carray_upload_array(0,0,0);
  carray_copy(0);
  carray_free(0);
  carray_rows(0);
  carray_cols(0);
  carray_set_ss(0,0,0,0,0);
  carray_set_s(0,0,0,0);
  carray_set_aa(0,0,0,0,0);
  carray_set_a(0,0,0,0);
  carray_get_ss(0,0,0,0,0);
  carray_get_s(0,0,0,0);
  carray_get_aa(0,0,0,0,0);
  carray_get_a(0,0,0,0);
  carray_duplicate(0,0,0);
  carray_add(0,0,0,0);
  carray_hcat(0,0,0,0);
  carray_vcat(0,0,0,0);
  carray_sub(0,0,0,0);
  carray_times(0,0,0,0);
  carray_pow(0,0,0,0);
  carray_dpow(0,0,0,0);
  carray_dtimes(0,0,0,0);
  carray_rdiv(0,0,0,0);
  carray_drdiv(0,0,0,0);
  carray_ldiv(0,0,0,0);
  carray_dldiv(0,0,0,0);
  carray_colon(0,0,0,0);
  carray_dcolon(0,0,0,0,0);
  carray_or(0,0,0,0);
  carray_and(0,0,0,0);
  carray_lt(0,0,0,0);
  carray_le(0,0,0,0);
  carray_gt(0,0,0,0);
  carray_ge(0,0,0,0);
  carray_eq(0,0,0,0);
  carray_neq(0,0,0,0);
  carray_pos(0,0,0);
  carray_neg(0,0,0);
  carray_not(0,0,0);
  carray_transpose(0,0,0);
  carray_dottranspose(0,0,0);
  carray_any(0,0,0);
  carray_all(0,0,0);
  carray_invoke_1(0,0,0,0);
  carray_invoke_2(0,0,0,0,0);
}
#endif