-
Notifications
You must be signed in to change notification settings - Fork 435
/
Andersen.cpp
981 lines (852 loc) · 29.3 KB
/
Andersen.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
//===- Andersen.cpp -- Field-sensitive Andersen's analysis-------------------//
//
// SVF: Static Value-Flow Analysis
//
// Copyright (C) <2013-2017> <Yulei Sui>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
/*
* Andersen.cpp
*
* Created on: Nov 12, 2013
* Author: Yulei Sui
*/
#include "Util/Options.h"
#include "Graphs/CHG.h"
#include "Util/SVFUtil.h"
#include "MemoryModel/PointsTo.h"
#include "WPA/Andersen.h"
#include "WPA/Steensgaard.h"
using namespace SVF;
using namespace SVFUtil;
using namespace std;
u32_t AndersenBase::numOfProcessedAddr = 0;
u32_t AndersenBase::numOfProcessedCopy = 0;
u32_t AndersenBase::numOfProcessedGep = 0;
u32_t AndersenBase::numOfProcessedLoad = 0;
u32_t AndersenBase::numOfProcessedStore = 0;
u32_t AndersenBase::numOfSfrs = 0;
u32_t AndersenBase::numOfFieldExpand = 0;
u32_t AndersenBase::numOfSCCDetection = 0;
double AndersenBase::timeOfSCCDetection = 0;
double AndersenBase::timeOfSCCMerges = 0;
double AndersenBase::timeOfCollapse = 0;
u32_t AndersenBase::AveragePointsToSetSize = 0;
u32_t AndersenBase::MaxPointsToSetSize = 0;
double AndersenBase::timeOfProcessCopyGep = 0;
double AndersenBase::timeOfProcessLoadStore = 0;
double AndersenBase::timeOfUpdateCallGraph = 0;
/*!
* Destructor
*/
AndersenBase::~AndersenBase()
{
delete consCG;
consCG = nullptr;
}
/*!
* Initialize analysis
*/
void AndersenBase::initialize()
{
/// Build SVFIR
PointerAnalysis::initialize();
/// Create statistic class
stat = new AndersenStat(this);
/// Build Constraint Graph
consCG = new ConstraintGraph(pag);
setGraph(consCG);
if (Options::ConsCGDotGraph())
consCG->dump("consCG_initial");
}
/*!
* Finalize analysis
*/
void AndersenBase::finalize()
{
/// dump constraint graph if PAGDotGraph flag is enabled
if (Options::ConsCGDotGraph())
consCG->dump("consCG_final");
if (Options::PrintCGGraph())
consCG->print();
BVDataPTAImpl::finalize();
}
void AndersenBase::solveConstraints()
{
// Start solving constraints
DBOUT(DGENERAL, outs() << SVFUtil::pasMsg("Start Solving Constraints\n"));
bool limitTimerSet = SVFUtil::startAnalysisLimitTimer(Options::AnderTimeLimit());
initWorklist();
do
{
numOfIteration++;
if (0 == numOfIteration % iterationForPrintStat)
printStat();
reanalyze = false;
solveWorklist();
if (updateCallGraph(getIndirectCallsites()))
reanalyze = true;
}
while (reanalyze);
// Analysis is finished, reset the alarm if we set it.
SVFUtil::stopAnalysisLimitTimer(limitTimerSet);
DBOUT(DGENERAL, outs() << SVFUtil::pasMsg("Finish Solving Constraints\n"));
}
/*!
* Andersen analysis
*/
void AndersenBase::analyze()
{
if(!Options::ReadAnder().empty())
{
readPtsFromFile(Options::ReadAnder());
}
else
{
if(Options::WriteAnder().empty())
{
initialize();
solveConstraints();
finalize();
}
else
{
solveAndwritePtsToFile(Options::WriteAnder());
}
}
}
/*!
* Andersen analysis: read pointer analysis result from file
*/
void AndersenBase::readPtsFromFile(const std::string& filename)
{
initialize();
if (!filename.empty())
this->readFromFile(filename);
finalize();
}
/*!
* Andersen analysis: solve constraints and write pointer analysis result to file
*/
void AndersenBase:: solveAndwritePtsToFile(const std::string& filename)
{
/// Initialization for the Solver
initialize();
if (!filename.empty())
this->writeObjVarToFile(filename);
solveConstraints();
if (!filename.empty())
this->writeToFile(filename);
finalize();
}
void AndersenBase::cleanConsCG(NodeID id)
{
consCG->resetSubs(consCG->getRep(id));
for (NodeID sub: consCG->getSubs(id))
consCG->resetRep(sub);
consCG->resetSubs(id);
consCG->resetRep(id);
assert(!consCG->hasGNode(id) && "this is either a rep nodeid or a sub nodeid should have already been merged to its field-insensitive base! ");
}
bool AndersenBase::updateCallGraph(const CallSiteToFunPtrMap& callsites)
{
double cgUpdateStart = stat->getClk();
CallEdgeMap newEdges;
onTheFlyCallGraphSolve(callsites, newEdges);
NodePairSet cpySrcNodes; /// nodes as a src of a generated new copy edge
for (CallEdgeMap::iterator it = newEdges.begin(), eit = newEdges.end();
it != eit; ++it)
{
for (FunctionSet::iterator cit = it->second.begin(),
ecit = it->second.end();
cit != ecit; ++cit)
{
connectCaller2CalleeParams(it->first, *cit, cpySrcNodes);
}
}
bool hasNewForkEdges = updateThreadCallGraph(callsites, cpySrcNodes);
for (NodePairSet::iterator it = cpySrcNodes.begin(),
eit = cpySrcNodes.end();
it != eit; ++it)
{
pushIntoWorklist(it->first);
}
double cgUpdateEnd = stat->getClk();
timeOfUpdateCallGraph += (cgUpdateEnd - cgUpdateStart) / TIMEINTERVAL;
return ((!newEdges.empty()) || hasNewForkEdges);
}
bool AndersenBase::updateThreadCallGraph(const CallSiteToFunPtrMap& callsites,
NodePairSet& cpySrcNodes)
{
CallEdgeMap newForkEdges;
onTheFlyThreadCallGraphSolve(callsites, newForkEdges);
for (CallEdgeMap::iterator it = newForkEdges.begin(), eit = newForkEdges.end(); it != eit; it++)
{
for (FunctionSet::iterator cit = it->second.begin(),
ecit = it->second.end();
cit != ecit; ++cit)
{
connectCaller2ForkedFunParams(it->first, *cit, cpySrcNodes);
}
}
return !newForkEdges.empty();
}
/*!
* Connect formal and actual parameters for indirect forksites
*/
void AndersenBase::connectCaller2ForkedFunParams(const CallICFGNode* cs, const SVFFunction* F,
NodePairSet& cpySrcNodes)
{
assert(F);
DBOUT(DAndersen, outs() << "connect parameters from indirect forksite "
<< cs->valueOnlyToString() << " to forked function "
<< *F << "\n");
ThreadCallGraph *tdCallGraph = SVFUtil::dyn_cast<ThreadCallGraph>(callgraph);
const PAGNode *cs_arg = tdCallGraph->getThreadAPI()->getActualParmAtForkSite(cs);
const PAGNode *fun_arg = tdCallGraph->getThreadAPI()->getFormalParmOfForkedFun(F);
if(cs_arg->isPointer() && fun_arg->isPointer())
{
DBOUT(DAndersen, outs() << "process actual parm"
<< cs_arg->toString() << "\n");
NodeID srcAA = sccRepNode(cs_arg->getId());
NodeID dstFA = sccRepNode(fun_arg->getId());
if (addCopyEdge(srcAA, dstFA))
{
cpySrcNodes.insert(std::make_pair(srcAA, dstFA));
}
}
}
///*!
// * Connect formal and actual parameters for indirect callsites
// */
void AndersenBase::connectCaller2CalleeParams(const CallICFGNode* cs,
const SVFFunction* F, NodePairSet &cpySrcNodes)
{
assert(F);
DBOUT(DAndersen, outs() << "connect parameters from indirect callsite " << cs->valueOnlyToString() << " to callee " << *F << "\n");
const CallICFGNode* callBlockNode = cs;
const RetICFGNode* retBlockNode = cs->getRetICFGNode();
if(SVFUtil::isHeapAllocExtFunViaRet(F) && pag->callsiteHasRet(retBlockNode))
{
heapAllocatorViaIndCall(cs,cpySrcNodes);
}
if (pag->funHasRet(F) && pag->callsiteHasRet(retBlockNode))
{
const PAGNode* cs_return = pag->getCallSiteRet(retBlockNode);
const PAGNode* fun_return = pag->getFunRet(F);
if (cs_return->isPointer() && fun_return->isPointer())
{
NodeID dstrec = sccRepNode(cs_return->getId());
NodeID srcret = sccRepNode(fun_return->getId());
if(addCopyEdge(srcret, dstrec))
{
cpySrcNodes.insert(std::make_pair(srcret,dstrec));
}
}
else
{
DBOUT(DAndersen, outs() << "not a pointer ignored\n");
}
}
if (pag->hasCallSiteArgsMap(callBlockNode) && pag->hasFunArgsList(F))
{
// connect actual and formal param
const SVFIR::SVFVarList& csArgList = pag->getCallSiteArgsList(callBlockNode);
const SVFIR::SVFVarList& funArgList = pag->getFunArgsList(F);
//Go through the fixed parameters.
DBOUT(DPAGBuild, outs() << " args:");
SVFIR::SVFVarList::const_iterator funArgIt = funArgList.begin(), funArgEit = funArgList.end();
SVFIR::SVFVarList::const_iterator csArgIt = csArgList.begin(), csArgEit = csArgList.end();
for (; funArgIt != funArgEit; ++csArgIt, ++funArgIt)
{
//Some programs (e.g. Linux kernel) leave unneeded parameters empty.
if (csArgIt == csArgEit)
{
DBOUT(DAndersen, outs() << " !! not enough args\n");
break;
}
const PAGNode *cs_arg = *csArgIt ;
const PAGNode *fun_arg = *funArgIt;
if (cs_arg->isPointer() && fun_arg->isPointer())
{
DBOUT(DAndersen, outs() << "process actual parm " << cs_arg->toString() << " \n");
NodeID srcAA = sccRepNode(cs_arg->getId());
NodeID dstFA = sccRepNode(fun_arg->getId());
if(addCopyEdge(srcAA, dstFA))
{
cpySrcNodes.insert(std::make_pair(srcAA,dstFA));
}
}
}
//Any remaining actual args must be varargs.
if (F->isVarArg())
{
NodeID vaF = sccRepNode(pag->getVarargNode(F));
DBOUT(DPAGBuild, outs() << "\n varargs:");
for (; csArgIt != csArgEit; ++csArgIt)
{
const PAGNode *cs_arg = *csArgIt;
if (cs_arg->isPointer())
{
NodeID vnAA = sccRepNode(cs_arg->getId());
if (addCopyEdge(vnAA,vaF))
{
cpySrcNodes.insert(std::make_pair(vnAA,vaF));
}
}
}
}
if(csArgIt != csArgEit)
{
writeWrnMsg("too many args to non-vararg func.");
writeWrnMsg("(" + cs->getSourceLoc() + ")");
}
}
}
void AndersenBase::heapAllocatorViaIndCall(const CallICFGNode* cs, NodePairSet &cpySrcNodes)
{
assert(cs->getCalledFunction() == nullptr && "not an indirect callsite?");
const RetICFGNode* retBlockNode = cs->getRetICFGNode();
const PAGNode* cs_return = pag->getCallSiteRet(retBlockNode);
NodeID srcret;
CallSite2DummyValPN::const_iterator it = callsite2DummyValPN.find(cs);
if(it != callsite2DummyValPN.end())
{
srcret = sccRepNode(it->second);
}
else
{
NodeID valNode = pag->addDummyValNode();
NodeID objNode = pag->addDummyObjNode(cs->getType());
addPts(valNode,objNode);
callsite2DummyValPN.insert(std::make_pair(cs,valNode));
consCG->addConstraintNode(new ConstraintNode(valNode),valNode);
consCG->addConstraintNode(new ConstraintNode(objNode),objNode);
srcret = valNode;
}
NodeID dstrec = sccRepNode(cs_return->getId());
if(addCopyEdge(srcret, dstrec))
cpySrcNodes.insert(std::make_pair(srcret,dstrec));
}
void AndersenBase::normalizePointsTo()
{
SVFIR::MemObjToFieldsMap &memToFieldsMap = pag->getMemToFieldsMap();
SVFIR::NodeOffsetMap &GepObjVarMap = pag->getGepObjNodeMap();
// clear GepObjVarMap/memToFieldsMap/nodeToSubsMap/nodeToRepMap
// for redundant gepnodes and remove those nodes from pag
for (NodeID n: redundantGepNodes)
{
NodeID base = pag->getBaseObjVar(n);
GepObjVar *gepNode = SVFUtil::dyn_cast<GepObjVar>(pag->getGNode(n));
assert(gepNode && "Not a gep node in redundantGepNodes set");
const APOffset apOffset = gepNode->getConstantFieldIdx();
GepObjVarMap.erase(std::make_pair(base, apOffset));
memToFieldsMap[base].reset(n);
cleanConsCG(n);
pag->removeGNode(gepNode);
}
}
/*!
* Initialize analysis
*/
void Andersen::initialize()
{
resetData();
AndersenBase::initialize();
if (Options::ClusterAnder()) cluster();
/// Initialize worklist
processAllAddr();
}
/*!
* Finalize analysis
*/
void Andersen::finalize()
{
// TODO: check -stat too.
// TODO: broken
if (Options::ClusterAnder())
{
Map<std::string, std::string> stats;
const PTDataTy *ptd = getPTDataTy();
// TODO: should we use liveOnly?
// TODO: parameterise final arg.
NodeIDAllocator::Clusterer::evaluate(*PointsTo::getCurrentBestNodeMapping(), ptd->getAllPts(true), stats, true);
NodeIDAllocator::Clusterer::printStats("post-main", stats);
}
/// sanitize field insensitive obj
/// TODO: Fields has been collapsed during Andersen::collapseField().
// sanitizePts();
AndersenBase::finalize();
}
/*!
* Start constraint solving
*/
void Andersen::processNode(NodeID nodeId)
{
// sub nodes do not need to be processed
if (sccRepNode(nodeId) != nodeId)
return;
ConstraintNode* node = consCG->getConstraintNode(nodeId);
double insertStart = stat->getClk();
handleLoadStore(node);
double insertEnd = stat->getClk();
timeOfProcessLoadStore += (insertEnd - insertStart) / TIMEINTERVAL;
double propStart = stat->getClk();
handleCopyGep(node);
double propEnd = stat->getClk();
timeOfProcessCopyGep += (propEnd - propStart) / TIMEINTERVAL;
}
/*!
* Process copy and gep edges
*/
void Andersen::handleCopyGep(ConstraintNode* node)
{
NodeID nodeId = node->getId();
computeDiffPts(nodeId);
if (!getDiffPts(nodeId).empty())
{
for (ConstraintEdge* edge : node->getCopyOutEdges())
processCopy(nodeId, edge);
for (ConstraintEdge* edge : node->getGepOutEdges())
{
if (GepCGEdge* gepEdge = SVFUtil::dyn_cast<GepCGEdge>(edge))
processGep(nodeId, gepEdge);
}
}
}
/*!
* Process load and store edges
*/
void Andersen::handleLoadStore(ConstraintNode *node)
{
NodeID nodeId = node->getId();
for (PointsTo::iterator piter = getPts(nodeId).begin(), epiter =
getPts(nodeId).end(); piter != epiter; ++piter)
{
NodeID ptd = *piter;
// handle load
for (ConstraintNode::const_iterator it = node->outgoingLoadsBegin(),
eit = node->outgoingLoadsEnd(); it != eit; ++it)
{
if (processLoad(ptd, *it))
pushIntoWorklist(ptd);
}
// handle store
for (ConstraintNode::const_iterator it = node->incomingStoresBegin(),
eit = node->incomingStoresEnd(); it != eit; ++it)
{
if (processStore(ptd, *it))
pushIntoWorklist((*it)->getSrcID());
}
}
}
/*!
* Process address edges
*/
void Andersen::processAllAddr()
{
for (ConstraintGraph::const_iterator nodeIt = consCG->begin(), nodeEit = consCG->end(); nodeIt != nodeEit; nodeIt++)
{
ConstraintNode * cgNode = nodeIt->second;
for (ConstraintNode::const_iterator it = cgNode->incomingAddrsBegin(), eit = cgNode->incomingAddrsEnd();
it != eit; ++it)
processAddr(SVFUtil::cast<AddrCGEdge>(*it));
}
}
/*!
* Process address edges
*/
void Andersen::processAddr(const AddrCGEdge* addr)
{
numOfProcessedAddr++;
NodeID dst = addr->getDstID();
NodeID src = addr->getSrcID();
if(addPts(dst,src))
pushIntoWorklist(dst);
}
/*!
* Process load edges
* src --load--> dst,
* node \in pts(src) ==> node--copy-->dst
*/
bool Andersen::processLoad(NodeID node, const ConstraintEdge* load)
{
/// TODO: New copy edges are also added for black hole obj node to
/// make gcc in spec 2000 pass the flow-sensitive analysis.
/// Try to handle black hole obj in an appropriate way.
// if (pag->isBlkObjOrConstantObj(node))
if (pag->isConstantObj(node) || pag->getGNode(load->getDstID())->isPointer() == false)
return false;
numOfProcessedLoad++;
NodeID dst = load->getDstID();
return addCopyEdge(node, dst);
}
/*!
* Process store edges
* src --store--> dst,
* node \in pts(dst) ==> src--copy-->node
*/
bool Andersen::processStore(NodeID node, const ConstraintEdge* store)
{
/// TODO: New copy edges are also added for black hole obj node to
/// make gcc in spec 2000 pass the flow-sensitive analysis.
/// Try to handle black hole obj in an appropriate way
// if (pag->isBlkObjOrConstantObj(node))
if (pag->isConstantObj(node) || pag->getGNode(store->getSrcID())->isPointer() == false)
return false;
numOfProcessedStore++;
NodeID src = store->getSrcID();
return addCopyEdge(src, node);
}
/*!
* Process copy edges
* src --copy--> dst,
* union pts(dst) with pts(src)
*/
bool Andersen::processCopy(NodeID node, const ConstraintEdge* edge)
{
numOfProcessedCopy++;
assert((SVFUtil::isa<CopyCGEdge>(edge)) && "not copy/call/ret ??");
NodeID dst = edge->getDstID();
const PointsTo& srcPts = getDiffPts(node);
bool changed = unionPts(dst, srcPts);
if (changed)
pushIntoWorklist(dst);
return changed;
}
/*!
* Process gep edges
* src --gep--> dst,
* for each srcPtdNode \in pts(src) ==> add fieldSrcPtdNode into tmpDstPts
* union pts(dst) with tmpDstPts
*/
bool Andersen::processGep(NodeID, const GepCGEdge* edge)
{
const PointsTo& srcPts = getDiffPts(edge->getSrcID());
return processGepPts(srcPts, edge);
}
/*!
* Compute points-to for gep edges
*/
bool Andersen::processGepPts(const PointsTo& pts, const GepCGEdge* edge)
{
numOfProcessedGep++;
PointsTo tmpDstPts;
if (SVFUtil::isa<VariantGepCGEdge>(edge))
{
// If a pointer is connected by a variant gep edge,
// then set this memory object to be field insensitive,
// unless the object is a black hole/constant.
for (NodeID o : pts)
{
if (consCG->isBlkObjOrConstantObj(o))
{
tmpDstPts.set(o);
continue;
}
if (!isFieldInsensitive(o))
{
setObjFieldInsensitive(o);
consCG->addNodeToBeCollapsed(consCG->getBaseObjVar(o));
}
// Add the field-insensitive node into pts.
NodeID baseId = consCG->getFIObjVar(o);
tmpDstPts.set(baseId);
}
}
else if (const NormalGepCGEdge* normalGepEdge = SVFUtil::dyn_cast<NormalGepCGEdge>(edge))
{
// TODO: after the node is set to field insensitive, handling invariant
// gep edge may lose precision because offsets here are ignored, and the
// base object is always returned.
for (NodeID o : pts)
{
if (consCG->isBlkObjOrConstantObj(o) || isFieldInsensitive(o))
{
tmpDstPts.set(o);
continue;
}
NodeID fieldSrcPtdNode = consCG->getGepObjVar(o, normalGepEdge->getAccessPath().getConstantStructFldIdx());
tmpDstPts.set(fieldSrcPtdNode);
}
}
else
{
assert(false && "Andersen::processGepPts: New type GEP edge type?");
}
NodeID dstId = edge->getDstID();
if (unionPts(dstId, tmpDstPts))
{
pushIntoWorklist(dstId);
return true;
}
return false;
}
/**
* Detect and collapse PWC nodes produced by processing gep edges, under the constraint of field limit.
*/
inline void Andersen::collapsePWCNode(NodeID nodeId)
{
// If a node is a PWC node, collapse all its points-to target.
// collapseNodePts() may change the points-to set of the nodes which have been processed
// before, in this case, we may need to re-do the analysis.
if (consCG->isPWCNode(nodeId) && collapseNodePts(nodeId))
reanalyze = true;
}
inline void Andersen::collapseFields()
{
while (consCG->hasNodesToBeCollapsed())
{
NodeID node = consCG->getNextCollapseNode();
// collapseField() may change the points-to set of the nodes which have been processed
// before, in this case, we may need to re-do the analysis.
if (collapseField(node))
reanalyze = true;
}
}
/*
* Merge constraint graph nodes based on SCC cycle detected.
*/
void Andersen::mergeSccCycle()
{
NodeStack revTopoOrder;
NodeStack & topoOrder = getSCCDetector()->topoNodeStack();
while (!topoOrder.empty())
{
NodeID repNodeId = topoOrder.top();
topoOrder.pop();
revTopoOrder.push(repNodeId);
const NodeBS& subNodes = getSCCDetector()->subNodes(repNodeId);
// merge sub nodes to rep node
mergeSccNodes(repNodeId, subNodes);
}
// restore the topological order for later solving.
while (!revTopoOrder.empty())
{
NodeID nodeId = revTopoOrder.top();
revTopoOrder.pop();
topoOrder.push(nodeId);
}
}
/**
* Union points-to of subscc nodes into its rep nodes
* Move incoming/outgoing direct edges of sub node to rep node
*/
void Andersen::mergeSccNodes(NodeID repNodeId, const NodeBS& subNodes)
{
for (NodeBS::iterator nodeIt = subNodes.begin(); nodeIt != subNodes.end(); nodeIt++)
{
NodeID subNodeId = *nodeIt;
if (subNodeId != repNodeId)
{
mergeNodeToRep(subNodeId, repNodeId);
}
}
}
/**
* Collapse node's points-to set. Change all points-to elements into field-insensitive.
*/
bool Andersen::collapseNodePts(NodeID nodeId)
{
bool changed = false;
const PointsTo& nodePts = getPts(nodeId);
/// Points to set may be changed during collapse, so use a clone instead.
PointsTo ptsClone = nodePts;
for (PointsTo::iterator ptsIt = ptsClone.begin(), ptsEit = ptsClone.end(); ptsIt != ptsEit; ptsIt++)
{
if (isFieldInsensitive(*ptsIt))
continue;
if (collapseField(*ptsIt))
changed = true;
}
return changed;
}
/**
* Collapse field. make struct with the same base as nodeId become field-insensitive.
*/
bool Andersen::collapseField(NodeID nodeId)
{
/// Black hole doesn't have structures, no collapse is needed.
/// In later versions, instead of using base node to represent the struct,
/// we'll create new field-insensitive node. To avoid creating a new "black hole"
/// node, do not collapse field for black hole node.
if (consCG->isBlkObjOrConstantObj(nodeId))
return false;
bool changed = false;
double start = stat->getClk();
// set base node field-insensitive.
setObjFieldInsensitive(nodeId);
// replace all occurrences of each field with the field-insensitive node
NodeID baseId = consCG->getFIObjVar(nodeId);
NodeID baseRepNodeId = consCG->sccRepNode(baseId);
NodeBS & allFields = consCG->getAllFieldsObjVars(baseId);
for (NodeBS::iterator fieldIt = allFields.begin(), fieldEit = allFields.end(); fieldIt != fieldEit; fieldIt++)
{
NodeID fieldId = *fieldIt;
if (fieldId != baseId)
{
// use the reverse pts of this field node to find all pointers point to it
const NodeSet revPts = getRevPts(fieldId);
for (const NodeID o : revPts)
{
// change the points-to target from field to base node
clearPts(o, fieldId);
addPts(o, baseId);
pushIntoWorklist(o);
changed = true;
}
// merge field node into base node, including edges and pts.
NodeID fieldRepNodeId = consCG->sccRepNode(fieldId);
mergeNodeToRep(fieldRepNodeId, baseRepNodeId);
if (fieldId != baseRepNodeId)
{
// gep node fieldId becomes redundant if it is merged to its base node who is set as field-insensitive
// two node IDs should be different otherwise this field is actually the base and should not be removed.
redundantGepNodes.set(fieldId);
}
}
}
if (consCG->isPWCNode(baseRepNodeId))
if (collapseNodePts(baseRepNodeId))
changed = true;
double end = stat->getClk();
timeOfCollapse += (end - start) / TIMEINTERVAL;
return changed;
}
/*!
* SCC detection on constraint graph
*/
NodeStack& Andersen::SCCDetect()
{
numOfSCCDetection++;
double sccStart = stat->getClk();
WPAConstraintSolver::SCCDetect();
double sccEnd = stat->getClk();
timeOfSCCDetection += (sccEnd - sccStart)/TIMEINTERVAL;
double mergeStart = stat->getClk();
mergeSccCycle();
double mergeEnd = stat->getClk();
timeOfSCCMerges += (mergeEnd - mergeStart)/TIMEINTERVAL;
return getSCCDetector()->topoNodeStack();
}
/*!
* merge nodeId to newRepId. Return true if the newRepId is a PWC node
*/
bool Andersen::mergeSrcToTgt(NodeID nodeId, NodeID newRepId)
{
if(nodeId==newRepId)
return false;
/// union pts of node to rep
updatePropaPts(newRepId, nodeId);
unionPts(newRepId,nodeId);
/// move the edges from node to rep, and remove the node
ConstraintNode* node = consCG->getConstraintNode(nodeId);
bool pwc = consCG->moveEdgesToRepNode(node, consCG->getConstraintNode(newRepId));
/// 1. if find gep edges inside SCC cycle, the rep node will become a PWC node and
/// its pts should be collapsed later.
/// 2. if the node to be merged is already a PWC node, the rep node will also become
/// a PWC node as it will have a self-cycle gep edge.
if(node->isPWCNode())
pwc = true;
/// set rep and sub relations
updateNodeRepAndSubs(node->getId(),newRepId);
consCG->removeConstraintNode(node);
return pwc;
}
/*
* Merge a node to its rep node based on SCC detection
*/
void Andersen::mergeNodeToRep(NodeID nodeId,NodeID newRepId)
{
if (mergeSrcToTgt(nodeId,newRepId))
consCG->setPWCNode(newRepId);
}
/*
* Updates subnodes of its rep, and rep node of its subs
*/
void Andersen::updateNodeRepAndSubs(NodeID nodeId, NodeID newRepId)
{
consCG->setRep(nodeId,newRepId);
NodeBS repSubs;
repSubs.set(nodeId);
/// update nodeToRepMap, for each subs of current node updates its rep to newRepId
// update nodeToSubsMap, union its subs with its rep Subs
NodeBS& nodeSubs = consCG->sccSubNodes(nodeId);
for(NodeBS::iterator sit = nodeSubs.begin(), esit = nodeSubs.end(); sit!=esit; ++sit)
{
NodeID subId = *sit;
consCG->setRep(subId,newRepId);
}
repSubs |= nodeSubs;
consCG->setSubs(newRepId,repSubs);
consCG->resetSubs(nodeId);
}
void Andersen::cluster(void) const
{
assert(Options::MaxFieldLimit() == 0 && "Andersen::cluster: clustering for Andersen's is currently only supported in field-insensitive analysis");
Steensgaard *steens = Steensgaard::createSteensgaard(pag);
std::vector<std::pair<unsigned, unsigned>> keys;
for (SVFIR::iterator pit = pag->begin(); pit != pag->end(); ++pit)
{
keys.push_back(std::make_pair(pit->first, 1));
}
std::vector<std::pair<hclust_fast_methods, std::vector<NodeID>>> candidates;
PointsTo::MappingPtr nodeMapping =
std::make_shared<std::vector<NodeID>>(NodeIDAllocator::Clusterer::cluster(steens, keys, candidates, "aux-steens"));
PointsTo::MappingPtr reverseNodeMapping =
std::make_shared<std::vector<NodeID>>(NodeIDAllocator::Clusterer::getReverseNodeMapping(*nodeMapping));
PointsTo::setCurrentBestNodeMapping(nodeMapping, reverseNodeMapping);
}
/*!
* Print pag nodes' pts by an ascending order
*/
void Andersen::dumpTopLevelPtsTo()
{
for (OrderedNodeSet::iterator nIter = this->getAllValidPtrs().begin();
nIter != this->getAllValidPtrs().end(); ++nIter)
{
const PAGNode* node = getPAG()->getGNode(*nIter);
if (getPAG()->isValidTopLevelPtr(node))
{
const PointsTo& pts = this->getPts(node->getId());
outs() << "\nNodeID " << node->getId() << " ";
if (pts.empty())
{
outs() << "\t\tPointsTo: {empty}\n";
}
else
{
outs() << "\t\tPointsTo: { ";
multiset<u32_t> line;
for (PointsTo::iterator it = pts.begin(), eit = pts.end();
it != eit; ++it)
{
line.insert(*it);
}
for (multiset<u32_t>::const_iterator it = line.begin(); it != line.end(); ++it)
{
if(Options::PrintFieldWithBasePrefix())
if (auto gepNode = SVFUtil::dyn_cast<GepObjVar>(pag->getGNode(*it)))
outs() << gepNode->getBaseNode() << "_" << gepNode->getConstantFieldIdx() << " ";
else
outs() << *it << " ";
else
outs() << *it << " ";
}
outs() << "}\n";
}
}
}
outs().flush();
}