forked from acsl-technion/cosmix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcosmix.cpp
2559 lines (2145 loc) · 82.3 KB
/
cosmix.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
/*
* COSMIX pass - Layered VM in SGX
*
* This pass adds COSMIX - customizing memory accesses to different backing stores with good performance for enclaves.
* This pass expects as input all the source files, combined in their IR representation.
* Then it is expected to be linked against the appropraite runtime libraries.
*
* The pass instruments the following:
* Global/Stack/Heap Insrumentation
*
* Asan reference code: $(LLVM-ROOT_DIR)/lib/Transforms/Instrumentation
*
*/
#define DEBUG_TYPE "cosmix"
#include "json/json.h"
#include "json/json-forwards.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSummaryIndex.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
// #include "llvm/Support/InitLLVM.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
// #include "llvm/Support/WithColor.h"
#include "llvm/Transforms/IPO/FunctionImport.h"
#include "llvm/Transforms/IPO/Internalize.h"
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
#include <llvm/Pass.h>
#include <llvm/IR/PassManager.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/CFG.h>
#include <llvm/Analysis/CFG.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/Casting.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Analysis/PostDominators.h>
#include <llvm/ADT/DepthFirstIterator.h>
#include <llvm/ADT/SmallSet.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/UnrollLoop.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/IR/MDBuilder.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/CallSite.h>
#include <llvm/Analysis/MemoryBuiltins.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/AssumptionCache.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/Loads.h>
#include <llvm/Analysis/LoopIterator.h>
#include <llvm/Analysis/LoopPass.h>
#include <llvm/Analysis/ValueTracking.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Transforms/Utils/LoopSimplify.h>
#include <llvm/Transforms/Utils/LCSSA.h>
#include <llvm/Transforms/Utils/LoopUtils.h>
#include <llvm/Support/Debug.h>
#include <llvm/Transforms/Utils/UnifyFunctionExitNodes.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Scalar/LoopPassManager.h>
#include <llvm/Analysis/ScalarEvolution.h>
#include <llvm/Analysis/ScalarEvolutionExpander.h>
#include <llvm/Analysis/ScalarEvolutionExpressions.h>
#include <llvm/Analysis/LoopAccessAnalysis.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/ADT/SCCIterator.h>
#include <MemoryModel/PointerAnalysis.h>
#include <WPA/Andersen.h>
#include <WPA/FlowSensitive.h>
#include <Util/SVFModule.h>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <tr1/memory>
#include <tr1/tuple>
#include <string>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include "../include/common.h"
using namespace llvm;
static cl::opt<std::string> opt_StartupFunctionMain("startup_func", cl::Optional, cl::init("main"),
cl::desc("Startup function name (defaults to main)"));
static cl::opt<bool> opt_FixRealFunctions("fix_real_functions", cl::Optional, cl::init(false),
cl::desc("temp solution"));
static cl::opt<bool> opt_HandleCrossPageCachedAccess("cross_page_cached_mstores_enabled", cl::Optional, cl::init(false),
cl::desc("Handle cross page accesses in cached mstores"));
static cl::opt<std::string> opt_AnalysisModule("analysis_module", cl::Optional, cl::init(""),
cl::desc("Perform pointer analysis just for this module (workaround for issue in SVF)"));
static cl::opt<std::string> opt_ConfigFile("config_file", cl::Optional, cl::init(""),
cl::desc("CoSMIX configuration file"));
static cl::opt<bool> opt_DisableLoopOptimization("disable_loop_opt", cl::Optional, cl::init(false),
cl::desc("Disable loop address translation caching optimization"));
static cl::opt<bool> opt_DisableInlineInstrumentation("disable_inline_instrumentation", cl::Optional, cl::init(false),
cl::desc("Force instrumentation of memory accesses to be regular function calls to CoSMIX runtime"));
static cl::opt<bool> opt_AlwaysReplaceAllocators("replace_all_allocators", cl::Optional, cl::init(true),
cl::desc("Instrument all dynamic allocators to invoke mstore allocator (can set runtime bound checking via config file)"));
static cl::opt<bool> opt_instrumentEnabled("instrument", cl::Optional, cl::init(true),
cl::desc("Enable/Disable instrumentation of memory operations"));
static cl::opt<bool> opt_CodeAnalysisWithInttoPtrOptEnalbed("code_analysis_integers", cl::Optional, cl::init(true),
cl::desc("Enable/Disable pointer analysis to include all encountered pointers to int casts (SVF workaround for variant GEPs)"));
static cl::opt<bool> opt_CodeAnalysisOptEnalbed("code_analysis", cl::Optional, cl::init(true),
cl::desc("Enable/Disable pointer analysis to instrument only MAY_ALIAS memory operations"));
static cl::opt<bool> opt_DumpSgx("dump_module", cl::Optional, cl::init(false),
cl::desc("Dump all of the module's IR to the console for debugging purposes"));
static cl::opt<bool> opt_printStatistics("cosmix_stats", cl::Optional, cl::init(true),
cl::desc("Print statistics on cosmix instrumentation of memory operations"));
namespace
{
const std::string COSMIX_PREFIX = "__cosmix_";
const std::string REAL_PREFIX = "_real_";
struct s_mstore
{
// std::string mstore_name;
std::string mstore_annotation_symbol;
std::string mstore_type;
std::string storage_type;
std::string mstore_function_annotation_name;
bool boundBasedAllocation;
size_t lowerBound;
size_t upperBound;
bool mstore_annotation_found;
};
/*
* Pass's logic
*/
class CosmixPass
{
// TODO: add helper print func with regards to verbosity requested by the user
#define GENERIC_ANNOTATION_SYMBOL "generic"
#define GET_FUNC(NAME) { if (F->getName().equals(#NAME)) NAME = F; }
#define LLVM_FUNC(F) (F->getName().contains("llvm"))
#define COSMIX_FUNC(F) (F->getName().startswith(COSMIX_PREFIX))
#define REAL_FUNC(F) (F->getName().startswith(REAL_PREFIX))
private:
struct s_mstore* g_mstores;
size_t num_of_mstores;
// Private Members
Module* M = nullptr;
DataLayout* DL = nullptr;
Function* __cosmix_debug_interal;
Function* __cosmix_write_page;
Function* __cosmix_fail;
Function* __cosmix_fail_asm;
DenseMap<Loop*, SmallPtrSet<Instruction*,4>> m_MemInstructionToOptimizeInLoop;
// Statistics counters
long m_NumOfMemoryAccessInstrumented;
long m_NumOfInstructions;
long m_NumOfOptMemInstInLoops;
long m_NumOfMemInstInLoops;
long m_NumOfInstrumentedAllocations;
DenseMap<NodeID, std::string> m_ValuesToInstrumentMap;
DenseMap<Value*, std::string> m_AnnotatedVars;
CallInst* m_CosmixLastInitInstruction;
PointerAnalysis* m_PTA;
PAG* m_PAG;
public:
// Ctor
CosmixPass(Module *M)
{
this->M = M;
this->DL = new DataLayout(M);
this->__cosmix_debug_interal = nullptr;
this->__cosmix_write_page = nullptr;
this->__cosmix_fail = nullptr;
this->__cosmix_fail_asm = nullptr;
this->m_NumOfMemInstInLoops = 0;
this->m_NumOfOptMemInstInLoops = 0;
this->m_NumOfMemoryAccessInstrumented = 0;
this->m_NumOfInstructions = 0;
this->m_NumOfInstrumentedAllocations = 0;
this->num_of_mstores = 0;
this->m_ValuesToInstrumentMap.clear();
this->m_AnnotatedVars.clear();
}
// Helper methods to deal with all encountered cases of LLVM due to different optimizations
void InitializePointerAnalysis()
{
SVFModule svfModule(this->M);
// m_PTA = new FlowSensitive();
m_PTA = new AndersenWaveDiffWithType();
m_PTA->disablePrintStat();
m_PAG = m_PTA->getPAG();
m_PAG->handleBlackHole(true);
// Finally, analyze
//
m_PTA->analyze(svfModule);
m_PAG = m_PTA->getPAG();
}
bool DONT_HAVE_COSMIX_METADATA(Value* value, Instruction* User)
{
if (!opt_CodeAnalysisOptEnalbed)
{
return false;
}
// Function* UserFunction = User->getParent()->getParent();
// if (COSMIX_FUNC(UserFunction) || MSTORE_FUNC(UserFunction))
// {
// return true;
// }
if (!m_PAG->hasValueNode(value))
{
return true;
}
NodeID targetNode = m_PAG->getValueNode(value->stripPointerCasts());
/*
for (auto kvp : m_AnnotatedVars)
{
Value* annotatedVar = kvp.first->stripPointerCasts();
// Get the node id for the annoated variable we analyze
//
NodeID annotatedNode = m_PAG->getValueNode(annotatedVar);
if (m_PTA->alias(targetNode, annotatedNode))
{
return false;
}
}
return true;
*/
return !m_ValuesToInstrumentMap.count(targetNode);
}
StringRef GetCosmixMetadata(Value* value)
{
if (!opt_CodeAnalysisOptEnalbed)
{
int numAnnotationFound = 0;
StringRef mstore_annotation_symbol;
for (unsigned int i=0;i<this->num_of_mstores;i++)
{
if (this->g_mstores[i].mstore_annotation_found)
{
mstore_annotation_symbol = this->g_mstores[i].mstore_annotation_symbol;
//errs() << "Found mstore_annotation_symbol: " << mstore_annotation_symbol << "\n";
numAnnotationFound++;
}
}
if (numAnnotationFound > 1)
{
return GENERIC_ANNOTATION_SYMBOL;
}
// Make sure at least one annotation was found - we do not currently support non-annotated programs
//
assert (numAnnotationFound == 1);
return mstore_annotation_symbol;
}
assert (m_PAG->hasValueNode(value));
NodeID targetNode = m_PAG->getValueNode(value);
assert (m_ValuesToInstrumentMap.count(targetNode));
return m_ValuesToInstrumentMap[targetNode];
}
bool is_direct_mstore(Value* value)
{
auto mstore_name = GetCosmixMetadata(value);
if (mstore_name == GENERIC_ANNOTATION_SYMBOL)
{
// Go over all mstores, if there is a direct one we can't currently prove its not a direct mstore
//
bool found_direct_mstore = false;
for (unsigned int i=0;i<this->num_of_mstores;i++)
{
if (this->g_mstores[i].mstore_type == "direct")
{
found_direct_mstore = true;
}
}
return found_direct_mstore;
}
for (unsigned int i=0;i<this->num_of_mstores;i++)
{
if (this->g_mstores[i].mstore_annotation_symbol == mstore_name)
{
return this->g_mstores[i].mstore_type == "direct";
}
}
assert (false && "[ERROR] - Could not determine mstore is direct or cached based on this value");
return false;
}
bool isPointerToPointer(const Value* V)
{
const Type* T = V->getType();
return T->isPointerTy() && T->getContainedType(0)->isPointerTy();
}
bool isPointerOriginally(Value* V)
{
if (V->getType()->isPointerTy())
return true;
if (isa<PtrToIntInst>(V))
return true;
if (V->getName().startswith("scevgep")
|| V->getName().startswith("uglygep"))
{
errs() <<"[Warning] - found unglygep\n";
V->dump();
exit(-1);
return true;
}
return false;
}
void fixRealFunctions(Function* F)
{
if (REAL_FUNC(F))
{
Function* functionToReplace = M->getFunction(F->getName().str().substr(REAL_PREFIX.length()));
assert (functionToReplace);
F->replaceAllUsesWith(functionToReplace);
}
}
// Helper method to find and initialize all related helper methods.
void findHelperFunc(Function *F)
{
if (F->isDeclaration() && !LLVM_FUNC(F) && !COSMIX_FUNC(F))
{
Function* functionToReplace = M->getFunction(COSMIX_PREFIX + F->getName().str());
if (functionToReplace)
{
SmallPtrSet<CallInst*, 4> fixCallInstsSet;
// Track all cosmix runtime functions that we didn't handle correctly, make them point to the original libc function
for (auto User : F->users())
{
CallInst* CI = dyn_cast<CallInst>(&*User);
if (CI && (COSMIX_FUNC(CI->getParent()->getParent())))
{
// restore done
fixCallInstsSet.insert(CI);
}
}
// errs() << "[INFO] - instrumented function: " << F->getName() << "\n";
F->replaceAllUsesWith(functionToReplace);
for (auto CI : fixCallInstsSet)
{
CI->setCalledFunction(F);
}
}
else
{
// errs() << "[Warning] - could not instrument function, not yet supported: " << F->getName() << "\n";
}
//m_DeclarationFunctions.insert(F);
}
GET_FUNC(__cosmix_debug_interal);
GET_FUNC(__cosmix_write_page);
GET_FUNC(__cosmix_fail);
GET_FUNC(__cosmix_fail_asm);
}
void handleExceptions(InvokeInst* II)
{
errs() << "== [Warning] == found throwable invoke function call...not yet tested this functionality, dumping\n";
II->dump();
exit(-1);
}
void visitGlobalDefinition(GlobalVariable* GV, StringRef mstoreType)
{
// 1. Create a new global that is a pointer to the global type
//
GlobalVariable* newG = new GlobalVariable(*M,
GV->getValueType()->getPointerTo(),
false,
GV->getLinkage(),
nullptr,
GV->getName() + "_" + mstoreType,
GV,
GV->getThreadLocalMode());
newG->copyAttributesFrom(GV);
newG->setInitializer(Constant::getNullValue(GV->getValueType()->getPointerTo()));
// 3. replace all uses of GV with a loaded value of newG, the rest will be handled as regular mstore variable by the compiler and runtime
//
auto UI = GV->use_begin();
auto E = GV->use_end();
for (; UI != E;) {
Use &U = *UI;
++UI;
// Must handle Constants specially, we cannot call replaceUsesOfWith on a
// constant because they are uniqued.
if (auto *C = dyn_cast<ConstantExpr>(U.getUser()))
{
for (auto C_User : C->users())
{
if (Instruction* I = dyn_cast<Instruction>(C_User))
{
IRBuilder<> IRB_internal(I);
LoadInst* LI = IRB_internal.CreateLoad(newG);
auto temp = C->getAsInstruction();
IRB_internal.Insert(temp);
temp->replaceUsesOfWith(GV, LI);
C->replaceAllUsesWith(temp);
// 4. Register this variable with the dataflow analysis
//
assert (!m_AnnotatedVars.count(LI));
m_AnnotatedVars[LI] = mstoreType.str();
}
assert (false && "Cannot handle global instrumentation of mstore for multi level constatnt experessions yet");
}
}
if (auto *I = dyn_cast<Instruction>(U.getUser()))
{
IRBuilder<> IRB_internal(I);
LoadInst* LI = IRB_internal.CreateLoad(newG);
U.set(LI);
// 4. Register this variable with the dataflow analysis
//
assert (!m_AnnotatedVars.count(LI));
m_AnnotatedVars[LI] = mstoreType.str();
}
assert (false && "cannot instrument this global since its use list contains undetermined use");
}
// 2. Allocate mstore memory for newG and initialize it with GV's data
//
IRBuilder<> IRB(M->getFunction(opt_StartupFunctionMain)->begin()->getFirstNonPHIOrDbgOrLifetime());
Function* F = M->getFunction("__cosmix_init_global_" + mstoreType.str());
assert (F && "Cannot find global init function");
auto GV8 = IRB.CreatePointerCast(GV, IRB.getInt8PtrTy());
auto newG8 = IRB.CreatePointerCast(newG, IRB.getInt8PtrTy());
// Value * PH = ConstantPointerNull::get (getVoidPtrType(GV->getContext()));
Type* csiType = IntegerType::getInt32Ty(GV->getContext());
Type * GlobalType = GV->getType()->getElementType();
unsigned TypeSize = this->DL->getTypeAllocSize((GlobalType));
if (!TypeSize) {
llvm::errs() << "FIXME: Ignoring global of size zero: ";
GV->dump();
return;
}
Value * AllocSize = ConstantInt::get (csiType, TypeSize);
IRB.CreateCall(F, { newG8, GV8, AllocSize });
// GV->eraseFromParent();
// newG->takeName(GV);
}
void visitStackAllocation(AllocaInst* AI, StringRef mstoreType)
{
// Note: for every alloca we replace it with heap allocation via cosmix runtime
IRBuilder<> IRB(AI);
Value* size = AI->isArrayAllocation() ?
IRB.CreateMul(
IRB.getInt64(AI->getAllocatedType()->getArrayNumElements()),
IRB.getInt64(DL->getTypeAllocSize(AI->getAllocatedType()->getArrayElementType()))) :
IRB.getInt64(DL->getTypeAllocSize(AI->getAllocatedType()));
Value* size_casted = IRB.CreateIntCast(size, IRB.getInt64Ty(), false);
// Get allocation function based on mstore type
//
std::string mstoreAllocFuncName = COSMIX_PREFIX + "malloc_" + mstoreType.str();
CallInst* CI = IRB.CreateCall(M->getFunction(mstoreAllocFuncName), size_casted);
Value* CI_casted = IRB.CreatePointerCast(CI, AI->getType());
AI->replaceAllUsesWith(CI_casted);
CI_casted->takeName(AI);
AI->eraseFromParent();
assert (!m_AnnotatedVars.count(CI));
m_AnnotatedVars[CI] = mstoreType;
// Finally, make sure it is freed at the end of the function
//
Function* F = CI->getParent()->getParent();
if (!F->doesNotReturn())
{
for (auto BB = F->begin(), BBend = F->end(); BB != BBend; ++BB)
{
for (auto I = BB->begin(); I != BB->end();I++)
{
if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
{
IRB.SetInsertPoint(RI);
CallInst* freeCI = IRB.CreateCall(M->getFunction(COSMIX_PREFIX + "free"), CI);
}
}
}
}
}
void visitInvokeInst(InvokeInst* II)
{
if (II->doesNotThrow())
{
return; // nothing to handle in this case
}
if (!II->getCalledFunction())
{
errs() << "[Warning] - invoke function pointer or inline computation\n";
}
handleExceptions(II);
}
void visitCallInst(CallInst* CI)
{
// regular functions are already instrumented, just handle inline asm calls
//
if (CI->isInlineAsm())
{
IRBuilder<> IRB(CI);
for (unsigned int j=0; j < CI->getNumArgOperands(); j++)
{
if (CI->getArgOperand(j)->getType()->isPtrOrPtrVectorTy())
{
Value* arg8 = IRB.CreatePointerCast(CI->getArgOperand(j), IRB.getInt8PtrTy());
IRB.CreateCall(__cosmix_fail_asm, arg8);
}
}
return;
}
Function* F = CI->getCalledFunction();
// TODO: printf-type functions should have wrappers as part of the cosmix runtime
//
if (F && F->isVarArg() && F->isDeclaration() && F->getName().contains("printf"))
{
IRBuilder<> IRB(CI);
// go over all args and make sure we replace them with a linked val
for (unsigned int i=0; i < CI->getNumArgOperands(); i++)
{
Value* ptr = CI->getArgOperand(i);
if (!ptr->getType()->isPointerTy() || DONT_HAVE_COSMIX_METADATA(ptr->stripPointerCasts(), CI))
{
continue;
}
// TODO: link generic and direct should be specially handled
std::string linkageFunctionName = COSMIX_PREFIX + "link_" + GetCosmixMetadata(ptr).str();
Function* linkageFunction = M->getFunction(linkageFunctionName);
assert (linkageFunction && "[Error] could not find instrumented linkage function\n");
unsigned sizeinBits = DL->getTypeSizeInBits(ptr->getType()->getPointerElementType());
unsigned size = sizeinBits / BIT_SIZE;
Value* valSize = IRB.getInt32(size);
Value* ptr8 = IRB.CreatePointerCast(ptr, IRB.getInt8PtrTy());
Value* isVectorPtr = IRB.getInt8(isDereferenceableAndAlignedPointer(ptr, size, *this->DL));
Value* isDirty = IRB.getInt8(0);
auto args = { ptr8, valSize, isVectorPtr, isDirty };
CallInst* linked_ptr = IRB.CreateCall(linkageFunction, args);
Value* linked_ptr_casted = IRB.CreatePointerCast(linked_ptr, ptr->getType());
CI->setArgOperand(i, linked_ptr_casted);
}
}
}
int getMemPointerOperandIdx(Instruction* I)
{
switch (I->getOpcode())
{
case Instruction::Load:
return cast<LoadInst>(I)->getPointerOperandIndex();
case Instruction::Store:
return cast<StoreInst>(I)->getPointerOperandIndex();
case Instruction::AtomicCmpXchg:
return cast<AtomicCmpXchgInst>(I)->getPointerOperandIndex();
case Instruction::AtomicRMW:
return cast<AtomicRMWInst>(I)->getPointerOperandIndex();
}
return -1;
}
void visitAtomics(Instruction* MI)
{
int ptrOperandIdx = getMemPointerOperandIdx(MI);
Value* ptr_strip_casts = MI->getOperand(ptrOperandIdx)->stripPointerCasts();
if (DONT_HAVE_COSMIX_METADATA(ptr_strip_casts, MI))
{
return;
}
IRBuilder<> IRB(MI);
Value* ptr8 = IRB.CreatePointerCast(MI->getOperand(ptrOperandIdx), IRB.getInt8PtrTy());
IRB.CreateCall(M->getFunction("__cosmix_test_atomic"), ptr8);
}
void visitMemInstAndLink(Instruction* MI, LoopInfo* LI, DominatorTree* DT, AliasAnalysis *AA, ScalarEvolution* SE)
{
// Optimize native pointers that we can determine at compile time
//
int ptrOperandIdx = getMemPointerOperandIdx(MI);
bool is_load_access = isa<LoadInst>(MI);
unsigned sizeinBits = isa<StoreInst>(MI) ? DL->getTypeStoreSizeInBits(MI->getOperand(ptrOperandIdx)->getType()->getPointerElementType()) :
DL->getTypeSizeInBits(MI->getOperand(ptrOperandIdx)->getType()->getPointerElementType());
unsigned size = sizeinBits / BIT_SIZE;
Value* ptr_strip_casts = MI->getOperand(ptrOperandIdx)->stripPointerCasts();
if (DONT_HAVE_COSMIX_METADATA(ptr_strip_casts, MI))
{
return;
}
if (!opt_DisableLoopOptimization)
{
// Start section of loop optimization
Loop *L = LI->getLoopFor(MI->getParent());
// Note: direct mstores cannot use TLB, so test for them
//
if (L && !is_direct_mstore(ptr_strip_casts))
{
m_NumOfMemInstInLoops++;
const SCEV* ptrSCEV = SE->getSCEV(ptr_strip_casts);
if (ptrSCEV && static_cast<SCEVTypes>(ptrSCEV->getSCEVType()) == scAddRecExpr)
{
const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ptrSCEV);
// We only work with expressions of form `A + B*x`
// We are going to transform this to a loop structure that assumes this mem access instruction executes on every loop iteration
// Verify both conditions are true before optimizing
//
if (AR->isAffine() && isGuaranteedToExecuteForEveryIteration(MI, AR->getLoop()))
{
m_NumOfOptMemInstInLoops++;
m_MemInstructionToOptimizeInLoop[L].insert(MI);
// We track this instruction and will translate it somewhere else (during the loop optimization pass)
//
return;
}
}
}
}
// end section of loop optimization
IRBuilder<> IRB(MI);
Value* valSize = IRB.getInt32(size);
Value* ptr8 = IRB.CreatePointerCast(MI->getOperand(ptrOperandIdx), IRB.getInt8PtrTy());
Value* isVectorPtr = IRB.getInt8(0);//isDereferenceableAndAlignedPointer(MI->getOperand(ptrOperandIdx), size, *this->DL, MI));
Value* isDirty = is_load_access ? IRB.getInt8(0) : IRB.getInt8(1);
// auto args = { ptr8, valSize, isVectorPtr, isDirty };
std::string linkageFunctionName = COSMIX_PREFIX + "link_" + GetCosmixMetadata(ptr_strip_casts).str().c_str();
Function* linkageFunction = M->getFunction(linkageFunctionName);
assert (linkageFunction && "[Error] could not find instrumented linkage function\n");
CallInst* linked_ptr = IRB.CreateCall(linkageFunction, { ptr8, valSize, isVectorPtr, isDirty });
Value* linked_ptr_casted = IRB.CreatePointerCast(linked_ptr, MI->getOperand(ptrOperandIdx)->getType());
MI->setOperand(ptrOperandIdx, linked_ptr_casted);
if (is_direct_mstore(ptr_strip_casts) && !is_load_access)
{
// Insert a direct store after the MI instruction
IRB.SetInsertPoint(MI->getNextNode());
Function* writeback_func = M->getFunction("__cosmix_writeback_" + GetCosmixMetadata(ptr_strip_casts).str());
assert(writeback_func && "[Error] could not find instrumented writeback function for direct mstore");
auto writeback_args = { ptr8, valSize };
IRB.CreateCall(writeback_func, writeback_args);
}
if (opt_HandleCrossPageCachedAccess && !is_load_access)
{
IRB.SetInsertPoint(MI->getNextNode());
Function* writeback_func = M->getFunction("__cosmix_writeback_" + GetCosmixMetadata(ptr_strip_casts).str());
assert(writeback_func && "[Error] could not find instrumented writeback function for direct mstore");
IRB.CreateCall(writeback_func);
}
}
void optimizeLoopMemInstruction(SmallPtrSet<Instruction*, 4>& MIs, LoopInfo* LI, DominatorTree* DT, ScalarEvolution* SE, Loop* L)
{
BasicBlock *PreHeader = L->getLoopPreheader();
BasicBlock *Header = L->getHeader();
BasicBlock *Latch = L->getLoopLatch();
// New latch - same logic as preheader - hold the values to validate the offsets - copy the same logic there
BasicBlock* NewLatch = SplitEdge(Latch, Header, DT, LI);
NewLatch->setName(Latch->getName() + ".loop_opt");
IRBuilder<> IRB(NewLatch->getTerminator());
BasicBlock* currBBToLatchFrom = NewLatch;
for (auto MI : MIs)
{
int memPtrIndex = getMemPointerOperandIdx(MI);
bool is_load_access = isa<LoadInst>(MI);
Value* memPtr = MI->getOperand(memPtrIndex);
uint64_t ptrSize = this->DL->getTypeSizeInBits(memPtr->getType()->getPointerElementType()) / BIT_SIZE;
std::string linkageFunctionName = COSMIX_PREFIX + "link_" + GetCosmixMetadata(memPtr->stripPointerCasts()).str();
std::string validIterationsFunctionName = COSMIX_PREFIX + "get_valid_iterations_" + GetCosmixMetadata(memPtr->stripPointerCasts()).str();
Function* linkageFunction = M->getFunction(linkageFunctionName);
Function* validIterationsFunction = M->getFunction(validIterationsFunctionName);
assert (linkageFunction && "[Error] could not find instrumented linkage function\n");
assert (validIterationsFunction && "[Error] could not find instrumented linkage function\n");
// First, set the number of valid iterations remaining
//
IRB.SetInsertPoint(Header->getFirstNonPHI());
int numberOfPredecessors = std::distance(pred_begin(Header), pred_end(Header));
assert(2 == numberOfPredecessors);
PHINode* ValidIterationsRemaining_PN = IRB.CreatePHI(IRB.getInt32Ty(), 2);
// Next, split and define the new BBs according to a condition based on the valid number of iterations
//
IRB.SetInsertPoint(currBBToLatchFrom->getTerminator());
Value* DecrementedValidIterations = IRB.CreateSub(ValidIterationsRemaining_PN, IRB.getInt32(1));
Value* TestIfIterationsStillValid = IRB.CreateICmpSLE(DecrementedValidIterations, IRB.getInt32(0));
TerminatorInst* TI = SplitBlockAndInsertIfThen(TestIfIterationsStillValid,
currBBToLatchFrom->getTerminator(), false, nullptr, DT, LI);
BasicBlock* ThenBlock = TI->getParent();
ThenBlock->setName(NewLatch->getName() + ".then." + MI->getName());
BasicBlock* AfterBlock = TI->getSuccessor(0);
AfterBlock->setName(NewLatch->getName() + ".after." + MI->getName());
// Code at the Prehader:
// Initialize the linking of the pointers and compute the valid number of iterations
//
IRB.SetInsertPoint(PreHeader->getTerminator());
const SCEV* ptrSCEV = SE->getSCEV(memPtr);
const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ptrSCEV);
SCEVExpander Expander(*SE, *this->DL, "loopscevs");
Value* stepValue = Expander.expandCodeFor(AR->getStepRecurrence(*SE),
memPtr->stripPointerCasts()->getType(), PreHeader->getTerminator());
Value* stepValueInt = IRB.CreatePtrToInt(
stepValue, IRB.getInt64Ty());
Value* minusStepValue = IRB.CreateMul(IRB.getInt64(-1), stepValueInt);
Value* initialValue = Expander.expandCodeFor(AR->getStart(),
memPtr->stripPointerCasts()->getType(), PreHeader->getTerminator());
Value* initialValue8 = IRB.CreatePointerCast(initialValue, IRB.getInt8PtrTy());
Value* isVectorPtr = IRB.getInt8(isDereferenceableAndAlignedPointer(memPtr, ptrSize, *this->DL, MI));
Value* isDirty = is_load_access ? IRB.getInt8(0) : IRB.getInt8(1);
// ArrayRef<Value*> args = { initialValue8, IRB.getInt32(ptrSize), isVectorPtr, isDirty };
CallInst* linked_ptr8 = IRB.CreateCall(linkageFunction, { initialValue8, IRB.getInt32(ptrSize), isVectorPtr, isDirty });
// InitialValidIterations->print(errs(), true);
// Value* linked_ptr = IRB.CreatePointerCast(linked_ptr8, memPtr->getType());
// We always move a single step (at every iteration) - so we should decrement this value at the preheader
//
Value* linked_ptr_correct_offset8 = IRB.CreateGEP(linked_ptr8, minusStepValue);
Value* linked_ptr_casted = IRB.CreatePointerCast(linked_ptr_correct_offset8, memPtr->getType());
// Get the minimum value of the valid iterations of this loop in relation to this MI
//
// ArrayRef<Value*> offset_args = { initialValue8, linked_ptr8, stepValueInt, IRB.getInt32(ptrSize) };
CallInst* InitialValidIterations = IRB.CreateCall(
validIterationsFunction, { initialValue8, linked_ptr8, stepValueInt, IRB.getInt32(ptrSize) });
ValidIterationsRemaining_PN->addIncoming(InitialValidIterations, PreHeader);
// Code at Header:
// Mutate the linked pointers between loop iterations (one from preheader, one from the latch)
//
IRB.SetInsertPoint(Header->getFirstNonPHI());
PHINode* LinkedPtr_PN = IRB.CreatePHI(memPtr->getType(), numberOfPredecessors);
PHINode* IterationsPassed = IRB.CreatePHI(IRB.getInt64Ty(), numberOfPredecessors);
Value* LinkedPtr_PN8 = IRB.CreatePointerCast(LinkedPtr_PN, IRB.getInt8PtrTy());
LinkedPtr_PN->addIncoming(linked_ptr_casted, PreHeader);
IterationsPassed->addIncoming(IRB.getInt64(1), PreHeader);
// Note: we set the one from the latch (after block) when we define it and set its logic
// Fix the memory access operand to the cached value but only after we add the step value
//
Value* currentIterationPtr8 = IRB.CreateGEP(LinkedPtr_PN8, stepValueInt);
Value* currentIterationPtr = IRB.CreatePointerCast(currentIterationPtr8, LinkedPtr_PN->getType());
Value* ptr_mask_removed = IRB.CreatePointerCast(currentIterationPtr8, LinkedPtr_PN->getType());
MI->setOperand(memPtrIndex, ptr_mask_removed);
// Code at the THEN block:
// We are at this block when we need to unlink+link since pointers are no longer valid
//
IRB.SetInsertPoint(ThenBlock->getFirstNonPHI());
// GEP unlinked ptr to move past the value.
//
Value* nextIterationPtr = IRB.CreateGEP(initialValue8, IRB.CreateMul(stepValueInt, IterationsPassed));
// ArrayRef<Value*> relink_args = { nextIterationPtr, IRB.getInt32(ptrSize), isVectorPtr, isDirty };
// Call link function
//
CallInst* relinked_ptr8 = IRB.CreateCall(linkageFunction, { nextIterationPtr, IRB.getInt32(ptrSize), isVectorPtr, isDirty });
// Value* relinked_ptr = IRB.CreatePointerCast(relinked_ptr8, memPtr->getType());
// GEP back so the offset in the next iteration will be correct
//
Value* relinked_ptr_correct_offset8 = IRB.CreateGEP(relinked_ptr8, minusStepValue);
Value* relinked_ptr_casted = IRB.CreatePointerCast(relinked_ptr_correct_offset8, memPtr->getType());
// Find the valid number of iterations for this new linked pointer
//
// ArrayRef<Value*> relink_offset_args = { initialValue8, relinked_ptr8, stepValueInt, IRB.getInt32(ptrSize) };
CallInst* RecomputedValidIterations = IRB.CreateCall(
validIterationsFunction, { initialValue8, relinked_ptr8, stepValueInt, IRB.getInt32(ptrSize) });
// After block:
// Simply set the Phi node of the pointer for mutation
//
IRB.SetInsertPoint(AfterBlock->getFirstNonPHI());
assert(2 == std::distance(pred_begin(AfterBlock), pred_end(AfterBlock)));
PHINode* NextLinkedPtr_PN = IRB.CreatePHI(memPtr->getType(), 2);
PHINode* NextValidIterations_PN = IRB.CreatePHI(IRB.getInt32Ty(), 2);
NextValidIterations_PN->addIncoming(DecrementedValidIterations, currBBToLatchFrom);
NextValidIterations_PN->addIncoming(RecomputedValidIterations, ThenBlock);
ValidIterationsRemaining_PN->addIncoming(NextValidIterations_PN, AfterBlock);
Value* NextIterationsPassed = IRB.CreateAdd(IterationsPassed, IRB.getInt64(1));
IterationsPassed->addIncoming(NextIterationsPassed, AfterBlock);
// If came from the THEN block - use the relinked version we computed
//
NextLinkedPtr_PN->addIncoming(relinked_ptr_casted, ThenBlock);
// Otherwise, its the original pointer, use the value we computed for the MI
//
NextLinkedPtr_PN->addIncoming(currentIterationPtr, currBBToLatchFrom);
// Finally, set the pointer in the header to consider in next iterations either relinked, or a mutable ptr
//
LinkedPtr_PN->addIncoming(NextLinkedPtr_PN, AfterBlock);
// Set the new latching block for next iteration
//
currBBToLatchFrom = AfterBlock;
if (opt_HandleCrossPageCachedAccess)
{
IRB.SetInsertPoint(MI);
CallInst* linked_ptr_temp = IRB.CreateCall(linkageFunction, { IRB.CreatePointerCast(memPtr, IRB.getInt8PtrTy()), IRB.getInt32(ptrSize), isVectorPtr, isDirty });
MI->setOperand(memPtrIndex, IRB.CreatePointerCast(linked_ptr_temp, memPtr->getType()));
IRB.SetInsertPoint(MI->getNextNode());
Function* writeback_func = M->getFunction("__cosmix_writeback_" + GetCosmixMetadata(memPtr->stripPointerCasts()).str());
assert(writeback_func && "[Error] could not find instrumented writeback function for direct mstore");
IRB.CreateCall(writeback_func);
}
}
}
Function* getMemIntrinsicFunction(MemIntrinsic *MI, StringRef name)
{
std::string functionName = COSMIX_PREFIX + name.str();
Function* F = M->getFunction(functionName);
assert (F && "[ERROR] Invalid instrumentation for memintrinsic, could not find a suitable instrumentation option");
return F;
}
void visitMemIntrinsic(MemIntrinsic *MI)
{
IRBuilder<> IRB(MI);
if (isa<MemTransferInst>(MI))
{
if (DONT_HAVE_COSMIX_METADATA(MI->getOperand(0)->stripPointerCasts(), MI) && DONT_HAVE_COSMIX_METADATA(MI->getOperand(1)->stripPointerCasts(), MI))
{
return;
}
auto memmove_args = { IRB.CreatePointerCast(MI->getOperand(0),
IRB.getInt8PtrTy()), IRB.CreatePointerCast(
MI->getOperand(1), IRB.getInt8PtrTy()),
IRB.CreateIntCast(MI->getOperand(2),
IRB.getInt64Ty(), false) };
IRB.CreateCall(
isa<MemMoveInst>(MI) ?
getMemIntrinsicFunction(MI, "memmove") :
getMemIntrinsicFunction(MI, "memcpy"),
memmove_args);
}
else if (isa<MemSetInst>(MI))
{
if (DONT_HAVE_COSMIX_METADATA(MI->getOperand(0)->stripPointerCasts(), MI))
{