-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcompilerengine.cpp
3122 lines (2691 loc) · 122 KB
/
compilerengine.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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "fix_clang_undef_eai.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include <clang/CodeGen/ModuleBuilder.h>
#include <clang/CodeGen/CodeGenAction.h>
#include <clang/CodeGen/BackendUtil.h>
#include <clang/Driver/Compilation.h>
#include <clang/Driver/Driver.h>
#include <clang/Driver/Tool.h>
#include <clang/Parse/ParseAST.h>
#include <clang/Sema/Sema.h>
#include <clang/Sema/Template.h>
#include <clang/AST/ASTLambda.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/AST/AST.h>
#include <clang/AST/ASTImporter.h>
#include <clang/AST/ExternalASTSource.h>
#include <clang/AST/Type.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Frontend/ASTUnit.h>
#include <llvm/Support/Host.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/AsmParser/Parser.h>
#include "ivm/dbghelper.h"
#include "ivm/findsymbolvisitor.h"
#include "invokestorage.h"
#include "compilerengine.h"
void test_raw_codegen()
{
clang::CompilerInstance ci;
ci.createASTContext();
ci.createDiagnostics();
clang::ASTContext &astctx = ci.getASTContext();
clang::DiagnosticsEngine &diag = ci.getDiagnostics();
llvm::LLVMContext &vmctx = llvm::getGlobalContext();
llvm::Module mod("piecegen", vmctx);
clang::CodeGenOptions &cgopt = ci.getCodeGenOpts();
llvm::DataLayout dlo("hehhe");
// clang::CodeGen::CodeGenModule cgmod(astctx, cgopt, mod, dlo, diag);
// cgmod.EmitAnnotationString("hhhh");
// clang::CodeGen::CodeGenFunction cgf(cgmod);
}
CompilerEngine::CompilerEngine()
{
this->initCompiler();
// static llvm::Module *jit_types_mod = NULL;
auto load_jit_types_module = []() -> std::unique_ptr<llvm::Module> {
llvm::LLVMContext *ctx = new llvm::LLVMContext();
llvm::Module *module = new llvm::Module("jit_types_in_ce", *ctx);
// load module
QFile fp("./metalize/jit_types.ll");
fp.open(QIODevice::ReadOnly);
QByteArray asm_data = fp.readAll();
fp.close();
char *asm_str = strdup(asm_data.data());
qDebug()<<"llstrlen:"<<strlen(asm_str);
llvm::SMDiagnostic smdiag;
std::unique_ptr<llvm::Module> rmod;
rmod = llvm::parseAssemblyString(asm_str, smdiag, *ctx);
qDebug()<<"rmod="<<rmod.get();
free(asm_str);
return rmod;
};
// mtmod = load_jit_types_module();
// mtmod = NULL;
}
CompilerEngine::~CompilerEngine()
{
}
bool CompilerEngine::initCompiler()
{
clang::CompilerInstance *cis = new clang::CompilerInstance();
clang::CompilerInvocation *civ = new clang::CompilerInvocation();
cis->createDiagnostics();
cis->createFileManager();
cis->createSourceManager(cis->getFileManager());
cis->createFrontendTimer();
// cis.createASTContext();
// cis.createModuleManager();
std::string path = "./myjitqt";
clang::driver::Driver *drv = new clang::driver::Driver(path, llvm::sys::getProcessTriple(),
cis->getDiagnostics());
drv->setTitle("myjitclangpp");
drv->setCheckInputsExist(false);
this->mcis = cis;
this->mciv = civ;
this->mdrv = drv;
static char *argv[] = {
(char*)"myjitqtrunner", (char*)"flycode.cxx",
(char*)"-fPIC", (char*)"-x", (char*)"c++",
(char*)"-I/usr/include/qt", (char*)"-I/usr/include/qt/QtCore",
(char*)"-I/usr/lib/clang/3.5.0/include",
};
static int argc = 8;
char **targv = argv;
llvm::SmallVector<const char*, 16> drv_args(targv, targv + argc);
drv_args.push_back("-S");
clang::driver::Compilation *C = drv->BuildCompilation(drv_args);
const clang::driver::JobList &Jobs = C->getJobs();
const clang::driver::Command *Cmd = llvm::cast<clang::driver::Command>(&(*Jobs.begin()));
const clang::driver::ArgStringList &CCArgs = Cmd->getArguments();
// clang::CompilerInvocation *civ = new clang::CompilerInvocation();
bool bret = clang::CompilerInvocation::CreateFromArgs(*civ,
const_cast<const char**>(CCArgs.data()),
const_cast<const char**>(CCArgs.data()) + CCArgs.size(),
cis->getDiagnostics());
cis->setInvocation(civ);
return true;
}
// 从一个模块转移到另一个模块
bool irfunccpy(llvm::Module *smod, llvm::Function *sfun, llvm::Module *dmod, llvm::Function *dfun)
{
return false;
}
void walk_decl(QStack<clang::Stmt*> &fexpr, clang::Stmt *bstmt, int level)
{
clang::Stmt *stmts = bstmt;
for (auto expr: stmts->children()) {
qDebug()<<"e:"<<expr<<level;
if (expr == 0) {
// bstmt->dumpColor();
DUMP_COLOR(bstmt);
continue;
}
qDebug()<<"e:"<<expr->getStmtClassName()<<level;
// expr->dumpColor();
fexpr.push(expr);
walk_decl(fexpr, expr, level+1);
}
// initors
if (llvm::isa<clang::CXXConstructExpr>(stmts)) {
auto ctor_decl = llvm::cast<clang::CXXConstructExpr>(stmts)->getConstructor();
for (auto ci: ctor_decl->inits()) {
auto e = ci->getInit();
qDebug()<<"ctorinit..."<<e;
// e->dumpColor();
DUMP_COLOR(e);
fexpr.push(e);
walk_decl(fexpr, e, level+1);
}
}
}
// 起始decl,一般是一个函数或者方法的定义
clang::FunctionDecl*
CompilerEngine::find_callee_decl_by_symbol2(clang::Decl *bdecl, QString callee_symbol)
{
qDebug()<<callee_symbol;
clang::Stmt *stmts = bdecl->getBody();
QStack<clang::Stmt*> fexpr; // flat expr
if (stmts != NULL) {
DUMP_COLOR(bdecl);
qDebug()<<"Wooooo, body decl...."<<stmts;
int cnter = 0;
for (auto expr: stmts->children()) {
qDebug()<<"e:"<<cnter++<<expr->getStmtClassName();
// expr->dumpColor();
fexpr.push(expr);
}
walk_decl(fexpr, stmts, 1);
}
if (llvm::isa<clang::CXXConstructorDecl>(bdecl)) {
auto ctor_decl = llvm::cast<clang::CXXConstructorDecl>(bdecl);
for (auto ci: ctor_decl->inits()) {
auto e = ci->getInit();
qDebug()<<"ctorinit..."<<e;
// e->dumpColor();
DUMP_COLOR(e);
fexpr.push(e);
walk_decl(fexpr, e, 1);
}
}
qDebug()<<"flat expr count:"<<fexpr.count();
// bdecl->dumpColor();
auto mgctx = bdecl->getASTContext().createMangleContext();
// 查找可能的函数/方法调用列表表达式。
while (!fexpr.isEmpty()) {
clang::Stmt *s = fexpr.pop();
qDebug()<<"flated..."<<s;
// s->dumpColor();
DUMP_COLOR(s);
if (llvm::isa<clang::CXXConstructExpr>(s)) {
clang::CXXConstructorDecl *d = llvm::cast<clang::CXXConstructExpr>(s)->getConstructor();
std::string str; llvm::raw_string_ostream stm(str);
std::string str2; llvm::raw_string_ostream stm2(str2);
mgctx->mangleCXXCtor(d, clang::Ctor_Base, stm);
mgctx->mangleCXXCtor(d, clang::Ctor_Complete, stm2);
qDebug()<<"mangle name:"<<"base:"<<stm.str().c_str()
<<",complete:"<<stm2.str().c_str()
<<",need:"<<callee_symbol;
if (stm.str() == callee_symbol.toStdString()
|| stm2.str() == callee_symbol.toStdString()) {
if (clang::isa<clang::FunctionDecl>(d)) {
return clang::cast<clang::FunctionDecl>(d);
}
}
}
else if (llvm::isa<clang::CallExpr>(s)) {
auto d = llvm::cast<clang::CallExpr>(s)->getCalleeDecl();
// d->dumpColor();
std::string str; llvm::raw_string_ostream stm(str);
mgctx->mangleName(clang::cast<clang::NamedDecl>(d), stm);
qDebug()<<"mangle name:"<<stm.str().c_str()<<",callee symbol:"<<callee_symbol;
if (stm.str() != callee_symbol.toStdString()) continue;
if (clang::isa<clang::FunctionDecl>(d)) {
return clang::cast<clang::FunctionDecl>(d);
}
assert(1==2);
}
else if (llvm::isa<clang::CXXTemporaryObjectExpr>(s)) {
qDebug()<<"not impled.";
}
else {
// qDebug()<<"do smth."<<s<<s->getStmtClassName();
}
}
return NULL;
}
// 起始decl,一般是一个函数或者方法的定义
clang::FunctionDecl*
CompilerEngine::find_callee_decl_by_symbol(clang::Decl *bdecl, QString callee_symbol)
{
qDebug()<<callee_symbol;
clang::Stmt *stmts = bdecl->getBody();
QStack<clang::Stmt*> fexpr; // flat expr
QVector<clang::CallExpr*> cexpr; // call expr
QVector<clang::CXXTemporaryObjectExpr*> toexpr; // 临时对象生成语句,和call类似,这里会有一个symbol
if (stmts != NULL) {
qDebug()<<"Wooooo...."<<stmts;
int cnter = 0;
for (auto expr: stmts->children()) {
qDebug()<<"e:"<<cnter++<<expr->getStmtClassName();
// expr->dumpColor();
fexpr.push(expr);
}
walk_decl(fexpr, stmts, 1);
}
qDebug()<<"flat expr count:"<<fexpr.count();
auto mgctx = bdecl->getASTContext().createMangleContext();
// 查找可能的函数/方法调用列表表达式。
while (!fexpr.isEmpty()) {
clang::Stmt *s = fexpr.pop();
if (s == NULL) {
qDebug()<<"Why NULL Stmt???"<<fexpr;
// qFatal("Why NULL Stmt???");
continue;
}
int cnter = 0;
for (auto expr: s->children()) {
cnter++;
fexpr.push(expr);
}
// qDebug()<<"push child:"<<cnter<<s->getStmtClassName();
if (clang::isa<clang::CallExpr>(s)) {
cexpr.append(clang::cast<clang::CallExpr>(s));
}
else if (llvm::isa<clang::CXXTemporaryObjectExpr>(s)) {
toexpr.append(llvm::cast<clang::CXXTemporaryObjectExpr>(s));
}
else if (llvm::isa<clang::ReturnStmt>(s)) {
// qDebug()<<"do smth."<<s;
// s->dumpColor();
qDebug()<<"do smth."<<s<<s->getStmtClassName();
}
else {
qDebug()<<"do smth."<<s<<s->getStmtClassName();
}
}
qDebug()<<bdecl<<"call expr count:"<<cexpr.count();
for (auto expr: cexpr) {
qDebug()<<"==========";
// expr->dumpColor();
auto d = expr->getCalleeDecl();
// d->dumpColor();
std::string str; llvm::raw_string_ostream stm(str);
mgctx->mangleName(clang::cast<clang::NamedDecl>(d), stm);
qDebug()<<"mangle name:"<<stm.str().c_str()<<",callee symbol:"<<callee_symbol;
if (stm.str() != callee_symbol.toStdString()) continue;
if (clang::isa<clang::FunctionDecl>(d)) {
return clang::cast<clang::FunctionDecl>(d);
}
assert(1==2);
// for test
if (clang::isa<clang::CXXMethodDecl>(d)) {
auto d1 = clang::cast<clang::CXXMethodDecl>(d);
this->conv_method(bdecl->getASTContext(), d1);
}
}
// qDebug()<<"toexpr count:"<<toexpr.count();
for (auto expr: toexpr) {
// qDebug()<<"see toexpr's decl:"<<expr;
// expr->getConstructor()->dumpColor();
DUMP_COLOR(expr->getConstructor());
return expr->getConstructor();
}
// for ctor's CtorInit
if (llvm::isa<clang::CXXConstructorDecl>(bdecl)) {
auto ctor_decl = llvm::cast<clang::CXXConstructorDecl>(bdecl);
for (auto ci: ctor_decl->inits()) {
auto e = ci->getInit();
qDebug()<<"ctorinit..."<<e;
// e->dumpColor();
DUMP_COLOR(e);
auto d = this->find_callee_decl_by_symbol(bdecl, callee_symbol, e);
if (d) return d;
}
}
return NULL;
}
clang::FunctionDecl*
CompilerEngine::find_callee_decl_by_symbol(clang::Decl *bdecl, QString callee_symbol,
clang::Stmt *bstmt)
{
clang::Stmt *stmts = bstmt;
QStack<clang::Stmt*> fexpr; // flat expr
QVector<clang::CallExpr*> cexpr; // call expr
QVector<clang::CXXConstructExpr*> ctor_expr;
int cnter = 0;
for (auto expr: stmts->children()) {
qDebug()<<"e:"<<cnter++<<expr->getStmtClassName();
// expr->dumpColor();
fexpr.push(expr);
}
walk_decl(fexpr, bstmt, 1);
if (fexpr.count() == 0 && llvm::isa<clang::Expr>(bstmt)) {
fexpr.push(bstmt);
}
qDebug()<<"flat expr count:"<<fexpr.count();
auto mgctx = bdecl->getASTContext().createMangleContext();
// 查找可能的函数/方法调用列表表达式。
while (!fexpr.isEmpty()) {
clang::Stmt *s = fexpr.pop();
for (auto expr: s->children()) {
fexpr.push(expr);
}
if (clang::isa<clang::CallExpr>(s)) {
cexpr.append(clang::cast<clang::CallExpr>(s));
}
else if (clang::isa<clang::MemberExpr>(s)) {
}
else if (clang::isa<clang::DeclRefExpr>(s)) {
auto d = llvm::cast<clang::DeclRefExpr>(s)->getDecl();
qDebug()<<"dddddddref"<<d->getName().data();
// d->dumpColor();
DUMP_COLOR(d);
if (0) {
std::string str; llvm::raw_string_ostream stm(str);
mgctx->mangleName(clang::cast<clang::NamedDecl>(d), stm);
qDebug()<<"mangle name:"<<stm.str().c_str();
}
}
else if (llvm::isa<clang::CXXConstructExpr>(s)) {
ctor_expr.append(llvm::cast<clang::CXXConstructExpr>(s));
}
else if (llvm::isa<clang::CXXDefaultArgExpr>(s)) {
auto *daexpr = llvm::cast<clang::CXXDefaultArgExpr>(s);
auto *e = daexpr->getExpr();
// e->dumpColor();
DUMP_COLOR(e);
if (llvm::isa<clang::CXXConstructExpr>(e)) {
ctor_expr.append(llvm::cast<clang::CXXConstructExpr>(e));
QStack<clang::Stmt*> texpr; // flat expr
walk_decl(texpr, e, 1);
qDebug()<<texpr.count();
while (!texpr.isEmpty()) {
clang::Stmt *s = texpr.pop();
if (llvm::isa<clang::CXXConstructExpr>(s)) {
ctor_expr.append(llvm::cast<clang::CXXConstructExpr>(s));
}
}
}
}
else {
qDebug()<<"stmt..."<<s<<s->getStmtClassName();
}
}
if (cexpr.count() == 0 && llvm::isa<clang::CallExpr>(bstmt)) {
cexpr.append(llvm::cast<clang::CallExpr>(bstmt));
}
qDebug()<<"call expr count:"<<cexpr.count()<<ctor_expr.count();
for (auto expr: cexpr) {
qDebug()<<"==========";
// expr->dumpColor();
auto d = expr->getCalleeDecl();
// d->dumpColor();
std::string str; llvm::raw_string_ostream stm(str);
mgctx->mangleName(clang::cast<clang::NamedDecl>(d), stm);
qDebug()<<"mangle name:"<<stm.str().c_str();
if (stm.str() != callee_symbol.toStdString()) continue;
if (clang::isa<clang::FunctionDecl>(d)) {
return clang::cast<clang::FunctionDecl>(d);
}
assert(1==2);
// for test
if (clang::isa<clang::CXXMethodDecl>(d)) {
auto d1 = clang::cast<clang::CXXMethodDecl>(d);
this->conv_method(bdecl->getASTContext(), d1);
}
}
for (auto expr: ctor_expr) {
auto cd = expr->getConstructor();
std::string str; llvm::raw_string_ostream stm(str);
std::string str2; llvm::raw_string_ostream stm2(str2);
mgctx->mangleCXXCtor(cd, clang::Ctor_Base, stm);
mgctx->mangleCXXCtor(cd, clang::Ctor_Complete, stm2);
qDebug()<<"mangle name:"<<"base:"<<stm.str().c_str()
<<",complete:"<<stm2.str().c_str()
<<",need:"<<callee_symbol;
if (stm.str() == callee_symbol.toStdString()
|| stm2.str() == callee_symbol.toStdString()) {
if (clang::isa<clang::FunctionDecl>(cd)) {
return clang::cast<clang::FunctionDecl>(cd);
}
}
}
return NULL;
}
// 第一种方式,拿到还未定义的symbol,到ast中查找
// 第二种方式,解析C++方法的源代码,找到这个未定义的symbol,从decl再把它编译成ll,效率更好。
void CompilerEngine::decl2def(llvm::Module *mod, clang::ASTContext &ctx,
clang::CodeGen::CodeGenModule &cgmod,
clang::Decl *decl, int level, QHash<QString, bool> noinlined)
{
QHash<QString, bool> efuns;
/*llvm::Module *jit_types_mod = NULL;
if (jit_types_mod == NULL) {
jit_types_mod = mtmod;
// jit_types_mod->dump();
for (auto &f: jit_types_mod->getFunctionList()) {
efuns.insert(QString(f.getName().data()), true);
}
}
qDebug()<<"exists funcs:"<<efuns.count()<<efuns;
*/
auto llfunc_cpy = []() {
// emu empty for compile
llvm::Module *jit_types_mod = NULL;
llvm::Module *mod = NULL;
QString fname;
// copy可能遇到需要递归的指定,如call,或者一些全局变量也需要同时处理。
// 还是比较复杂的。
auto srcf = jit_types_mod->getFunction(fname.toLatin1().data());
auto dstf = mod->getFunction(fname.toLatin1().data());
llvm::IRBuilder<> builder(mod->getContext());
// llvm::BasicBlock *entry = llvm::BasicBlock::Create(mod->getContext(),
// "clvm_func_entrypoint", dstf);
// builder.SetInsertPoint(entry);
// qDebug()<<entry<<dstf;
for (auto &blk: *srcf) {
qDebug()<<","<<blk.getName().data()<<",";
llvm::BasicBlock *tb = llvm::BasicBlock::Create(mod->getContext(),
blk.getName(), dstf);
builder.SetInsertPoint(tb);
for (auto &ins: blk) {
auto ni = ins.clone();
builder.Insert(ni);
qDebug()<<&blk<<&ins<<ins.getName().data()<<"opc:"<<ins.getOpcodeName()<<ins.getOpcode();
if (ins.getOpcode() == llvm::Instruction::Call) {
llvm::CallInst *ci = llvm::cast<llvm::CallInst>(ni);
qDebug()<<"call arg num:"<<ci->getNumArgOperands();
auto called_func = ci->getArgOperand(0);
qDebug()<<"afun?"<<called_func->getName().data()
<<llvm::isa<llvm::Function>(called_func);
}
}
}
};
int copyed = 0;
QVector<QString> gfuns;
for (auto &f: mod->getFunctionList()) {
QString fname = f.getName().data();
qDebug()<<"name:"<<f.getName().data()<<f.size()<<"decl:"<<f.isDeclaration();
if (!f.isDeclaration()) {
continue;
}
if (noinlined.contains(fname)) {
continue;
}
// 如果判断是不是inline的呢。
if (efuns.contains(fname)) {
// copy function from prepared module
qDebug()<<"copying func:"<<fname;
continue;
copyed ++;
continue;
}
gfuns.append(fname);
}
qDebug()<<"need gen funs:"<<gfuns.count()<<copyed;
if (gfuns.count() == 0 && copyed == 0) return;
// assert(islined and hasinlinedbody)
auto get_decl_with_body = [](clang::CXXMethodDecl *mth) -> decltype(mth) {
if (mth->hasInlineBody()) return mth;
int cnt = 0;
for (auto rd: mth->redecls()) cnt++;
if (cnt == 1) return mth;
for (auto rd: mth->redecls()) {
if (rd == mth) continue;
return (decltype(mth))rd;
}
return 0;
};
auto genmth = [](clang::CodeGen::CodeGenModule &cgm,
clang::CodeGen::CodeGenFunction &cgf,
clang::CXXMethodDecl *decl) -> bool {
clang::CodeGen::CodeGenTypes &cgtypes = cgm.getTypes();
const clang::CodeGen::CGFunctionInfo &FI =
cgtypes.arrangeCXXMethodDeclaration(decl);
llvm::FunctionType *FTy = cgtypes.GetFunctionType(FI);
clang::QualType retype = decl->getReturnType();
llvm::Type *lvtype = cgtypes.ConvertType(retype);
llvm::Constant * v = cgm.GetAddrOfFunction(decl, FTy,
false, false);
llvm::Function *f = llvm::cast<llvm::Function>(v);
qDebug()<<"dbg func:"<<f<<f->arg_size()
<< cgf.CapturedStmtInfo;
// f->viewCFG();
// clang::Stmt *stmt = decl->getBody();
clang::CodeGen::FunctionArgList alist;
cgf.GenerateCode(clang::GlobalDecl(decl), f, FI);
f->addFnAttr(llvm::Attribute::AlwaysInline);
cgm.setFunctionLinkage(decl, f);
return false;
};
// TODO 无法生成正确的函数参数信息,所有参数类型全部成了i64了
// eg. declare void @_ZN7QObject7connectEPKS_PKcS1_S3_N2Qt14ConnectionTypeE
// (%"class.QMetaObject::Connection"* sret, i64, i64, i64, i64, i32) #0
auto genmth_decl = [](clang::CodeGen::CodeGenModule &cgm,
clang::CodeGen::CodeGenFunction &cgf,
clang::CXXMethodDecl *decl
) -> bool {
clang::CodeGen::CodeGenTypes &cgtypes = cgm.getTypes();
const clang::CodeGen::CGFunctionInfo &FI =
cgtypes.arrangeCXXMethodDeclaration(decl);
llvm::FunctionType *FTy = cgtypes.GetFunctionType(FI);
clang::QualType retype = decl->getReturnType();
llvm::Type *lvtype = cgtypes.ConvertType(retype);
cgm.EmitGlobal(decl);
llvm::Constant * v = cgm.GetAddrOfFunction(decl, FTy,
false, false);
llvm::Function *f = llvm::cast<llvm::Function>(v);
// FTy->dump();
qDebug()<<"dbg func:"<<f<<f->arg_size()
<< cgf.CapturedStmtInfo<<decl->param_size();
int cnter = 0;
for (auto &arg: f->getArgumentList()) {
if (arg.hasStructRetAttr()) continue; // skip sret
if (!decl->isStatic()) continue; // skip this
// qDebug()<<cnter<<cgtypes.ConvertType(decl->getParamDecl(cnter)->getType());
arg.mutateType(cgtypes.ConvertType(decl->getParamDecl(cnter++)->getType()));
// 该函数执行后,mod->dump()看不出来变化,但是在用程序检测的时候却改变了。
}
return false;
};
for (auto fname: gfuns) {
auto d = find_callee_decl_by_symbol(decl, fname);
if (d == NULL) continue;
if (clang::isa<clang::CXXMethodDecl>(d)) {
auto d1 = get_decl_with_body(clang::cast<clang::CXXMethodDecl>(d));
clang::CodeGen::CodeGenFunction cgf(cgmod);
if (d1->isInlined()) {
genmth(cgmod, cgf, d1);
} else {
genmth_decl(cgmod, cgf, d1);
}
}
// mod->dump();
DUMP_IR(mod);
exit(-1);
}
if (level > 10) {
qDebug()<<"maybe too much recursive level.";
exit(-1);
}
decl2def(mod, ctx, cgmod, decl, ++level, noinlined);
}
// todo 还需要一个递归生成的过程,多次检查生成的结果是否有inline方法
llvm::Module* CompilerEngine::conv_ctor(clang::ASTContext &ctx, clang::CXXConstructorDecl *ctor)
{
clang::CompilerInstance ci;
// ci.createASTContext();
ci.createDiagnostics();
ci.createFileManager();
clang::DiagnosticsEngine &diag = ci.getDiagnostics();
clang::CodeGenOptions &cgopt = ci.getCodeGenOpts();
auto vmctx = new llvm::LLVMContext();
auto mod = new llvm::Module("piecegen", *vmctx);
mod->setDataLayout(ctx.getTargetInfo().getTargetDescription());
// llvm::DataLayout dlo("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
llvm::DataLayout dlo(ctx.getTargetInfo().getTargetDescription());
clang::HeaderSearchOptions headersearchopts;
clang::PreprocessorOptions ppopts;
clang::CodeGen::CodeGenModule cgmod(ctx, headersearchopts, ppopts, cgopt, *mod, dlo, diag);
auto &cgtypes = cgmod.getTypes();
auto cgf = new clang::CodeGen::CodeGenFunction(cgmod);
// assert(islined and hasinlinedbody)
auto get_decl_with_body = [](clang::CXXConstructorDecl *ctor) -> decltype(ctor) {
if (ctor->hasInlineBody()) return ctor;
int cnt = 0;
for (auto rd: ctor->redecls()) cnt++;
if (cnt == 1) return ctor;
for (auto rd: ctor->redecls()) {
if (rd == ctor) continue;
return (decltype(ctor))rd;
}
return 0;
};
ctor = get_decl_with_body(ctor);
// try ctor base , 能生成正确的Base代码了
const clang::CodeGen::CGFunctionInfo &FIB =
cgtypes.arrangeCXXStructorDeclaration(ctor, clang::CodeGen::StructorType::Base);
llvm::FunctionType *FTyB = cgtypes.GetFunctionType(FIB);
llvm::Constant *ctor_base_val =
cgmod.getAddrOfCXXStructor(ctor, clang::CodeGen::StructorType::Base, &FIB, FTyB, true);
llvm::Function *ctor_base_fn = clang::cast<llvm::Function>(ctor_base_val);
clang::CodeGen::FunctionArgList alist;
QHash<QString, bool> noinlined; // 不需要生成define的symbol,在decl2def中使用。
if (ctor->isInlined()) {
cgmod.setFunctionLinkage(clang::GlobalDecl(ctor, clang::Ctor_Base), ctor_base_fn);
cgf->GenerateCode(clang::GlobalDecl(ctor, clang::Ctor_Base), ctor_base_fn, FIB);
} else {
noinlined[ctor_base_fn->getName().data()] = true;
}
// mod->dump();
DUMP_IR(mod);
// ??? 没用了吧
QHash<QString, llvm::Function*> usyms;
for (auto &f: mod->getFunctionList()) {
qDebug()<<"name:"<<f.getName().data()<<f.size()<<f.isDeclaration();
if (f.isDeclaration()) usyms.insert(QString(f.getName().data()), &f);
}
// ctor->dumpColor();
DUMP_COLOR(ctor);
// 遍历body stmt
auto s = ctor->getBody();
// s->dumpColor();
DUMP_COLOR(s);
// 遍历Ctor init
for (auto i: ctor->inits()) {
auto s = i->getInit();
auto cs = clang::cast<clang::CallExpr>(s);
// s->dumpColor();
DUMP_COLOR(s);
auto d = cs->getCalleeDecl();
// d->dumpColor();
DUMP_COLOR(d);
auto sd = clang::cast<clang::CXXMethodDecl>(d);
qDebug()<<"call name:"<<cgmod.getMangledName(clang::cast<clang::CXXMethodDecl>(d)).data();
// this->conv_ctor(ctx, sd);
QString tmp = cgmod.getMangledName(sd).data();
if (usyms.contains(tmp)) {
llvm::Function *f = usyms.value(tmp);
// need def
qDebug()<<"need def:"<<tmp<<f;
}
break;
}
// mod->dump();
DUMP_IR(mod);
decl2def(mod, ctx, cgmod, ctor, 0, noinlined);
// mod->dump();
DUMP_IR(mod);
return mod;
}
// 这个方法支持普通方法,static也可以,非template
// 已知问题,不支持模板类中的静态方法。
// TODO 模板类中的静态方法支持
llvm::Module* CompilerEngine::conv_method(clang::ASTContext &ctx, clang::CXXMethodDecl *mth)
{
clang::CompilerInstance ci;
// ci.createASTContext();
ci.createDiagnostics();
ci.createFileManager();
clang::DiagnosticsEngine &diag = ci.getDiagnostics();
clang::CodeGenOptions &cgopt = ci.getCodeGenOpts();
auto vmctx = new llvm::LLVMContext();
auto mod = new llvm::Module("piecegen2", *vmctx);
mod->setDataLayout(ctx.getTargetInfo().getTargetDescription());
// llvm::DataLayout dlo("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
llvm::DataLayout dlo(ctx.getTargetInfo().getTargetDescription());
clang::HeaderSearchOptions headersearchopts;
clang::PreprocessorOptions ppopts;
clang::CodeGen::CodeGenModule cgmod(ctx, headersearchopts, ppopts, cgopt, *mod, dlo, diag);
auto &cgtypes = cgmod.getTypes();
auto cgf = new clang::CodeGen::CodeGenFunction(cgmod);
// assert(islined and hasinlinedbody)
auto get_decl_with_body = [](clang::CXXMethodDecl *mth) -> decltype(mth) {
if (mth->hasInlineBody()) return mth;
int cnt = 0;
for (auto rd: mth->redecls()) cnt++;
if (cnt == 1) return mth;
for (auto rd: mth->redecls()) {
if (rd == mth) continue;
return (decltype(mth))rd;
}
return 0;
};
mth = get_decl_with_body(mth);
auto genmth = [](clang::CodeGen::CodeGenModule &cgm,
clang::CodeGen::CodeGenFunction &cgf,
clang::CXXMethodDecl *decl) -> bool {
clang::CodeGen::CodeGenTypes &cgtypes = cgm.getTypes();
const clang::CodeGen::CGFunctionInfo &FI =
cgtypes.arrangeCXXMethodDeclaration(decl);
llvm::FunctionType *FTy = cgtypes.GetFunctionType(FI);
clang::QualType retype = decl->getReturnType();
llvm::Type *lvtype = cgtypes.ConvertType(retype);
llvm::Constant * v = cgm.GetAddrOfFunction(decl, FTy,
false, false);
llvm::Function *f = llvm::cast<llvm::Function>(v);
qDebug()<<"dbg func:"<<f<<f->arg_size()
<< cgf.CapturedStmtInfo;
// f->viewCFG();
// clang::Stmt *stmt = decl->getBody();
clang::CodeGen::FunctionArgList alist;
cgf.GenerateCode(clang::GlobalDecl(decl), f, FI);
f->addFnAttr(llvm::Attribute::AlwaysInline);
cgm.setFunctionLinkage(decl, f);
return false;
};
// TODO 无法生成正确的函数参数信息,所有参数类型全部成了i64了
// eg. declare void @_ZN7QObject7connectEPKS_PKcS1_S3_N2Qt14ConnectionTypeE
// (%"class.QMetaObject::Connection"* sret, i64, i64, i64, i64, i32) #0
auto genmth_decl = [](clang::CodeGen::CodeGenModule &cgm,
clang::CodeGen::CodeGenFunction &cgf,
clang::CXXMethodDecl *decl
) -> bool {
clang::CodeGen::CodeGenTypes &cgtypes = cgm.getTypes();
const clang::CodeGen::CGFunctionInfo &FI =
cgtypes.arrangeCXXMethodDeclaration(decl);
llvm::FunctionType *FTy = cgtypes.GetFunctionType(FI);
clang::QualType retype = decl->getReturnType();
llvm::Type *lvtype = cgtypes.ConvertType(retype);
cgm.EmitGlobal(decl);
llvm::Constant * v = cgm.GetAddrOfFunction(decl, FTy,
false, false);
llvm::Function *f = llvm::cast<llvm::Function>(v);
// FTy->dump();
qDebug()<<"dbg func:"<<f<<f->arg_size()
<< cgf.CapturedStmtInfo<<decl->param_size();
int cnter = 0;
for (auto &arg: f->getArgumentList()) {
if (arg.hasStructRetAttr()) continue; // skip sret
if (!decl->isStatic()) continue; // skip this
// qDebug()<<cnter<<cgtypes.ConvertType(decl->getParamDecl(cnter)->getType());
arg.mutateType(cgtypes.ConvertType(decl->getParamDecl(cnter++)->getType()));
// 该函数执行后,mod->dump()看不出来变化,但是在用程序检测的时候却改变了。
}
return false;
};
QHash<QString, bool> noinlined; // 不需要生成define的symbol,在decl2def中使用。
if (mth->isInlined()) {
genmth(cgmod, *cgf, mth);
} else {
genmth_decl(cgmod, *cgf, mth);
noinlined[cgmod.getMangledName(mth).data()] = true;
}
qDebug()<<"dump module after gencode...";
// mod->dump();
DUMP_IR(mod);
decl2def(mod, ctx, cgmod, mth, 0, noinlined);
qDebug()<<"dump module after all...";
// mod->dump();
DUMP_IR(mod);
return mod;
}
// TODO 使用 MangleContext::MangleCtor 代替当前方式。
QString CompilerEngine::mangle_ctor(clang::ASTContext &ctx, clang::CXXConstructorDecl *ctor)
{
clang::CompilerInstance ci;
// ci.createASTContext();
ci.createDiagnostics();
ci.createFileManager();
clang::DiagnosticsEngine &diag = ci.getDiagnostics();
clang::CodeGenOptions &cgopt = ci.getCodeGenOpts();
auto vmctx = new llvm::LLVMContext();
auto mod = new llvm::Module("piecegen", *vmctx);
mod->setDataLayout(ctx.getTargetInfo().getTargetDescription());
// llvm::DataLayout dlo("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
llvm::DataLayout dlo(ctx.getTargetInfo().getTargetDescription());
clang::HeaderSearchOptions headersearchopts;
clang::PreprocessorOptions ppopts;
clang::CodeGen::CodeGenModule cgmod(ctx, headersearchopts, ppopts, cgopt, *mod, dlo, diag);
auto &cgtypes = cgmod.getTypes();
auto cgf = new clang::CodeGen::CodeGenFunction(cgmod);
auto vm_symname = cgmod.getMangledName(clang::GlobalDecl(ctor, clang::Ctor_Base));
QString symname = vm_symname.data();
return symname;
}
// TODO 使用 MangleContext::MangleCtor 代替当前方式。
QString CompilerEngine::mangle_dtor(clang::ASTContext &ctx, clang::CXXDestructorDecl *dtor)
{
clang::CompilerInstance ci;
// ci.createASTContext();
ci.createDiagnostics();
ci.createFileManager();
clang::DiagnosticsEngine &diag = ci.getDiagnostics();
clang::CodeGenOptions &cgopt = ci.getCodeGenOpts();
auto vmctx = new llvm::LLVMContext();
auto mod = new llvm::Module("piecegen", *vmctx);
mod->setDataLayout(ctx.getTargetInfo().getTargetDescription());
// llvm::DataLayout dlo("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
llvm::DataLayout dlo(ctx.getTargetInfo().getTargetDescription());
clang::HeaderSearchOptions headersearchopts;
clang::PreprocessorOptions ppopts;
clang::CodeGen::CodeGenModule cgmod(ctx, headersearchopts, ppopts, cgopt, *mod, dlo, diag);
auto &cgtypes = cgmod.getTypes();
auto cgf = new clang::CodeGen::CodeGenFunction(cgmod);
auto vm_symname = cgmod.getMangledName(clang::GlobalDecl(dtor, clang::Dtor_Base));
QString symname = vm_symname.data();
return symname;
}
QString CompilerEngine::mangle_method(clang::ASTContext &ctx, clang::CXXMethodDecl *mth)
{
clang::CompilerInstance ci;
// ci.createASTContext();
ci.createDiagnostics();
ci.createFileManager();
clang::DiagnosticsEngine &diag = ci.getDiagnostics();
clang::CodeGenOptions &cgopt = ci.getCodeGenOpts();
auto vmctx = new llvm::LLVMContext();
auto mod = new llvm::Module("piecegen", *vmctx);
mod->setDataLayout(ctx.getTargetInfo().getTargetDescription());
// llvm::DataLayout dlo("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
llvm::DataLayout dlo(ctx.getTargetInfo().getTargetDescription());
clang::HeaderSearchOptions headersearchopts;
clang::PreprocessorOptions ppopts;
clang::CodeGen::CodeGenModule cgmod(ctx, headersearchopts, ppopts, cgopt, *mod, dlo, diag);
auto &cgtypes = cgmod.getTypes();
auto cgf = new clang::CodeGen::CodeGenFunction(cgmod);
auto vm_symname = cgmod.getMangledName(clang::GlobalDecl(mth));
QString symname = vm_symname.data();
return symname;
return QString();
}