-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathGenMCDriver.cpp
More file actions
3909 lines (3321 loc) · 115 KB
/
GenMCDriver.cpp
File metadata and controls
3909 lines (3321 loc) · 115 KB
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
/*
* GenMC -- Generic Model Checking.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you can access it online at
* http://www.gnu.org/licenses/gpl-3.0.html.
*
* Author: Michalis Kokologiannakis <michalis@mpi-sws.org>
*/
#include "GenMCDriver.hpp"
#include "BoundDecider.hpp"
#include "Config.hpp"
#include "DepExecutionGraph.hpp"
#include "DriverHandlerDispatcher.hpp"
#include "Error.hpp"
#include "GraphIterators.hpp"
#include "Interpreter.h"
#include "LLVMModule.hpp"
#include "LabelVisitor.hpp"
#include "Logger.hpp"
#include "MaximalIterator.hpp"
#include "Parser.hpp"
#include "SExprVisitor.hpp"
#include "ThreadPool.hpp"
#include "config.h"
#include <llvm/IR/Verifier.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/raw_os_ostream.h>
#include <algorithm>
#include <csignal>
/************************************************************
** GENERIC MODEL CHECKING DRIVER
***********************************************************/
GenMCDriver::GenMCDriver(std::shared_ptr<const Config> conf, std::unique_ptr<llvm::Module> mod,
std::unique_ptr<ModuleInfo> modInfo, Mode mode /* = VerificationMode{} */)
: userConf(std::move(conf)), mode(mode)
{
/* Set up the execution context */
auto execGraph = userConf->isDepTrackingModel ? std::make_unique<DepExecutionGraph>()
: std::make_unique<ExecutionGraph>();
execStack.emplace_back(std::move(execGraph), std::move(LocalQueueT()),
std::move(ChoiceMap()));
auto hasBounder = userConf->bound.has_value();
GENMC_DEBUG(hasBounder |= userConf->boundsHistogram;);
if (hasBounder)
bounder = BoundDecider::create(getConf()->boundType);
/* Create an interpreter for the program's instructions */
std::string buf;
EE = llvm::Interpreter::create(std::move(mod), std::move(modInfo), this, getConf(),
getAddrAllocator(), &buf);
/* Set up a random-number generator (for the scheduler) */
std::random_device rd;
auto seedVal = (!userConf->randomScheduleSeed.empty())
? (MyRNG::result_type)stoull(userConf->randomScheduleSeed)
: rd();
if (userConf->printRandomScheduleSeed) {
PRINT(VerbosityLevel::Error) << "Seed: " << seedVal << "\n";
}
rng.seed(seedVal);
estRng.seed(rd());
/*
* Make sure we can resolve symbols in the program as well. We use 0
* as an argument in order to load the program, not a library. This
* is useful as it allows the executions of external functions in the
* user code.
*/
std::string ErrorStr;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr, &ErrorStr)) {
WARN("Could not resolve symbols in the program: " + ErrorStr);
}
}
GenMCDriver::~GenMCDriver() = default;
GenMCDriver::Execution::Execution(std::unique_ptr<ExecutionGraph> g, LocalQueueT &&w, ChoiceMap &&m)
: graph(std::move(g)), workqueue(std::move(w)), choices(std::move(m))
{}
GenMCDriver::Execution::~Execution() = default;
void repairRead(ExecutionGraph &g, ReadLabel *lab)
{
auto last = (store_rbegin(g, lab->getAddr()) == store_rend(g, lab->getAddr()))
? Event::getInit()
: store_rbegin(g, lab->getAddr())->getPos();
g.changeRf(lab->getPos(), last);
lab->setAddedMax(true);
lab->setIPRStatus(g.getEventLabel(last)->getStamp() > lab->getStamp());
}
void repairDanglingReads(ExecutionGraph &g)
{
for (auto i = 0U; i < g.getNumThreads(); i++) {
auto *rLab = llvm::dyn_cast<ReadLabel>(g.getLastThreadLabel(i));
if (!rLab)
continue;
if (!rLab->getRf()) {
repairRead(g, rLab);
}
}
}
void GenMCDriver::Execution::restrictGraph(Stamp stamp)
{
/* Restrict the graph (and relations). It can be the case that
* events with larger stamp remain in the graph (e.g.,
* BEGINs). Fix their stamps too. */
auto &g = getGraph();
g.cutToStamp(stamp);
g.compressStampsAfter(stamp);
repairDanglingReads(g);
}
void GenMCDriver::Execution::restrictWorklist(Stamp stamp)
{
std::vector<Stamp> idxsToRemove;
auto &workqueue = getWorkqueue();
for (auto rit = workqueue.rbegin(); rit != workqueue.rend(); ++rit)
if (rit->first > stamp && rit->second.empty())
idxsToRemove.push_back(rit->first); // TODO: break out of loop?
for (auto &i : idxsToRemove)
workqueue.erase(i);
}
void GenMCDriver::Execution::restrictChoices(Stamp stamp)
{
auto &choices = getChoiceMap();
for (auto cit = choices.begin(); cit != choices.end();) {
if (cit->first > stamp.get()) {
cit = choices.erase(cit);
} else {
++cit;
}
}
}
void GenMCDriver::Execution::restrict(Stamp stamp)
{
restrictGraph(stamp);
restrictWorklist(stamp);
restrictChoices(stamp);
}
void GenMCDriver::pushExecution(Execution &&e) { execStack.push_back(std::move(e)); }
bool GenMCDriver::popExecution()
{
if (execStack.empty())
return false;
execStack.pop_back();
return !execStack.empty();
}
GenMCDriver::State::State(std::unique_ptr<ExecutionGraph> g, ChoiceMap &&m, SAddrAllocator &&a,
llvm::BitVector &&fds, ValuePrefixT &&c, Event la)
: graph(std::move(g)), choices(std::move(m)), alloctor(std::move(a)), fds(std::move(fds)),
cache(std::move(c)), lastAdded(la)
{}
GenMCDriver::State::~State() = default;
void GenMCDriver::initFromState(std::unique_ptr<State> s)
{
execStack.clear();
execStack.emplace_back(std::move(s->graph), LocalQueueT(), std::move(s->choices));
alloctor = std::move(s->alloctor);
fds = std::move(s->fds);
seenPrefixes = std::move(s->cache);
lastAdded = s->lastAdded;
}
std::unique_ptr<GenMCDriver::State> GenMCDriver::extractState()
{
auto cache = std::move(seenPrefixes);
seenPrefixes.clear();
return std::make_unique<State>(getGraph().clone(), ChoiceMap(getChoiceMap()),
SAddrAllocator(alloctor), llvm::BitVector(fds),
std::move(cache), lastAdded);
}
/* Returns a fresh address to be used from the interpreter */
SAddr GenMCDriver::getFreshAddr(const MallocLabel *aLab)
{
/* The arguments to getFreshAddr() need to be well-formed;
* make sure the alignment is positive and a power of 2 */
auto alignment = aLab->getAlignment();
BUG_ON(alignment <= 0 || (alignment & (alignment - 1)) != 0);
switch (aLab->getStorageDuration()) {
case StorageDuration::SD_Automatic:
return getAddrAllocator().allocAutomatic(
aLab->getAllocSize(), alignment,
aLab->getStorageType() == StorageType::ST_Durable,
aLab->getAddressSpace() == AddressSpace::AS_Internal);
case StorageDuration::SD_Heap:
return getAddrAllocator().allocHeap(
aLab->getAllocSize(), alignment,
aLab->getStorageType() == StorageType::ST_Durable,
aLab->getAddressSpace() == AddressSpace::AS_Internal);
case StorageDuration::SD_Static: /* Cannot ask for fresh static addresses */
default:
BUG();
}
BUG();
return SAddr();
}
int GenMCDriver::getFreshFd()
{
int fd = fds.find_first_unset();
/* If no available descriptor found, grow fds and try again */
if (fd == -1) {
fds.resize(2 * fds.size() + 1);
return getFreshFd();
}
/* Otherwise, mark the file descriptor as used */
markFdAsUsed(fd);
return fd;
}
void GenMCDriver::markFdAsUsed(int fd)
{
if (fd > fds.size())
fds.resize(fd);
fds.set(fd);
}
void GenMCDriver::resetThreadPrioritization() { threadPrios.clear(); }
bool GenMCDriver::isSchedulable(int thread) const
{
auto &thr = getEE()->getThrById(thread);
auto *lab = getGraph().getLastThreadLabel(thread);
return !thr.ECStack.empty() && !lab->isTerminator();
}
bool GenMCDriver::schedulePrioritized()
{
/* Return false if no thread is prioritized */
if (threadPrios.empty())
return false;
BUG_ON(getConf()->bound.has_value());
const auto &g = getGraph();
auto *EE = getEE();
for (auto &e : threadPrios) {
/* Skip unschedulable threads */
if (!isSchedulable(e.thread))
continue;
/* Found a not-yet-complete thread; schedule it */
EE->scheduleThread(e.thread);
return true;
}
return false;
}
bool GenMCDriver::scheduleNextLTR()
{
auto &g = getGraph();
auto *EE = getEE();
for (auto i = 0U; i < g.getNumThreads(); i++) {
if (!isSchedulable(i))
continue;
/* Found a not-yet-complete thread; schedule it */
EE->scheduleThread(i);
return true;
}
/* No schedulable thread found */
return false;
}
bool GenMCDriver::isNextThreadInstLoad(int tid)
{
auto &I = getEE()->getThrById(tid).ECStack.back().CurInst;
/* Overapproximate with function calls some of which might be modeled as loads */
auto *ci = llvm::dyn_cast<CallInst>(I);
return llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::AtomicCmpXchgInst>(I) ||
llvm::isa<llvm::AtomicRMWInst>(I) ||
(ci && ci->getCalledFunction() &&
hasGlobalLoadSemantics(ci->getCalledFunction()->getName().str()));
}
bool GenMCDriver::scheduleNextWF()
{
auto &g = getGraph();
auto *EE = getEE();
/* First, schedule based on the EG */
for (auto i = 0u; i < g.getNumThreads(); i++) {
if (!isSchedulable(i))
continue;
if (g.containsPos(Event(i, EE->getThrById(i).globalInstructions + 1))) {
EE->scheduleThread(i);
return true;
}
}
/* Try and find a thread that satisfies the policy.
* Keep an LTR fallback option in case this fails */
long fallback = -1;
for (auto i = 0u; i < g.getNumThreads(); i++) {
if (!isSchedulable(i))
continue;
if (fallback == -1)
fallback = i;
if (!isNextThreadInstLoad(i)) {
EE->scheduleThread(getFirstSchedulableSymmetric(i));
return true;
}
}
/* Otherwise, try to schedule the fallback thread */
if (fallback != -1) {
EE->scheduleThread(getFirstSchedulableSymmetric(fallback));
return true;
}
return false;
}
int GenMCDriver::getFirstSchedulableSymmetric(int tid)
{
if (!getConf()->symmetryReduction)
return tid;
auto firstSched = tid;
auto symm = getSymmPredTid(tid);
while (symm != -1) {
if (isSchedulable(symm))
firstSched = symm;
symm = getSymmPredTid(symm);
}
return firstSched;
}
bool GenMCDriver::scheduleNextWFR()
{
auto &g = getGraph();
auto *EE = getEE();
/* First, schedule based on the EG */
for (auto i = 0u; i < g.getNumThreads(); i++) {
if (!isSchedulable(i))
continue;
if (g.containsPos(Event(i, EE->getThrById(i).globalInstructions + 1))) {
EE->scheduleThread(i);
return true;
}
}
std::vector<int> nonwrites;
std::vector<int> writes;
for (auto i = 0u; i < g.getNumThreads(); i++) {
if (!isSchedulable(i))
continue;
if (!isNextThreadInstLoad(i)) {
writes.push_back(i);
} else {
nonwrites.push_back(i);
}
}
std::vector<int> &selection = !writes.empty() ? writes : nonwrites;
if (selection.empty())
return false;
MyDist dist(0, selection.size() - 1);
auto candidate = selection[dist(rng)];
EE->scheduleThread(getFirstSchedulableSymmetric(static_cast<int>(candidate)));
return true;
}
bool GenMCDriver::scheduleNextRandom()
{
auto &g = getGraph();
auto *EE = getEE();
/* Check if randomize scheduling is enabled and schedule some thread */
MyDist dist(0, g.getNumThreads());
auto random = dist(rng);
for (auto j = 0u; j < g.getNumThreads(); j++) {
auto i = (j + random) % g.getNumThreads();
if (!isSchedulable(i))
continue;
/* Found a not-yet-complete thread; schedule it */
EE->scheduleThread(getFirstSchedulableSymmetric(static_cast<int>(i)));
return true;
}
/* No schedulable thread found */
return false;
}
void GenMCDriver::resetExplorationOptions()
{
unmoot();
setRescheduledRead(Event::getInit());
resetThreadPrioritization();
}
void GenMCDriver::handleExecutionStart()
{
const auto &g = getGraph();
/* Set-up (optimize) the interpreter for the new exploration */
for (auto i = 1u; i < g.getNumThreads(); i++) {
/* Skip not-yet-created threads */
BUG_ON(g.isThreadEmpty(i));
auto *labFst = g.getFirstThreadLabel(i);
auto parent = labFst->getParentCreate();
/* Skip if parent create does not exist yet (or anymore) */
if (!g.containsPos(parent) ||
!llvm::isa<ThreadCreateLabel>(g.getEventLabel(parent)))
continue;
/* Skip finished threads */
auto *labLast = g.getLastThreadLabel(i);
if (llvm::isa<ThreadFinishLabel>(labLast))
continue;
/* Skip the recovery thread, if it exists.
* It will be scheduled separately afterwards */
if (i == g.getRecoveryRoutineId())
continue;
/* Otherwise, initialize ECStacks in interpreter */
auto &thr = getEE()->getThrById(i);
BUG_ON(!thr.ECStack.empty());
thr.ECStack = thr.initEC;
}
}
std::pair<std::vector<SVal>, Event> GenMCDriver::extractValPrefix(Event pos)
{
auto &g = getGraph();
std::vector<SVal> vals;
Event last;
for (auto i = 0u; i < pos.index; i++) {
auto *lab = g.getEventLabel(Event(pos.thread, i));
if (auto *rLab = llvm::dyn_cast<ReadLabel>(lab)) {
auto *drLab = llvm::dyn_cast<DskReadLabel>(rLab);
vals.push_back(drLab ? getDskReadValue(drLab) : getReadValue(rLab));
last = lab->getPos();
} else if (auto *jLab = llvm::dyn_cast<ThreadJoinLabel>(lab)) {
vals.push_back(getJoinValue(jLab));
last = lab->getPos();
} else if (auto *bLab = llvm::dyn_cast<ThreadStartLabel>(lab)) {
vals.push_back(getStartValue(bLab));
last = lab->getPos();
} else if (auto *oLab = llvm::dyn_cast<OptionalLabel>(lab)) {
vals.push_back(SVal(oLab->isExpanded()));
last = lab->getPos();
} else {
BUG_ON(lab->hasValue());
}
}
return {vals, last};
}
Event findNextLabelToAdd(const ExecutionGraph &g, Event pos)
{
auto first = Event(pos.thread, 0);
auto it = std::find_if(po_succ_begin(g, first), po_succ_end(g, first),
[&](auto &lab) { return llvm::isa<EmptyLabel>(&lab); });
return it == po_succ_end(g, first) ? g.getLastThreadEvent(pos.thread).next() : it->getPos();
}
bool GenMCDriver::tryOptimizeScheduling(Event pos)
{
if (!getConf()->instructionCaching || inEstimationMode())
return false;
auto next = findNextLabelToAdd(getGraph(), pos);
auto [vals, last] = extractValPrefix(next);
auto *res = retrieveCachedSuccessors(pos.thread, vals);
if (res == nullptr || res->empty() || res->back()->getIndex() < next.index)
return false;
for (auto &vlab : *res) {
BUG_ON(vlab->hasStamp());
DriverHandlerDispatcher dispatcher(this);
dispatcher.visit(vlab);
if (llvm::isa<BlockLabel>(getGraph().getLastThreadLabel(vlab->getThread())) ||
isMoot() || getEE()->getCurThr().isBlocked() || isHalting())
return true;
}
return true;
}
void GenMCDriver::checkHelpingCasAnnotation()
{
/* If we were waiting for a helped CAS that did not appear, complain */
auto &g = getGraph();
for (auto i = 0U; i < g.getNumThreads(); i++) {
if (llvm::isa<HelpedCASBlockLabel>(g.getLastThreadLabel(i)))
ERROR("Helped/Helping CAS annotation error! Does helped CAS always "
"execute?\n");
}
/* Next, we need to check whether there are any extraneous
* stores, not visible to the helped/helping CAS */
auto hs = g.collectAllEvents(
[&](const EventLabel *lab) { return llvm::isa<HelpingCasLabel>(lab); });
if (hs.empty())
return;
for (auto &h : hs) {
auto *hLab = llvm::dyn_cast<HelpingCasLabel>(g.getEventLabel(h));
BUG_ON(!hLab);
/* Check that all stores that would make this helping
* CAS succeed are read by a helped CAS.
* We don't need to check the swap value of the helped CAS */
if (std::any_of(store_begin(g, hLab->getAddr()), store_end(g, hLab->getAddr()),
[&](auto &sLab) {
return hLab->getExpected() == sLab.getVal() &&
std::none_of(
sLab.readers_begin(), sLab.readers_end(),
[&](auto &rLab) {
return llvm::isa<HelpedCasReadLabel>(
&rLab);
});
}))
ERROR("Helped/Helping CAS annotation error! "
"Unordered store to helping CAS location!\n");
/* Special case for the initializer (as above) */
if (hLab->getAddr().isStatic() &&
hLab->getExpected() == getEE()->getLocInitVal(hLab->getAccess())) {
auto rs = g.collectAllEvents([&](const EventLabel *lab) {
auto *rLab = llvm::dyn_cast<ReadLabel>(lab);
return rLab && rLab->getAddr() == hLab->getAddr();
});
if (std::none_of(rs.begin(), rs.end(), [&](const Event &r) {
return llvm::isa<HelpedCasReadLabel>(g.getEventLabel(r));
}))
ERROR("Helped/Helping CAS annotation error! "
"Unordered store to helping CAS location!\n");
}
}
return;
}
#ifdef ENABLE_GENMC_DEBUG
void GenMCDriver::trackExecutionBound()
{
auto bound = bounder->calculate(getGraph());
result.exploredBounds.grow(bound);
result.exploredBounds[bound]++;
}
#endif
bool GenMCDriver::isExecutionBlocked() const
{
return std::any_of(
getEE()->threads_begin(), getEE()->threads_end(), [this](const llvm::Thread &thr) {
// FIXME: was thr.isBlocked()
auto &g = getGraph();
if (thr.id >= g.getNumThreads() || g.isThreadEmpty(thr.id)) // think rec
return false;
return llvm::isa<BlockLabel>(g.getLastThreadLabel(thr.id));
});
}
void GenMCDriver::updateStSpaceEstimation()
{
/* Calculate current sample */
auto &choices = getChoiceMap();
auto sample = std::accumulate(choices.begin(), choices.end(), 1.0L,
[](auto sum, auto &kv) { return sum *= kv.second.size(); });
/* This is the (i+1)-th exploration */
auto totalExplored = (long double)result.explored + result.exploredBlocked + 1L;
/* As the estimation might stop dynamically, we can't just
* normalize over the max samples to avoid overflows. Instead,
* use Welford's online algorithm to calculate mean and
* variance. */
auto prevM = result.estimationMean;
auto prevV = result.estimationVariance;
result.estimationMean += (sample - prevM) / totalExplored;
result.estimationVariance +=
(sample - prevM) / totalExplored * (sample - result.estimationMean) -
prevV / totalExplored;
}
void GenMCDriver::handleExecutionEnd()
{
if (isMoot()) {
GENMC_DEBUG(++result.exploredMoot;);
return;
}
/* Helper: Check helping CAS annotation */
if (getConf()->helper)
checkHelpingCasAnnotation();
/* If under estimation mode, guess the total.
* (This may run a few times, but that's OK.)*/
if (inEstimationMode()) {
updateStSpaceEstimation();
if (!shouldStopEstimating())
addToWorklist(0, std::make_unique<RerunForwardRevisit>());
}
/* Ignore the execution if some assume has failed */
if (isExecutionBlocked()) {
++result.exploredBlocked;
if (getConf()->printBlockedExecs)
printGraph();
if (getConf()->checkLiveness)
checkLiveness();
return;
}
if (fullExecutionExceedsBound())
++result.boundExceeding;
if (getConf()->printExecGraphs && !getConf()->persevere)
printGraph(); /* Delay printing if persevere is enabled */
GENMC_DEBUG(if (getConf()->boundsHistogram && !inEstimationMode()) trackExecutionBound(););
++result.explored;
}
void GenMCDriver::handleRecoveryStart()
{
if (isExecutionBlocked())
return;
auto &g = getGraph();
auto *EE = getEE();
/* Make sure that a thread for the recovery routine is
* added only once in the execution graph*/
if (g.getRecoveryRoutineId() == -1)
g.addRecoveryThread();
/* We will create a start label for the recovery thread.
* We synchronize with a persistency barrier, if one exists,
* otherwise, we synchronize with nothing */
auto tid = g.getRecoveryRoutineId();
auto psb = g.collectAllEvents(
[&](const EventLabel *lab) { return llvm::isa<DskPbarrierLabel>(lab); });
if (psb.empty())
psb.push_back(Event::getInit());
ERROR_ON(psb.size() > 1, "Usage of only one persistency barrier is allowed!\n");
auto tsLab = ThreadStartLabel::create(Event(tid, 0), psb.back(),
ThreadInfo(tid, psb.back().thread, 0, 0));
auto *lab = addLabelToGraph(std::move(tsLab));
/* Create a thread for the interpreter, and appropriately
* add it to the thread list (pthread_create() style) */
EE->createAddRecoveryThread(tid);
/* Finally, do all necessary preparations in the interpreter */
getEE()->setupRecoveryRoutine(tid);
return;
}
void GenMCDriver::handleRecoveryEnd()
{
/* Print the graph with the recovery routine */
if (getConf()->printExecGraphs)
printGraph();
getEE()->cleanupRecoveryRoutine(getGraph().getRecoveryRoutineId());
return;
}
void GenMCDriver::run()
{
/* Explore all graphs and print the results */
explore();
}
bool GenMCDriver::isHalting() const
{
auto *tp = getThreadPool();
return shouldHalt || (tp && tp->shouldHalt());
}
void GenMCDriver::halt(VerificationError status)
{
shouldHalt = true;
result.status = status;
if (getThreadPool())
getThreadPool()->halt();
}
GenMCDriver::Result GenMCDriver::verify(std::shared_ptr<const Config> conf,
std::unique_ptr<llvm::Module> mod,
std::unique_ptr<ModuleInfo> modInfo)
{
/* Spawn a single or multiple drivers depending on the configuration */
if (conf->threads == 1) {
auto driver = DriverFactory::create(conf, std::move(mod), std::move(modInfo));
driver->run();
return driver->getResult();
}
std::vector<std::future<GenMCDriver::Result>> futures;
{
/* Then, fire up the drivers */
ThreadPool pool(conf, mod, modInfo);
futures = pool.waitForTasks();
}
GenMCDriver::Result res;
for (auto &f : futures) {
res += f.get();
}
return res;
}
GenMCDriver::Result GenMCDriver::estimate(std::shared_ptr<const Config> conf,
const std::unique_ptr<llvm::Module> &mod,
const std::unique_ptr<ModuleInfo> &modInfo)
{
auto estCtx = std::make_unique<llvm::LLVMContext>();
auto newmod = LLVMModule::cloneModule(mod, estCtx);
auto newMI = modInfo->clone(*newmod);
auto driver = DriverFactory::create(conf, std::move(newmod), std::move(newMI),
GenMCDriver::EstimationMode{conf->estimationMax});
driver->run();
return driver->getResult();
}
void GenMCDriver::addToWorklist(Stamp stamp, WorkSet::ItemT item)
{
getWorkqueue()[stamp].add(std::move(item));
}
std::pair<Stamp, WorkSet::ItemT> GenMCDriver::getNextItem()
{
auto &workqueue = getWorkqueue();
for (auto rit = workqueue.rbegin(); rit != workqueue.rend(); ++rit) {
if (rit->second.empty()) {
continue;
}
return {rit->first, rit->second.getNext()};
}
return {0, nullptr};
}
/************************************************************
** Scheduling methods
***********************************************************/
void GenMCDriver::blockThread(std::unique_ptr<BlockLabel> bLab)
{
/* There are a couple of reasons we don't call Driver::addLabelToGraph() here:
* 1) It's redundant to update the views of the block label
* 2) If addLabelToGraph() does extra stuff (e.g., event caching) we absolutely
* don't want to do that here. blockThread() should be safe to call from
* anywhere in the code, with no unexpected side-effects */
getGraph().addLabelToGraph(std::move(bLab));
}
void GenMCDriver::blockThreadTryMoot(std::unique_ptr<BlockLabel> bLab)
{
auto pos = bLab->getPos();
blockThread(std::move(bLab));
mootExecutionIfFullyBlocked(pos);
}
void GenMCDriver::unblockThread(Event pos)
{
auto *bLab = getGraph().getLastThreadLabel(pos.thread);
BUG_ON(!llvm::isa<BlockLabel>(bLab));
getGraph().removeLast(pos.thread);
}
bool GenMCDriver::scheduleAtomicity()
{
auto *lastLab = getGraph().getEventLabel(lastAdded);
if (llvm::isa<FaiReadLabel>(lastLab)) {
getEE()->scheduleThread(lastAdded.thread);
return true;
}
if (auto *casLab = llvm::dyn_cast<CasReadLabel>(lastLab)) {
if (getReadValue(casLab) == casLab->getExpected()) {
getEE()->scheduleThread(lastAdded.thread);
return true;
}
}
return false;
}
bool GenMCDriver::scheduleNormal()
{
if (inEstimationMode())
return scheduleNextWFR();
switch (getConf()->schedulePolicy) {
case SchedulePolicy::ltr:
return scheduleNextLTR();
case SchedulePolicy::wf:
return scheduleNextWF();
case SchedulePolicy::wfr:
return scheduleNextWFR();
case SchedulePolicy::arbitrary:
return scheduleNextRandom();
default:
BUG();
}
BUG();
}
bool GenMCDriver::rescheduleReads()
{
auto &g = getGraph();
auto *EE = getEE();
for (auto i = 0u; i < g.getNumThreads(); ++i) {
auto *bLab = llvm::dyn_cast<ReadOptBlockLabel>(g.getLastThreadLabel(i));
if (!bLab)
continue;
BUG_ON(getConf()->bound.has_value());
setRescheduledRead(bLab->getPos());
unblockThread(bLab->getPos());
EE->scheduleThread(i);
return true;
}
return false;
}
bool GenMCDriver::scheduleNext()
{
if (isMoot() || isHalting())
return false;
auto &g = getGraph();
auto *EE = getEE();
/* 1. Ensure atomicity. This needs to here because of weird interactions with in-place
* revisiting and thread priotitization. For example, consider the following scenario:
* - restore @ T2, in-place rev @ T1, prioritize rev @ T1,
* restore FAIR @ T2, schedule T1, atomicity violation */
if (scheduleAtomicity())
return true;
/* Check if we should prioritize some thread */
if (schedulePrioritized())
return true;
/* Schedule the next thread according to the chosen policy */
if (scheduleNormal())
return true;
/* Finally, check if any reads needs to be rescheduled */
return rescheduleReads();
}
std::vector<ThreadInfo> createExecutionContext(const ExecutionGraph &g)
{
std::vector<ThreadInfo> tis;
for (auto i = 1u; i < g.getNumThreads(); i++) { // skip main
auto *bLab = g.getFirstThreadLabel(i);
BUG_ON(!bLab);
tis.push_back(bLab->getThreadInfo());
}
return tis;
}
void GenMCDriver::explore()
{
auto *EE = getEE();
resetExplorationOptions();
EE->setExecutionContext(createExecutionContext(getGraph()));
while (!isHalting()) {
EE->reset();
/* Get main program function and run the program */
EE->runAsMain(getConf()->programEntryFun);
if (getConf()->persevere)
EE->runRecovery();
auto validExecution = false;
while (!validExecution) {
/*
* restrictAndRevisit() might deem some execution infeasible,
* so we have to reset all exploration options before
* calling it again
*/
resetExplorationOptions();
auto [stamp, item] = getNextItem();
if (!item) {
if (popExecution())
continue;
return;
}
auto pos = item->getPos();
validExecution = restrictAndRevisit(stamp, item) && isRevisitValid(*item);
}
}
}
bool isUninitializedAccess(const SAddr &addr, const Event &pos)
{
return addr.isDynamic() && pos.isInitializer();
}
bool readsUninitializedMem(const ReadLabel *lab)
{
return isUninitializedAccess(lab->getAddr(), lab->getRf()->getPos());
}
bool GenMCDriver::isRevisitValid(const Revisit &revisit)
{
auto &g = getGraph();
auto pos = revisit.getPos();
auto *mLab = llvm::dyn_cast<MemAccessLabel>(g.getEventLabel(pos));
/* E.g., for optional revisits, do nothing */
if (!mLab)
return true;
if (!isExecutionValid(mLab))
return false;
auto *rLab = llvm::dyn_cast<ReadLabel>(mLab);
if (rLab && readsUninitializedMem(rLab)) {
reportError(pos, VerificationError::VE_UninitializedMem);
return false;
}
/* If an extra event is added, re-check consistency */
auto *nLab = g.getNextLabel(pos);
return !g.isRMWLoad(pos) ||
(isExecutionValid(nLab) && checkForRaces(nLab) == VerificationError::VE_OK);
}
bool GenMCDriver::isExecutionDrivenByGraph(const EventLabel *lab)
{
const auto &g = getGraph();
auto curr = lab->getPos();
auto replay = (curr.index < g.getThreadSize(curr.thread)) &&
!llvm::isa<EmptyLabel>(g.getEventLabel(curr));
if (!replay && !llvm::isa<MallocLabel>(lab) && !llvm::isa<ReadLabel>(lab))
cacheEventLabel(lab);
return replay;
}
bool GenMCDriver::executionExceedsBound(BoundCalculationStrategy strategy) const
{
if (!getConf()->bound.has_value() || inEstimationMode())
return false;
return bounder->doesExecutionExceedBound(getGraph(), *getConf()->bound, strategy);
}
bool GenMCDriver::fullExecutionExceedsBound() const
{
return executionExceedsBound(BoundCalculationStrategy::NonSlacked);
}
bool GenMCDriver::partialExecutionExceedsBound() const
{