-
Notifications
You must be signed in to change notification settings - Fork 2
/
Translator.cpp
1499 lines (1473 loc) · 56.3 KB
/
Translator.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 "Translator.hpp"
/*
Default contructor:
- we need the LLVM context to access the cached LLVM-IR Modules
- we need the Triton context to access the AstContext and the symbolic variables
*/
Translator::Translator(LLVMContext& Context, API& Api) : Context(Context), Api(Api) {}
/*
Determine the Triton AST size.
*/
uint64_t Translator::DetermineASTSize(SharedAbstractNode Node, map<SharedAbstractNode, uint64_t>& Nodes) {
// Check if it's a known node -> size
if (Nodes.find(Node) != Nodes.end()) {
return Nodes[Node];
}
// We always consider the single AST as 1
uint64_t Size = 1;
// Handle the AST type
switch (Node->getType()) {
case ast_e::SX_NODE:
case ast_e::ZX_NODE:
case ast_e::LNOT_NODE:
case ast_e::BVNOT_NODE:
case ast_e::BVNEG_NODE:
case ast_e::EXTRACT_NODE: {
uint64_t Size1 = DetermineASTSize(Node->getChildren()[0], Nodes);
Size += Size1;
break;
}
case ast_e::BVSLT_NODE:
case ast_e::BVUGE_NODE:
case ast_e::BVUGT_NODE:
case ast_e::BVULE_NODE:
case ast_e::BVULT_NODE:
case ast_e::BVNAND_NODE:
case ast_e::BVNOR_NODE:
case ast_e::BVXNOR_NODE:
case ast_e::BVSLE_NODE:
case ast_e::BVSGT_NODE:
case ast_e::BVSGE_NODE:
case ast_e::DISTINCT_NODE:
case ast_e::EQUAL_NODE:
case ast_e::BVSMOD_NODE:
case ast_e::BVSREM_NODE:
case ast_e::BVUREM_NODE:
case ast_e::BVUDIV_NODE:
case ast_e::BVSDIV_NODE:
case ast_e::BVROR_NODE:
case ast_e::BVROL_NODE:
case ast_e::BVMUL_NODE:
case ast_e::BVSHL_NODE:
case ast_e::BVLSHR_NODE:
case ast_e::BVASHR_NODE:
case ast_e::LOR_NODE:
case ast_e::BVOR_NODE:
case ast_e::LAND_NODE:
case ast_e::BVAND_NODE:
case ast_e::BVXOR_NODE:
case ast_e::BVSUB_NODE:
case ast_e::BVADD_NODE: {
uint64_t Size1 = DetermineASTSize(Node->getChildren()[0], Nodes);
uint64_t Size2 = DetermineASTSize(Node->getChildren()[1], Nodes);
Size += (Size1 + Size2);
break;
}
case ast_e::ITE_NODE: {
uint64_t Size1 = DetermineASTSize(Node->getChildren()[0], Nodes);
uint64_t Size2 = DetermineASTSize(Node->getChildren()[1], Nodes);
uint64_t Size3 = DetermineASTSize(Node->getChildren()[2], Nodes);
Size += (Size1 + Size2 + Size3);
break;
}
case ast_e::CONCAT_NODE: {
for (auto Child : Node->getChildren()) {
Size += DetermineASTSize(Child, Nodes);
}
break;
}
default:
break;
}
// Save the sub-AST size in the dictionary
Nodes[Node] = Size;
// Return the calculated size
return Size;
}
/*
Converting a Triton AST to a LLVM-IR block.
*/
ConstantInt* Translator::GetDecimal(IntegerNode& Node, uint64_t BitVectorSize) {
// Construct a new integer from a string (so we can support arbitrarily long bitvectors)
stringstream ss;
ss << dec << Node.getInteger();
auto NodeValue = APInt(BitVectorSize, ss.str(), 10);
#ifdef VERBOSE_OUTPUT
cout << "GetDecimal: { bvsz = " << BitVectorSize << ", value = 0x" << hex << Node.getInteger() << " }" << endl;
#endif
return ConstantInt::get(this->Context, NodeValue);
}
/*
Worklist-based translation of a Triton AST to an LLVM-IR Module.
*/
Value* Translator::LiftNodesWBS(const SharedAbstractNode& TopNode, shared_ptr<IRBuilder<>> IR, map<ExpKey, shared_ptr<llvm::Module>>& Cache, ssize_t MaxDepth) {
// Use a dictionary for the known references
map<triton::usize, triton::engines::symbolic::SharedSymbolicExpression> References;
// Use a dictionary for the known AST nodes
map<SharedAbstractNode, Value*> Nodes;
// Counter for the fake global variable
size_t FakeIndex = 0;
// At this point we can translate the AST
auto Curr = make_shared<AstNode>(TopNode, nullptr);
while (Curr) {
// Print the node
#ifdef VERBOSE_OUTPUT
cout << "Handling: " << Curr->Node << endl;
Curr->print(llvm::errs(), false);
#endif
// Go to the parent if this node is already lifted
if (Nodes.find(Curr->Node) != Nodes.end()) {
#ifdef VERBOSE_OUTPUT
cout << "Translating: KNOWN_NODE" << endl;
#endif
// Get the parent
Curr = Curr->Parent;
// Restart the loop
continue;
}
// Check if we reached the maximum depth
if (Curr->Depth == MaxDepth) {
// Create a fake variable
stringstream ss;
ss << "FakeVar_";
ss << dec << Curr->Node->getBitvectorSize();
ss << "_";
ss << dec << FakeIndex++;
auto FakeVarName = ss.str();
auto FakeVar = new GlobalVariable(*this->Module, IntegerType::get(this->Context, Curr->Node->getBitvectorSize()), false, GlobalValue::CommonLinkage, nullptr, FakeVarName);
auto FakeLoad = IR->CreateLoad(FakeVar);
Nodes[Curr->Node] = FakeLoad;
continue;
}
// Craft a constant if possible and continue with the parent
if (!Curr->Node->isSymbolized() && Curr->Node->getType() != ast_e::INTEGER_NODE) {
#ifdef VERBOSE_OUTPUT
cout << "Translating: CONSTANT_NODE (size = " << Curr->Node->getBitvectorSize() << ")" << endl;
#endif
// Construct a new integer from a string (so we can support arbitrarily long bitvectors)
stringstream ss;
ss << dec << Curr->Node->evaluate();
auto NodeValue = APInt(Curr->Node->getBitvectorSize(), ss.str(), 10);
// Dump the constant value
#ifdef VERBOSE_OUTPUT
cout << "CONSTANT_NODE: " << ss.str() << endl;
#endif
// Get the constant
Nodes[Curr->Node] = ConstantInt::get(this->Context, NodeValue);
// Get the parent
Curr = Curr->Parent;
// Restart the loop
continue;
}
// Fetch the children of the node
auto Children = Curr->Node->getChildren();
// Handle the current node
if (Curr->Index < Children.size()) {
// Determine the child depth
size_t ChildDepth = Curr->Depth + 1;
// Create the child node
Curr = make_shared<AstNode>(Children[Curr->Index++], Curr);
// Save the child depth
Curr->Depth = ChildDepth;
} else {
#ifdef VERBOSE_OUTPUT
cout << "Translating: ";
#endif
// Get the current node
auto CNode = Curr->Node;
// Resolved reference flag
bool UnresolvedReference = false;
// Translate the node
switch (CNode->getType()) {
// Handle the reference node
case ast_e::REFERENCE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "REFERENCE_NODE: " << endl;
#endif
// Fetch the current "ReferenceNode"
auto* ReferenceAst = static_cast<ReferenceNode*>(CNode.get());
// Fetch the referenced expression
auto ReferencedExpression = ReferenceAst->getSymbolicExpression();
// Fetch the referenced AST
auto ReferencedAst = ReferencedExpression->getAst();
// Check if the referenced expression is in the cache
if (Cache.find(ReferencedExpression->getId()) != Cache.end()) {
#ifdef VERBOSE_OUTPUT
cout << "[!] Found a cached reference, continuing." << endl;
#endif
// Clone the Module (we don't want to destroy the original)
unique_ptr<llvm::Module> Cloned = llvm::CloneModule(*Cache[ReferencedExpression->getId()]);
// Generate a proper function name
string FunName = "ref" + to_string(ReferencedExpression->getId());
// Fetch and rename the referenced function
auto* RefFun = Cloned->getFunction("TritonAstFunction");
RefFun->setName(FunName);
// Link the modules together
if (Linker::linkModules(*this->Module, std::move(Cloned), llvm::Linker::Flags::OverrideFromSrc)) {
cout << "Error while linking the modules" << endl;
}
// Fetch all the declared global variables
for (auto& GVar : this->Module->getGlobalList()) {
// Detect the symbolic variables
StringRef VarName = GVar.getName();
if (VarName.startswith("SymVar")) {
this->VarsValue[VarName.str()] = &GVar;
}
}
// Get the linked copy of the function
RefFun = this->Module->getFunction(FunName);
// Call the referenced function
Nodes[CNode] = IR->CreateCall(RefFun);
} else if (References.find(ReferencedExpression->getId()) != References.end()) {
#ifdef VERBOSE_OUTPUT
cout << "[!] Found a resolved reference, caching it and continuing." << endl;
cout << "----------- Referenced Expression -----------" << endl;
cout << ReferencedExpression << endl;
cout << "---------------------------------------------" << endl;
cout << "----------- Referenced AST -----------" << endl;
cout << ReferencedAst << endl;
cout << "--------------------------------------" << endl;
#endif
// Fetch the main function (in the original module)
auto* MF = this->Module->getFunction("TritonAstFunction");
// Fetch the entry block
auto& EB = MF->getEntryBlock();
// Add a return instruction at the end of the entry block
auto* RI = ReturnInst::Create(this->Context, Nodes[ReferencedAst], &EB);
// Optimize the cloned module
this->OptimizeModule(this->Module.get());
// Debug print the optimized cloned module
#ifdef VERBOSE_OUTPUT
cout << "----------- Referenced Module -----------" << endl;
this->Module->print(llvm::errs(), false);
cout << "-----------------------------------------" << endl;
#endif
// Cache the optimized cloned module
Cache[ReferencedExpression->getId()] = this->Module;
// Mark the reference as fully resolved
References.erase(ReferencedExpression->getId());
// Restore the previous exploration state
if (Curr->Module) {
this->VarsValue = Curr->VarsValue;
this->Module = Curr->Module;
this->Vars = Curr->Vars;
Nodes = Curr->Nodes;
IR = Curr->IR;
}
// Notify we found an unresolved reference
UnresolvedReference = true;
} else {
#ifdef VERBOSE_OUTPUT
cout << "[!] Found an unresolved reference, adding it to the references to be solved." << endl;
cout << "----------- Referenced AST -----------" << endl;
cout << ReferencedAst << endl;
cout << "--------------------------------------" << endl;
#endif
// Mark the reference as known
References[ReferencedExpression->getId()] = ReferencedExpression;
// Backup the current exploration state
Curr->VarsValue = this->VarsValue;
Curr->Module = this->Module;
Curr->Vars = this->Vars;
Curr->Nodes = Nodes;
Curr->IR = IR;
// Determine the child depth
size_t ChildDepth = Curr->Depth + 1;
// Craft a new child node
Curr = make_shared<AstNode>(ReferencedAst, Curr);
// Save the child depth
Curr->Depth = ChildDepth;
// Save the expression reference when known
Curr->Expression = ReferencedExpression;
// Reset the exploration state
this->VarsValue.clear();
this->Vars.clear();
Nodes.clear();
// Allocate a new module with the proper signature
this->Module = make_shared<llvm::Module>("NewTritonAstModule", this->Context);
// Create the function type (consistent with the top node type)
auto* TritonAstType = FunctionType::get(IntegerType::get(this->Context, ReferencedAst->getBitvectorSize()), false);
// Create the function (which will contain the basic block)
auto* TritonAstFunction = Function::Create(TritonAstType, llvm::Function::CommonLinkage, "TritonAstFunction", this->Module.get());
// Mark the function as always inlineable
TritonAstFunction->addFnAttr(Attribute::AlwaysInline);
// Create the only basic block (which will contain the lifted instructions)
auto* TritonAstBlock = BasicBlock::Create(this->Context, "TritonAstEntry", TritonAstFunction);
// Initialize the IRBuilder to lift the nodes
IR = make_shared<IRBuilder<>>(TritonAstBlock);
// Notify we found an unresolved reference
UnresolvedReference = true;
}
} break;
// Handle the terminal nodes
case ast_e::BV_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BV_NODE" << endl;
#endif
// Construct a new integer from a string (so we can support arbitrarily long bitvectors)
stringstream ss;
ss << dec << CNode->evaluate();
auto NodeValue = APInt(CNode->getBitvectorSize(), ss.str(), 10);
Nodes[CNode] = ConstantInt::get(this->Context, NodeValue);
} break;
case ast_e::INTEGER_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "INTEGER_NODE" << endl;
#endif
Nodes[CNode] = nullptr;
// Ignoring this node
} break;
case ast_e::VARIABLE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "VARIABLE_NODE" << endl;
#endif
// Get the VariableNode
auto* Node = (VariableNode*)(CNode.get());
// Get the variable name
string VarName = Node->getSymbolicVariable()->getName();
// Determine if it's a known variable
if (this->VarsValue.find(VarName) != this->VarsValue.end()) {
// It's known, fetch the old Value
Nodes[CNode] = this->VarsValue[VarName];
// If it's a GlobalVariable, create a load
if (auto* gv = dyn_cast<GlobalVariable>(Nodes[CNode])) {
Nodes[CNode] = IR->CreateLoad(Nodes[CNode]);
}
} else {
// First we create the global variable
Nodes[CNode] = new GlobalVariable(*this->Module, IntegerType::get(this->Context, CNode->getBitvectorSize()), false, GlobalValue::CommonLinkage, nullptr, VarName);
// Then we load its value
Nodes[CNode] = IR->CreateLoad(Nodes[CNode]);
// At last we save the reference to the variable AstNode
this->VarsValue[VarName] = Nodes[CNode];
this->Vars[VarName] = CNode;
}
} break;
// Handle non-terminal nodes
case ast_e::BVADD_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVADD_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateAdd(LHS, RHS);
} break;
case ast_e::BVSUB_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSUB_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateSub(LHS, RHS);
} break;
case ast_e::BVXOR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVXOR_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateXor(LHS, RHS);
} break;
case ast_e::LAND_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "LAND_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateAnd(LHS, RHS);
// Convert it to be logical
auto TrueNode = ConstantInt::get(this->Context, APInt(1, 1));
Nodes[CNode] = IR->CreateICmpEQ(Nodes[CNode], TrueNode);
} break;
case ast_e::BVAND_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVAND_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateAnd(LHS, RHS);
} break;
case ast_e::LOR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "LOR_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateOr(LHS, RHS);
// Convert it to be logical
auto TrueNode = ConstantInt::get(this->Context, APInt(1, 1));
Nodes[CNode] = IR->CreateICmpEQ(Nodes[CNode], TrueNode);
} break;
case ast_e::BVOR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVOR_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateOr(LHS, RHS);
} break;
case ast_e::BVASHR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVASHR_NODE" << endl;
#endif
// Fetch the children
auto c0 = Children[0];
auto c1 = Children[1];
// Get the children and handle them first
auto LHS = Nodes[c0];
auto RHS = Nodes[c1];
// BEWARE: we should take into account the sign bit of the first operand
// https://llvm.org/docs/LangRef.html#ashr-instruction
if (c0->getBitvectorSize() <= 16 && c1->getBitvectorSize() <= 16) {
LHS = IR->CreateSExt(LHS, Type::getInt64Ty(this->Context));
RHS = IR->CreateSExt(RHS, Type::getInt64Ty(this->Context));
}
// Lift the current node
Nodes[CNode] = IR->CreateAShr(LHS, RHS);
// Truncate the result
if (c0->getBitvectorSize() <= 16 && c1->getBitvectorSize() <= 16) {
Nodes[CNode] = IR->CreateTrunc(Nodes[CNode], Type::getIntNTy(this->Context, CNode->getBitvectorSize()));
}
} break;
case ast_e::BVLSHR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVLSHR_NODE" << endl;
#endif
// Fetch the children
auto c0 = Children[0];
auto c1 = Children[1];
// Get the known children
auto LHS = Nodes[c0];
auto RHS = Nodes[c1];
// https://llvm.org/docs/LangRef.html#shl-instruction
if (c0->getBitvectorSize() <= 16 && c1->getBitvectorSize() <= 16) {
LHS = IR->CreateZExt(LHS, Type::getInt64Ty(this->Context));
RHS = IR->CreateZExt(RHS, Type::getInt64Ty(this->Context));
}
// Lift the current node
Nodes[CNode] = IR->CreateLShr(LHS, RHS);
// Trunc the final result to the expected size
if (c0->getBitvectorSize() <= 16 && c1->getBitvectorSize() <= 16) {
Nodes[CNode] = IR->CreateTrunc(Nodes[CNode], Type::getIntNTy(this->Context, CNode->getBitvectorSize()));
}
} break;
case ast_e::BVSHL_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSHL_NODE" << endl;
#endif
// Fetch the children
auto c0 = Children[0];
auto c1 = Children[1];
// Get the known children
auto LHS = Nodes[c0];
auto RHS = Nodes[c1];
// https://llvm.org/docs/LangRef.html#shl-instruction
if (c0->getBitvectorSize() <= 16 && c1->getBitvectorSize() <= 16) {
LHS = IR->CreateZExt(LHS, Type::getInt64Ty(this->Context));
RHS = IR->CreateZExt(RHS, Type::getInt64Ty(this->Context));
}
// Lift the current node
Nodes[CNode] = IR->CreateShl(LHS, RHS);
// Trunc the final result to the expected size
if (c0->getBitvectorSize() <= 16 && c1->getBitvectorSize() <= 16) {
Nodes[CNode] = IR->CreateTrunc(Nodes[CNode], Type::getIntNTy(this->Context, CNode->getBitvectorSize()));
}
} break;
case ast_e::BVMUL_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVMUL_NODE" << endl;
#endif
// Get the known children
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateMul(LHS, RHS);
} break;
case ast_e::BVNEG_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVNEG_NODE" << endl;
#endif
// Get the known child
auto LHS = Nodes[Children[0]];
// Lift the current node
Nodes[CNode] = IR->CreateNeg(LHS);
} break;
case ast_e::LNOT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "LNOT_NODE" << endl;
#endif
// Get the known child
auto LHS = Nodes[Children[0]];
// Lift the current node
Nodes[CNode] = IR->CreateNot(LHS);
// Convert it to be logical
auto TrueNode = ConstantInt::get(this->Context, APInt(1, 1));
Nodes[CNode] = IR->CreateICmpEQ(Nodes[CNode], TrueNode);
} break;
case ast_e::BVNOT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "LNOT_NODE|BVNOT_NODE" << endl;
#endif
// Get the known child
auto LHS = Nodes[Children[0]];
// Lift the current node
Nodes[CNode] = IR->CreateNot(LHS);
} break;
case ast_e::BVROL_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVROL_NODE" << endl;
#endif
// Get the bitvector to be rotated and the rotation
auto bv = Children[0];
auto rot = Children[1];
// Get the rotation decimal node
auto rotd = (IntegerNode*)(rot.get());
// Get the child and handle it first
auto rotv = GetDecimal(*rotd, bv->getBitvectorSize());
auto bvv = Nodes[bv];
// If the rotation value is 0, return the child
if (rotv->getLimitedValue() == 0) {
Nodes[CNode] = bvv;
} else {
// Size of the bitvector being rotated
uint64_t sz = bv->getBitvectorSize();
uint64_t rd = rotd->getInteger().convert_to<uint64_t>();
// Rotation value
auto rrot = ConstantInt::get(this->Context, APInt(sz, sz - rd));
// Emulate the right rotation
auto shl = IR->CreateShl(bvv, rotv);
auto shr = IR->CreateLShr(bvv, rrot);
Nodes[CNode] = IR->CreateXor(shl, shr);
}
} break;
case ast_e::BVROR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVROR_NODE" << endl;
#endif
// Get the bitvector to be rotated and the rotation
auto bv = Children[0];
auto rot = Children[1];
// Get the rotation decimal node
auto rotd = (IntegerNode*)(rot.get());
// Get the child and handle it first
auto rotv = GetDecimal(*rotd, bv->getBitvectorSize());
auto bvv = Nodes[bv];
// If the rotation value is 0, return the child
if (rotv->getLimitedValue() == 0) {
Nodes[CNode] = bvv;
} else {
// Size of the bitvector being rotated
uint64_t sz = bv->getBitvectorSize();
uint64_t rd = rotd->getInteger().convert_to<uint64_t>();
// Rotation value
auto rrot = ConstantInt::get(this->Context, APInt(sz, sz - rd));
// Emulate the right rotation
auto shl = IR->CreateShl(bvv, rrot);
auto shr = IR->CreateLShr(bvv, rotv);
Nodes[CNode] = IR->CreateXor(shl, shr);
}
} break;
case ast_e::ZX_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "ZX_NODE" << endl;
#endif
// Get the child
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateZExt(RHS, IntegerType::get(this->Context, CNode->getBitvectorSize()));
} break;
case ast_e::SX_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "SX_NODE" << endl;
#endif
// Get the child
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateSExt(RHS, IntegerType::get(this->Context, CNode->getBitvectorSize()));
} break;
case ast_e::EXTRACT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "EXTRACT_NODE" << endl;
#endif
// Get the children
auto c0 = Children[0];
auto c1 = Children[1];
auto c2 = Children[2];
// Get the decimal values
auto c0d = (IntegerNode*)(c0.get());
auto c1d = (IntegerNode*)(c1.get());
// Determine the extraction size
auto sz = 1 + c0d->getInteger().convert_to<uint64_t>() - c1d->getInteger().convert_to<uint64_t>();
// Get the high and low indexes
auto lo = GetDecimal(*c1d, c2->getBitvectorSize());
// Get the value to extract from
auto bv = Nodes[c2];
// Proceed with the extraction
Nodes[CNode] = IR->CreateLShr(bv, lo);
Nodes[CNode] = IR->CreateTrunc(Nodes[CNode], IntegerType::get(this->Context, sz));
} break;
case ast_e::CONCAT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "CONCAT_NODE" << endl;
#endif
// Get the final concatenation size
auto sz = CNode->getBitvectorSize();
// Get the children
auto children = Children;
// Get the last node and extend it to the full size
Nodes[CNode] = Nodes[children.back()];
Nodes[CNode] = IR->CreateZExt(Nodes[CNode], IntegerType::get(this->Context, sz));
// Determine the initial shift value
uint64_t shift = children.back()->getBitvectorSize();
// Remove the last child from the children
children.pop_back();
// Concatenate all the other children
for (uint64_t i = children.size(); i-- > 0;) {
// Get the current child
auto child = children[i];
// Get the current child instruction
auto curr = Nodes[child];
// Zero extend the value to the full size
curr = IR->CreateZExt(curr, IntegerType::get(this->Context, sz));
// Shift it left
curr = IR->CreateShl(curr, shift);
// Concatenate it
Nodes[CNode] = IR->CreateOr(Nodes[CNode], curr);
// Get the current shift value
shift += child->getBitvectorSize();
}
} break;
case ast_e::BVSDIV_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSDIV_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateSDiv(LHS, RHS);
} break;
case ast_e::BVUDIV_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVUDIV_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateUDiv(LHS, RHS);
} break;
case ast_e::BVSMOD_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSMOD_NODE" << endl;
#endif
// BEWARE: Proper emulation of SMOD is necessary here
// https://llvm.org/docs/LangRef.html#srem-instruction
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
auto srem = IR->CreateSRem(LHS, RHS);
auto add = IR->CreateAdd(srem, RHS);
Nodes[CNode] = IR->CreateSRem(add, RHS);
} break;
case ast_e::BVSREM_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSREM_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateSRem(LHS, RHS);
} break;
case ast_e::BVUREM_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVUREM_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateURem(LHS, RHS);
} break;
case ast_e::ITE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "ITE_NODE" << endl;
#endif
// Get the 'if' node
auto _if = Nodes[Children[0]];
// Get the 'then' node
auto _then = Nodes[Children[1]];
// Get the 'else' node
auto _else = Nodes[Children[2]];
// Lift the 'ite' ast to a 'select'
Nodes[CNode] = IR->CreateSelect(_if, _then, _else);
} break;
case ast_e::EQUAL_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "EQUAL_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'equal' ast to a 'icmp eq'
Nodes[CNode] = IR->CreateICmpEQ(e0, e1);
} break;
case ast_e::DISTINCT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "DISTINCT_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'equal' ast to a 'icmp eq'
Nodes[CNode] = IR->CreateICmpNE(e0, e1);
} break;
case ast_e::BVSGE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSGE_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpSGE(e0, e1);
} break;
case ast_e::BVSGT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSGT_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpSGT(e0, e1);
} break;
case ast_e::BVSLE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSLE_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpSLE(e0, e1);
} break;
case ast_e::BVSLT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVSLT_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpSLT(e0, e1);
} break;
case ast_e::BVUGE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVUGE_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpUGE(e0, e1);
} break;
case ast_e::BVUGT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVUGT_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpUGT(e0, e1);
} break;
case ast_e::BVULE_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVULE_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpULE(e0, e1);
} break;
case ast_e::BVULT_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVULT_NODE" << endl;
#endif
// Get the 2 expressions
auto e0 = Nodes[Children[0]];
auto e1 = Nodes[Children[1]];
// Lift the 'sge' ast to a 'icmp sge'
Nodes[CNode] = IR->CreateICmpULT(e0, e1);
} break;
case ast_e::BVNAND_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVNAND_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateAnd(LHS, RHS);
Nodes[CNode] = IR->CreateNot(Nodes[CNode]);
} break;
case ast_e::BVNOR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVNOR_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateOr(LHS, RHS);
Nodes[CNode] = IR->CreateNot(Nodes[CNode]);
} break;
case ast_e::BVXNOR_NODE: {
#ifdef VERBOSE_OUTPUT
cout << "BVXNOR_NODE" << endl;
#endif
// Get the children and handle them first
auto LHS = Nodes[Children[0]];
auto RHS = Nodes[Children[1]];
// Lift the current node
Nodes[CNode] = IR->CreateXor(LHS, RHS);
Nodes[CNode] = IR->CreateNot(Nodes[CNode]);
} break;
default: {
// Notify we don't support these nodes
// COMPOUND, DECLARE, INVALID,
// ASSERT, STRING, IFF, LEFT
report_fatal_error("LiftNodesWBS: unsupported node found.");
} break;
}
// Check if we found an unresolved reference
if (!UnresolvedReference) {
// Print the translated node
#ifdef VERBOSE_OUTPUT
if (Nodes[CNode]) {
Nodes[CNode]->print(llvm::errs(), false);
}
#endif
// Check the counter of the shared pointers
Curr->Expression.reset();
Curr->Module.reset();
Curr->Nodes.clear();
Curr->Node.reset();
Curr->IR = nullptr;
// Get the parent
Curr = Curr->Parent;
}
}
}
// Return the final node
return Nodes[TopNode];
}
/*
Function to apply the LLVM optimizations to an LLVM-IR Module.
*/
void Translator::OptimizeModule(llvm::Module* M) {
auto PassManager = llvm::legacy::PassManager();
PassManagerBuilder Builder;
Builder.OptLevel = 3;
Builder.SizeLevel = 2;
Builder.Inliner = createAlwaysInlinerLegacyPass();
Builder.populateModulePassManager(PassManager);
PassManager.run(*M);
// Remove all the functions except for TritonAstFunction
vector<Function*> ToBeRemoved;
for (auto& F : M->functions()) {
if (F.getName().startswith("ref")) {
ToBeRemoved.push_back(&F);
}
}
for (auto& F : ToBeRemoved) {
F->eraseFromParent();
}
// Strip the weird names
auto* MF = M->getFunction("TritonAstFunction");
for (inst_iterator I = inst_begin(MF), E = inst_end(MF); I != E; I++) {
if (I->hasName()) I->setName("");
}
}
/*
Function to clone a source LLVM-IR Function inside a destination LLVM-IR Function.
*/
void Translator::CloneFunctionInto(Function* SrcFunc, Function* DstFunc) const {
// Map the new arguments to the old arguments
auto NewArgs = DstFunc->arg_begin();
ValueMap<const Value*, WeakTrackingVH> ArgsMap;
for (auto& OldArg : SrcFunc->args()) {
NewArgs->setName(OldArg.getName());
ArgsMap[&OldArg] = &*NewArgs;
NewArgs++;
}
// Clone the source function into the destination function
SmallVector<ReturnInst*, 8> Returns;
llvm::CloneFunctionInto(DstFunc, SrcFunc, ArgsMap, false, Returns);
}
/*
Public function to execute the Triton AST to LLVM-IR Module translation.
*/
shared_ptr<Module> Translator::TritonAstToLLVMIR(const SharedAbstractNode& node, map<ExpKey, shared_ptr<llvm::Module>>& cache, ssize_t MaxDepth) {
// Allocate a new Module (the old one is deallocated only if not referenced anymore)
this->Module = make_shared<llvm::Module>("TritonAstModule", this->Context);
if (Module == nullptr) {
report_fatal_error("TritonAstToLLVMIR: failed to allocate Module");
}
// Create the function type (consistent with the top node type)
auto* TritonAstType = FunctionType::get(IntegerType::get(this->Context, node->getBitvectorSize()), false);
// Create the function (which will contain the basic block)
auto* TritonAstFunction = Function::Create(TritonAstType, llvm::Function::CommonLinkage, "TritonAstFunction", this->Module.get());
// Mark the function as always inlineable
TritonAstFunction->addFnAttr(Attribute::AlwaysInline);
// Create the only basic block (which will contain the lifted instructions)
auto* TritonAstBlock = BasicBlock::Create(this->Context, "TritonAstEntry", TritonAstFunction);
// Clear the old variable Value(s)
this->VarsValue.clear();
this->Vars.clear();
// Map for the AST nodes
map<SharedAbstractNode, Value*> nodes;
// Initialize the IRBuilder to lift the nodes
shared_ptr<IRBuilder<>> IR = make_shared<IRBuilder<>>(TritonAstBlock);
// Traverse the AST in a WBS way (and lift the AST nodes)
auto* Value = this->LiftNodesWBS(node, IR, cache, MaxDepth);
// Add the return statement
IR->CreateRet(Value);
#ifdef DEBUG_OUTPUT
// DEBUG: show the original ast
cout << "\nOriginal Triton AST: " << node << endl;
// DEBUG: dump the Module
cout << "\nLifted Triton AST" << endl;
#endif
// Dumping the unoptimized function
cout << "\n> Unoptimized LLVM-IR Module\n" << endl;
this->Module->print(llvm::errs(), nullptr);
// Optimize with LLVM
this->OptimizeModule(this->Module.get());
// DEBUG: dump the optimized Module
#ifdef DEBUG_OUTPUT
cout << "\nOptimized Lifted Triton AST" << endl;
Module->print(llvm::errs(), false);
#endif
// Return the generated Module
return Module;
}
/*
Converting a LLVM-IR basic block to a Triton AST.
*/
SharedAbstractNode Translator::LiftInstructionsDFS(Value* value, map<Value*, SharedAbstractNode>& values, map<string, SharedAbstractNode>& variables) {
// DEBUG: show input value
#ifdef VERBOSE_OUTPUT
cout << "Input value: " << endl;
cout << "------------" << endl;
value->print(llvm::errs(), false);
cout << "------------" << endl;
#endif
// Check if we already lifted this value