-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLLVMParser.cpp
2393 lines (2023 loc) · 69.6 KB
/
LLVMParser.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 "LLVMParser.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TargetParser/Triple.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Threading.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Evaluator.h"
// add new pass manager builder
#include "llvm/IR/PassManager.h"
#include "llvm/Passes/PassBuilder.h"
#include <cmath>
#include <memory>
#include <stack>
#include <string>
#include <thread>
#include <llvm/IR/ConstantFold.h>
#include <vector>
#include <z3++.h>
#include "CSiMBA.h"
#include "Modulo.h"
#include "ShuttingYard.h"
#include "Simplifier.h"
#include "Z3Prover.h"
// #define DEBUG_SIMPLIFICATION
using namespace llvm;
using namespace std;
using namespace std::chrono;
llvm::cl::opt<std::string>
UseExternalSimplifier("external-simplifier", cl::Optional,
cl::desc("Path to external simplifier script for "
"simplification (Supports: SiMBA/GAMBA"),
cl::value_desc("external-simplifier"), cl::init(""));
llvm::cl::opt<int>
MaxVarCount("max-var-count", cl::Optional,
cl::desc("Max variable count for simplification"),
cl::value_desc("max-var-count"), cl::init(6));
llvm::cl::opt<int> MinASTSize("min-ast-size", cl::Optional,
cl::desc("Minimum AST size for simplification"),
cl::value_desc("min-ast-size"), cl::init(4));
llvm::cl::opt<bool>
ShouldWalkSubAST("walk-sub-ast", cl::Optional,
cl::desc("Walk sub AST if full AST to not match"),
cl::value_desc("walk-sub-ast"), cl::init(false));
namespace LSiMBA {
llvm::LLVMContext LLVMParser::Context;
LLVMParser::LLVMParser(const std::string &filename,
const std::string &OutputFile, bool Parallel,
bool Verify, bool OptimizeBefore, bool OptimizeAfter,
bool Debug, bool Prove)
: OutputFile(OutputFile), Parallel(Parallel), Verify(Verify),
OptimizeBefore(OptimizeBefore), OptimizeAfter(OptimizeAfter),
Debug(Debug), Prove(Prove), SP64(filename.length()), TLII(nullptr),
TLI(nullptr), M(nullptr), F(nullptr) {
if (!this->parse(filename)) {
llvm::errs() << "[!] Error: Could not parse file " << filename << "\n";
return;
}
// Create evaluator
this->TLII = new TargetLibraryInfoImpl(Triple(M->getTargetTriple()));
this->TLI = std::make_unique<TargetLibraryInfo>(*TLII);
this->Eval = std::make_unique<Evaluator>(M->getDataLayout(), TLI.get());
this->MaxThreadCount = thread::hardware_concurrency();
this->IsExternalSimplifier = !UseExternalSimplifier.empty();
}
LLVMParser::LLVMParser(llvm::Module *M, bool Parallel, bool Verify,
bool OptimizeBefore, bool OptimizeAfter, bool Debug,
bool Prove)
: M(M), F(nullptr), Parallel(Parallel), Verify(Verify),
OptimizeBefore(OptimizeBefore), OptimizeAfter(OptimizeAfter),
Debug(Debug), Prove(Prove), SP64((uint64_t)M), TLII(nullptr),
TLI(nullptr) {
// Create evaluator
this->TLII = new TargetLibraryInfoImpl(Triple(M->getTargetTriple()));
this->TLI = std::make_unique<TargetLibraryInfo>(*TLII);
this->Eval = std::make_unique<Evaluator>(M->getDataLayout(), TLI.get());
this->MaxThreadCount = thread::hardware_concurrency();
this->IsExternalSimplifier = !UseExternalSimplifier.empty();
}
LLVMParser::LLVMParser(llvm::Function *F, bool Parallel, bool Verify,
bool OptimizeBefore, bool OptimizeAfter, bool Debug,
bool Prove)
: M(F->getParent()), F(F), Parallel(Parallel), Verify(Verify),
OptimizeBefore(OptimizeBefore), OptimizeAfter(OptimizeAfter),
Debug(Debug), Prove(Prove), SP64((uint64_t)M), TLII(nullptr),
TLI(nullptr) {
// Create evaluator
this->TLII = new TargetLibraryInfoImpl(Triple(M->getTargetTriple()));
this->TLI = std::make_unique<TargetLibraryInfo>(*TLII);
this->Eval = std::make_unique<Evaluator>(M->getDataLayout(), TLI.get());
this->MaxThreadCount = thread::hardware_concurrency();
this->IsExternalSimplifier = !UseExternalSimplifier.empty();
// Disable instruction count as it has a big performance impact
this->CountInstructions = false;
}
LLVMParser::~LLVMParser() {}
int LLVMParser::simplify() {
// Simplify MBAs
auto Count = this->extractAndSimplify();
if (this->CountInstructions) {
this->InstructionCountAfter = getInstructionCount(M);
}
writeModule();
return Count;
}
int LLVMParser::simplifyMBAFunctionsOnly() {
int Count = this->simplifyMBAModule();
writeModule();
return Count;
}
void LLVMParser::writeModule() {
if (this->OutputFile.empty())
return;
std::error_code EC;
llvm::raw_fd_ostream OS(this->OutputFile, EC, llvm::sys::fs::OF_None);
if (EC) {
outs() << "[!] Could not open file: '" << this->OutputFile << "'\n";
return;
}
OS << *this->M;
OS.close();
outs() << "[+] Wrote LLVM Module to: '" << this->OutputFile << "'\n";
}
llvm::LLVMContext &LLVMParser::getLLVMContext() { return LLVMParser::Context; };
bool LLVMParser::hasLoadStores(llvm::Function &F) {
for (auto &BB : F) {
for (auto &I : BB) {
if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
return true;
}
}
}
return false;
}
void LLVMParser::initResultVector(llvm::Function &F,
std::vector<llvm::APInt> &ResultVector,
const llvm::APInt &Modulus, int VNumber,
llvm::Type *IntType) {
auto RetVal = ConstantInt::get(IntType, 0);
llvm::SmallVector<Constant *, 32> par;
for (int i = 0; i < pow(2, VNumber); i++) {
int n = i;
for (int j = 0; j < VNumber; j++) {
auto C = ConstantInt::get(IntType, n & 1);
par.push_back(C);
n = n >> 1;
}
// Evaluate function
auto R = Eval->EvaluateFunction(&F, RetVal, par);
// Get Result and store in result vector
auto CIRetVal = dyn_cast<ConstantInt>(RetVal);
APInt v = dyn_cast<ConstantInt>(CIRetVal)->getValue();
auto OldBitWidth = v.getBitWidth();
if (v.isSignBitSet()) {
// v = v.srem(Modulus);
v = v.sextOrTrunc(Modulus.getBitWidth()).srem(Modulus).trunc(OldBitWidth);
} else {
// v = v.urem(Modulus);
v = v.sextOrTrunc(Modulus.getBitWidth()).urem(Modulus).trunc(OldBitWidth);
}
// Store value mod modulus
ResultVector.push_back(v);
par.clear();
}
return;
}
llvm::Instruction *LLVMParser::getSingleTerminator(llvm::Function &F) {
// Collect all terminators
std::vector<llvm::Instruction *> Terminators;
for (auto &BB : F) {
Terminators.push_back(dyn_cast<Instruction>(BB.getTerminator()));
}
// Only allow 1 Terminator
if (Terminators.size() != 1) {
std::string ErrMsg = "[!] Error: More than 1 Terminator in function " +
F.getName().str() + "\n";
llvm::report_fatal_error(ErrMsg.c_str());
}
return Terminators.front();
}
bool LLVMParser::parse(const std::string &filename) {
SMDiagnostic Err;
M = llvm::parseIRFile(filename, Err, Context).release();
if (!M) {
llvm::report_fatal_error("[!] Could not read llvm ir file!", false);
}
if (this->CountInstructions) {
this->InstructionCountBefore = getInstructionCount(M);
}
return true;
}
int LLVMParser::extractAndSimplify() {
int MBASimplified = 0;
// Collect all functions
std::vector<llvm::Function *> Functions;
for (auto &F : *M) {
// If F set only work on F
if (this->F && (&F != this->F)) {
continue;
}
if (F.isDeclaration()) {
continue;
}
// Skip simplifed functions
if (F.getName().starts_with("MBA_Simp")) {
continue;
}
Functions.push_back(&F);
}
// Walk through all functions
if (this->Debug) {
outs() << "[+] Simplifying " << Functions.size() << " function(s) ...\n";
}
auto start = high_resolution_clock::now();
for (auto F : Functions) {
if (F->isDeclaration())
continue;
if (F->getName().contains("_keep")) {
if (this->Debug) {
outs() << "[!] Skipping simplification of function: " << F->getName()
<< "\n";
}
continue;
}
if (this->Debug) {
outs() << "[*] Simplifying function: " << F->getName() << "\n";
}
// Optimize before if asked for
if (this->OptimizeBefore) {
optimizeFunction(*F);
}
int MBACount = 0;
bool Found = false;
DominatorTree DT(*F);
// Measure Time
auto start = high_resolution_clock::now();
// Get candidates
std::vector<MBACandidate> Candidates;
this->extractCandidates(*F, Candidates);
// Find valid replacements for candidates
Found = this->findReplacements(&DT, Candidates);
// Apply replacements and optimize
bool Replaced = false;
for (int i = 0; i < Candidates.size(); i++) {
if (Candidates[i].isValid == false)
continue;
if (this->Debug) {
printAST(Candidates[i].AST);
if (this->Debug) {
outs() << "[!] Simplification: '" << Candidates[i].Replacement
<< " with " << countOperators(Candidates[i].Replacement)
<< " operators!\n";
}
}
std::vector<std::string> VNames;
char ArgName = 'a';
for (int j = 0; j < Candidates[i].Variables.size(); j++) {
VNames.push_back(std::string(1, ArgName++));
}
createLLVMReplacement(
Candidates[i].Candidate, Candidates[i].Candidate->getType(),
Candidates[i].Replacement, VNames, Candidates[i].Variables);
MBASimplified++;
MBACount++;
Replaced = true;
}
// Optimize if any replacements
if (Replaced && this->OptimizeAfter) {
optimizeFunction(*F);
}
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
if (this->Debug) {
outs() << "[+] Done! " << MBASimplified << " MBAs simplified ("
<< duration.count() << " ms)\n";
}
return MBASimplified;
}
int LLVMParser::simplifyMBAModule() {
// Collect all functions
std::vector<llvm::Function *> Functions;
for (auto &F : *M) {
if (this->F && (&F != this->F))
continue;
// Skip simplifed functions
if (F.getName().starts_with("MBA_Simp"))
continue;
// Check if any load/stores are in the function
if (hasLoadStores(F))
report_fatal_error("[!] Error: Function contains load/stores!");
Functions.push_back(&F);
}
// Walk through all functions
outs() << "[+] Simplifying " << Functions.size() << " functions ...\t";
auto start = high_resolution_clock::now();
for (auto F : Functions) {
// Optimize before if asked for
if (this->OptimizeBefore) {
optimizeFunction(*F);
}
// Get the terminator
auto Terminator = getSingleTerminator(*F);
int BitWidth = Terminator->getOperand(0)->getType()->getIntegerBitWidth();
auto Modulus = getModulus(BitWidth);
// Collect the arguments
std::vector<std::string> VNames;
SmallVector<llvm::Value *, 8> Variables;
char ArgName = 'a';
for (auto &Arg : F->args()) {
Variables.push_back(&Arg);
VNames.push_back(std::string(1, ArgName++));
}
auto RetTy = Terminator->getOperand(0)->getType();
auto VNumber = Variables.size();
// Calc the result vector
std::vector<APInt> ResultVector;
this->initResultVector(*F, ResultVector, Modulus, VNumber, RetTy);
// Simpify MBA
Simplifier S(BitWidth, false, VNumber, ResultVector);
std::string SimpExpr;
S.simplify(SimpExpr, false, false);
// Convert simplified expression to LLVM IR
auto FSimp =
createLLVMFunction(this->M, Variables, SimpExpr, VNames, RetTy);
// Verify if simplification is valid
if (this->Verify && !this->verify(F, FSimp, Modulus)) {
outs() << "[!] Error: Simplification is not valid for function "
<< F->getName() << "\n";
}
// Debug out
if (this->Debug) {
outs() << "\n[*] Simplified Expression: " << SimpExpr << "\n";
}
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
outs() << "Done! (" << duration.count() << " ms)\n";
return Functions.size();
}
bool LLVMParser::verify(llvm::Function *F0, llvm::Function *F1,
llvm::APInt &Modulus) {
// Check functions have the same amount of arguments
if (F0->arg_size() != F1->arg_size()) {
return false;
}
// Check if types are the sames
if (F0->getReturnType() != F1->getReturnType()) {
return false;
}
// Check if argument types are the same
if (F0->arg_size() != F1->arg_size()) {
return false;
}
for (int i = 0; i < F0->arg_size(); i++) {
if (F0->getArg(i)->getType() != F1->getArg(i)->getType()) {
return false;
}
}
auto RetTy = F0->getReturnType();
auto RetVal0 = ConstantInt::get(RetTy, 0);
auto RetVal1 = ConstantInt::get(RetTy, 0);
auto vnumber = F0->arg_size();
llvm::SmallVector<Constant *, 16> par;
for (int i = 0; i < NUM_TEST_CASES; i++) {
for (int j = 0; j < vnumber; j++) {
auto C = ConstantInt::get(RetTy, SP64.next());
par.push_back(C);
}
Eval->EvaluateFunction(F0, RetVal0, par);
Eval->EvaluateFunction(F1, RetVal1, par);
auto R0 = dyn_cast<ConstantInt>(RetVal0)
->getValue()
.zextOrTrunc(Modulus.getBitWidth())
.urem(Modulus)
.getLimitedValue();
auto R1 = dyn_cast<ConstantInt>(RetVal1)
->getValue()
.zextOrTrunc(Modulus.getBitWidth())
.urem(Modulus)
.getLimitedValue();
if (R0 != R1) {
return false;
}
par.clear();
}
return true;
}
bool LLVMParser::verify(int ASTSize, llvm::SmallVectorImpl<BFSEntry> &AST,
std::string &SimpExpr,
llvm::SmallVectorImpl<llvm::Value *> &Variables) {
int VNumber = Variables.size();
int BitWidth = AST.front().I->getType()->getIntegerBitWidth();
auto Modulus = getModulus(BitWidth);
std::string Expr1_replVar = SimpExpr;
for (int i = 0; i < Variables.size(); i++) {
char Var = 'a' + i;
string StrVar(1, Var);
Simplifier::replaceAllStrings(Expr1_replVar, StrVar,
"X[" + std::to_string(i) + "]");
}
// The number of operations in the new expressions
int Operations = 0;
llvm::SmallVector<APInt, 16> par;
for (int i = 0; i < NUM_TEST_CASES; i++) {
for (int j = 0; j < VNumber; j++) {
auto v = SP64.next();
par.push_back(APInt(BitWidth, v));
}
// Eval AST
bool Error = false;
auto AP_R0 = this->evaluateAST(AST, Variables, par, Error);
if (Error) {
#ifdef DEBUG_SIMPLIFICATION
outs() << "[!] Error: Evaluation failed for: " << SimpExpr << "\n";
#endif
return false;
}
// Eval replacement
auto AP_R1 = eval(Expr1_replVar, par, BitWidth, &Operations);
// Check if replacement is cheaper than original expression
if (ASTSize <= Operations) {
#ifdef DEBUG_SIMPLIFICATION
outs() << "[!] Simplification is no improvement: AST: " << ASTSize
<< " Operations: " << Operations << "\n";
#endif
return false;
}
if (AP_R0 != AP_R1) {
#ifdef DEBUG_SIMPLIFICATION
outs() << "[!] Error: Verification failed for: " << SimpExpr << "\n";
#endif
return false;
}
par.clear();
}
// Prove with z3
if (this->Prove) {
z3::context Z3Ctx;
// Build Variable replacements
std::vector<std::string> Vars;
std::map<std::string, llvm::Type *> VarTypes;
for (int i = 0; i < Variables.size(); i++) {
char c = 'a' + i;
string strC = string(1, c);
Vars.push_back(strC);
VarTypes[strC] = Variables[i]->getType();
}
if (this->Debug) {
outs() << "[Z3] Proving ...\n";
}
// New way: opt(Exp0 - Exp1) != 0
OPTSTATUS Proved;
auto Z3ExpOpt =
getOptimizedZ3Expression(Z3Ctx, SimpExpr, Vars, AST, Variables, Proved);
// Prove expressions
auto start = high_resolution_clock::now();
bool Result = false;
if (Proved == OPT_PROVED) {
// Solved by optimization
Result = 1;
} else if (Proved == OPT_NOT_VALID) {
// Solved by optimization
Result = 0;
} else if (OPT_PROVE_ME) {
// Solve with Z3
Result = prove((Z3ExpOpt != 0));
}
auto stop = high_resolution_clock::now();
if (this->Debug) {
auto duration = duration_cast<milliseconds>(stop - start);
outs() << "[Z3] Proved in " << duration.count()
<< " ms Result (1 == valid): " << Result << "\n";
}
return Result;
}
// Otherwise don't apply this replacement
return true;
}
bool LLVMParser::isSupportedInstruction(llvm::Value *V) {
// We dont support AShr as GAMBA does not support it, for now
if (auto BO = dyn_cast<BinaryOperator>(V)) {
// Got removed from constant expr
if (BO->getOpcode() == Instruction::Shl ||
BO->getOpcode() == Instruction::Or ||
BO->getOpcode() == Instruction::And ||
BO->getOpcode() == Instruction::LShr ||
BO->getOpcode() == Instruction::AShr) {
return true;
}
return ConstantExpr::isSupportedBinOp(BO->getOpcode());
}
if (isa<TruncInst>(V)) {
return true;
}
if (isa<ZExtInst>(V)) {
return true;
}
if (isa<SExtInst>(V)) {
return true;
}
if (isa<SelectInst>(V)) {
if (IsExternalSimplifier)
return false;
return true;
}
if (isa<ICmpInst>(V)) {
if (IsExternalSimplifier)
return false;
// Check if operands are pointer type
auto IC = dyn_cast<ICmpInst>(V);
if (IC->getOperand(0)->getType()->isPointerTy() ||
IC->getOperand(1)->getType()->isPointerTy()) {
return false;
}
return true;
}
if (isa<CallInst>(V)) {
// check if intrinsic
auto CI = dyn_cast<CallInst>(V);
auto Intr = CI->getIntrinsicID();
switch (Intr) {
case 0: {
// Not an intrinsic
return false;
}
case Intrinsic::fshl:
case Intrinsic::ctpop:
case Intrinsic::bswap:
case Intrinsic::umax:
case Intrinsic::umin:
case Intrinsic::abs:
case Intrinsic::smin:
case Intrinsic::smax:
case Intrinsic::bitreverse: {
return true;
}
default: {
outs() << "[!] Unsupported intrinsic: " << "\n";
CI->dump();
// report_fatal_error("Unsupported intrinsic");
return false;
}
}
}
return false;
}
void LLVMParser::extractCandidates(llvm::Function &F,
std::vector<MBACandidate> &Candidates) {
std::set<llvm::Value *> Visited;
auto isVisited = [&](llvm::Value *I) -> bool {
return Visited.find(I) != Visited.end();
};
// Instruction to look for 'store', 'select', 'gep', 'icmp', 'ret'
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
// Check if integer type
if (!I->getType()->isIntegerTy()) {
continue;
}
switch (I->getOpcode()) {
case Instruction::Store: {
// Check Candidate
auto SI = dyn_cast<StoreInst>(&*I);
auto Op = SI->getValueOperand();
if (!isVisited(Op) && isSupportedInstruction(Op)) {
MBACandidate Cand;
Cand.Candidate = dyn_cast<Instruction>(Op);
Candidates.push_back(Cand);
Visited.insert(Op);
}
} break;
case Instruction::GetElementPtr: {
auto GEP = dyn_cast<GetElementPtrInst>(&*I);
auto Index = GEP->getOperand(GEP->getNumOperands() - 1);
if (isSupportedInstruction(Index->stripPointerCasts())) {
if (isVisited(Index->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate = dyn_cast<Instruction>(Index->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(Index->stripPointerCasts());
}
} break;
case Instruction::ICmp: {
if (IsExternalSimplifier)
continue;
for (unsigned int i = 0; i < I->getNumOperands(); i++) {
if (isSupportedInstruction(I->getOperand(i)->stripPointerCasts())) {
if (isVisited(I->getOperand(i)->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate =
dyn_cast<Instruction>(I->getOperand(i)->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(I->getOperand(i)->stripPointerCasts());
}
}
} break;
case Instruction::Ret: {
auto RI = dyn_cast<ReturnInst>(&*I);
if (!RI->getReturnValue())
continue;
if (isSupportedInstruction(RI->getReturnValue()->stripPointerCasts())) {
if (isVisited(RI->getReturnValue()->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate =
dyn_cast<Instruction>(RI->getReturnValue()->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(RI->getReturnValue()->stripPointerCasts());
}
} break;
case Instruction::Call: {
auto CI = dyn_cast<CallInst>(&*I);
for (unsigned int i = 0; i < CI->arg_size(); i++) {
if (isSupportedInstruction(CI->getArgOperand(i)->stripPointerCasts())) {
if (isVisited(CI->getArgOperand(i)->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate =
dyn_cast<Instruction>(CI->getArgOperand(i)->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(CI->getArgOperand(i)->stripPointerCasts());
}
}
} break;
case Instruction::Select: {
// Add Instruction
auto SI = dyn_cast<SelectInst>(&*I);
if (!isVisited(SI)) {
MBACandidate Cand;
Cand.Candidate = dyn_cast<Instruction>(SI);
Candidates.push_back(Cand);
Visited.insert(SI);
}
// Add Condition
if (isSupportedInstruction(SI->getCondition()->stripPointerCasts())) {
if (isVisited(SI->getCondition()->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate =
dyn_cast<Instruction>(SI->getCondition()->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(SI->getCondition()->stripPointerCasts());
}
// Add Operands
for (unsigned int i = 0; i < I->getNumOperands(); i++) {
if (isSupportedInstruction(I->getOperand(i)->stripPointerCasts())) {
if (isVisited(I->getOperand(i)->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate =
dyn_cast<Instruction>(I->getOperand(i)->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(I->getOperand(i)->stripPointerCasts());
}
}
} break;
case Instruction::PHI: {
auto Phi = dyn_cast<PHINode>(&*I);
for (auto &Inc : Phi->incoming_values()) {
if (isSupportedInstruction(Inc->stripPointerCasts())) {
if (isVisited(Inc->stripPointerCasts()))
continue;
MBACandidate Cand;
Cand.Candidate = dyn_cast<Instruction>(Inc->stripPointerCasts());
Candidates.push_back(Cand);
Visited.insert(Inc->stripPointerCasts());
}
}
} break;
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::Shl:
case Instruction::Xor:
case Instruction::Trunc:
case Instruction::Or:
case Instruction::And:
case Instruction::URem:
case Instruction::SRem:
case Instruction::IntToPtr:
case Instruction::BitCast: {
if (isVisited(&*I))
continue;
MBACandidate Cand;
Cand.Candidate = dyn_cast<Instruction>(&*I);
Candidates.push_back(Cand);
Visited.insert(&*I);
} break;
case Instruction::LShr:
case Instruction::AShr: {
if (IsExternalSimplifier || isVisited(&*I))
continue;
MBACandidate Cand;
Cand.Candidate = dyn_cast<Instruction>(&*I);
Candidates.push_back(Cand);
Visited.insert(&*I);
} break;
default: {
}
}
}
#ifdef DEBUG_SIMPLIFICATION
outs() << "[*] Found " << Candidates.size()
<< " candidates Duplicates: " << (Visited.size() - Candidates.size())
<< "\n";
#endif
}
bool LLVMParser::constainsReplacedInstructions(
SmallPtrSet<llvm::Instruction *, 16> &ReplacedInstructions,
MBACandidate &Cand) {
for (auto &E : Cand.AST) {
if (ReplacedInstructions.find(E.I) != ReplacedInstructions.end()) {
return true;
}
}
return false;
}
bool LLVMParser::replaceWithKnownPatterns(
LSiMBA::MBACandidate &Cand, const std::vector<APInt> &ResultVector) {
#ifdef DEBUG_SIMPLIFICATION
for (auto V : ResultVector) {
outs() << V << "\n";
}
#endif
if (Cand.Variables.size() == 1 && ResultVector[0].getSExtValue() == 1 &&
ResultVector[1] == 0) {
Cand.Replacement = "!a";
return true;
}
return false;
}
bool LLVMParser::findReplacements(llvm::DominatorTree *DT,
std::vector<MBACandidate> &Candidates) {
if (Candidates.empty()) {
return false;
}
bool ReplacementFound = false;
#ifdef DEBUG_SIMPLIFICATION
// Debug out
// Candidates.front().Candidate->getFunction()->print(outs());
#endif
// Search for replacements
std::vector<MBACandidate> SubASTCandidates;
auto StartTime = high_resolution_clock::now();
for (int i = 0; i < Candidates.size(); i++) {
auto &Cand = Candidates[i];
getAST(DT, Cand.Candidate, Cand.AST, Cand.Variables, true);
Cand.ASTSize = getASTSize(Cand.AST);
}
auto EndTime = high_resolution_clock::now();
auto Duration = duration_cast<milliseconds>(EndTime - StartTime);
#ifdef DEBUG_SIMPLIFICATION
outs() << "[*] Extracted ASTs in " << Duration.count() << " ms\n";
#endif
// Sort Candidates by AST size
std::sort(Candidates.begin(), Candidates.end(),
[](const MBACandidate &A, const MBACandidate &B) {
return A.AST.size() > B.AST.size();
});
// To not solve things twice we keep track of replaced instructions
llvm::SmallPtrSet<llvm::Instruction *, 16> ReplacedInstructions;
for (int i = 0; i < Candidates.size(); i++) {
auto &Cand = Candidates[i];
if (Cand.ASTSize < MinASTSize) {
continue;
}
#ifdef DEBUG_SIMPLIFICATION
// Debug out
printAST(Cand.AST);
// Debug print variables
outs() << "[*] Variables:\n";
for (auto Var : Cand.Variables) {
Var->print(outs());
outs() << "\n";
}
#endif
// Only handle max xx Vars
if (Cand.Variables.size() > MaxVarCount) {
#ifdef DEBUG_SIMPLIFICATION
outs() << "[*] Skipping too many variables: " << Cand.Variables.size()
<< "\n";
#endif
Cand.isValid = false;
continue;
}
// Dont work on vector types
if (Cand.AST.front().I->getType()->isVectorTy()) {
Cand.isValid = false;
continue;
}
// Skip Ptr types
if (Cand.AST.front().I->getType()->isPointerTy()) {
Cand.isValid = false;
continue;
}
// Check if we already replaced this instruction
if (constainsReplacedInstructions(ReplacedInstructions, Cand)) {
#ifdef DEBUG_SIMPLIFICATION
outs() << "[*] Skipping already replaced instruction\n";
#endif
Cand.isValid = false;
continue;
}
// Try to simplify the whole AST
int BitWidth = Cand.AST.front().I->getType()->getIntegerBitWidth();
if (BitWidth == 0 || BitWidth > 64) {
// If BitWidth is zero then stop here
continue;