forked from facebook/hhvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdce.cpp
More file actions
1156 lines (1098 loc) · 29 KB
/
Copy pathdce.cpp
File metadata and controls
1156 lines (1098 loc) · 29 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
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/dce.h"
#include <array>
#include <folly/MapUtil.h>
#include "hphp/util/low-ptr.h"
#include "hphp/util/match.h"
#include "hphp/util/trace.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/runtime/vm/jit/analysis.h"
#include "hphp/runtime/vm/jit/cfg.h"
#include "hphp/runtime/vm/jit/check.h"
#include "hphp/runtime/vm/jit/id-set.h"
#include "hphp/runtime/vm/jit/ir-opcode.h"
#include "hphp/runtime/vm/jit/ir-unit.h"
#include "hphp/runtime/vm/jit/mutation.h"
#include "hphp/runtime/vm/jit/memory-effects.h"
#include "hphp/runtime/vm/jit/opt.h"
#include "hphp/runtime/vm/jit/print.h"
#include "hphp/runtime/vm/jit/simple-propagation.h"
#include "hphp/runtime/vm/jit/state-vector.h"
#include "hphp/runtime/vm/jit/timer.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
namespace HPHP { namespace jit {
namespace {
TRACE_SET_MOD(hhir_dce);
bool canDCE(IRInstruction* inst) {
switch (inst->op()) {
case AssertNonNull:
case AssertType:
case AbsDbl:
case AddInt:
case SubInt:
case MulInt:
case AndInt:
case AddDbl:
case SubDbl:
case MulDbl:
case Sqrt:
case OrInt:
case XorInt:
case Shl:
case Shr:
case Lshr:
case Floor:
case Ceil:
case XorBool:
case Mod:
case ConvDblToBool:
case ConvIntToBool:
case ConvStrToBool:
case ConvArrToDbl:
case ConvBoolToDbl:
case ConvIntToDbl:
case ConvStrToDbl:
case ConvResToDbl:
case ConvBoolToInt:
case ConvDblToInt:
case ConvStrToInt:
case ConvResToInt:
case ConvDblToStr:
case ConvIntToStr:
case DblAsBits:
case ConvPtrToLval:
case NewColFromArray:
case GtInt:
case GteInt:
case LtInt:
case LteInt:
case EqInt:
case NeqInt:
case CmpInt:
case GtDbl:
case GteDbl:
case LtDbl:
case LteDbl:
case EqDbl:
case NeqDbl:
case CmpDbl:
case GtStr:
case GteStr:
case LtStr:
case LteStr:
case EqStr:
case NeqStr:
case SameStr:
case NSameStr:
case CmpStr:
case GtStrInt:
case GteStrInt:
case LtStrInt:
case LteStrInt:
case EqStrInt:
case NeqStrInt:
case CmpStrInt:
case GtBool:
case GteBool:
case LtBool:
case LteBool:
case EqBool:
case NeqBool:
case CmpBool:
case SameObj:
case NSameObj:
case EqKeyset:
case NeqKeyset:
case SameKeyset:
case NSameKeyset:
case GtRes:
case GteRes:
case LtRes:
case LteRes:
case EqRes:
case NeqRes:
case CmpRes:
case EqRecDesc:
case EqCls:
case EqFunc:
case EqStrPtr:
case EqArrayDataPtr:
case HasReifiedGenerics:
case InstanceOf:
case InstanceOfIface:
case InstanceOfIfaceVtable:
case ExtendsClass:
case InstanceOfBitmask:
case NInstanceOfBitmask:
case InstanceOfRecDesc:
case InterfaceSupportsArr:
case InterfaceSupportsVec:
case InterfaceSupportsDict:
case InterfaceSupportsKeyset:
case InterfaceSupportsStr:
case InterfaceSupportsInt:
case InterfaceSupportsDbl:
case HasToString:
case IsType:
case IsNType:
case IsTypeMem:
case IsNTypeMem:
case IsWaitHandle:
case IsCol:
case LdStk:
case LdLoc:
case LdStkAddr:
case LdLocAddr:
case LdRDSAddr:
case LdMem:
case LdContField:
case LdClsInitElem:
case LdIterBase:
case LdIterPos:
case LdIterEnd:
case LdFrameThis:
case LdFrameCls:
case LdSmashable:
case LdSmashableFunc:
case LdClsFromClsMeth:
case LdFuncFromClsMeth:
case LdClsFromRClsMeth:
case LdFuncFromRClsMeth:
case LdGenericsFromRClsMeth:
case LdFuncFromRFunc:
case LdGenericsFromRFunc:
case LdRecDesc:
case DefConst:
case Conjure:
case LdClsInitData:
case LookupClsRDS:
case LdClsMethodCacheCls:
case LdFuncVecLen:
case LdClsMethod:
case LdIfaceMethod:
case LdPropAddr:
case LdObjClass:
case LdClsName:
case LdARNumParams:
case LdFuncCls:
case LdFuncNumParams:
case LdFuncName:
case LdMethCallerName:
case LdStrLen:
case LdVecElem:
case LdPackedElem:
case LdPackedArrayDataElemAddr:
case NewInstanceRaw:
case NewDArray:
case NewDictArray:
case NewCol:
case NewPair:
case NewRFunc:
case NewRClsMeth:
case DefCallFlags:
case DefCallFunc:
case DefCallNumArgs:
case DefCallCtx:
case LdRetVal:
case Mov:
case CountArray:
case CountVec:
case CountDict:
case CountKeyset:
case CountCollection:
case Nop:
case AKExistsArr:
case AKExistsDict:
case AKExistsKeyset:
case LdBindAddr:
case LdSwitchDblIndex:
case LdSwitchStrIndex:
case LdSSwitchDestFast:
case LdClosureCls:
case LdClosureThis:
case CreateSSWH:
case LdContActRec:
case LdContArValue:
case LdContArKey:
case LdWHState:
case LdWHResult:
case LdWHNotDone:
case LdAFWHActRec:
case LdMIStateAddr:
case StringIsset:
case ColIsEmpty:
case ColIsNEmpty:
case LdUnwinderValue:
case LdColVec:
case LdColDict:
case OrdStr:
case ChrInt:
case CheckRange:
case LdMBase:
case MethodExists:
case LdTVAux:
case ArrayIdx:
case ArrayIsset:
case DictGetQuiet:
case DictGetK:
case DictIsset:
case DictIdx:
case KeysetGetQuiet:
case KeysetGetK:
case KeysetIsset:
case KeysetIdx:
case VecFirst:
case VecLast:
case DictFirst:
case DictFirstKey:
case DictLast:
case DictLastKey:
case KeysetFirst:
case KeysetLast:
case GetTime:
case GetTimeNs:
case Select:
case LdARFlags:
case FuncHasAttr:
case IsFunReifiedGenericsMatched:
case IsClsDynConstructible:
case LdFuncRxLevel:
case StrictlyIntegerConv:
case SetLegacyDict:
case SetLegacyVec:
case GetMemoKeyScalar:
case LookupSPropSlot:
case ConstructClosure:
case AllocStructDArray:
case AllocStructDict:
case AllocVArray:
case AllocVec:
case GetMixedPtrIter:
case GetPackedPtrIter:
case AdvanceMixedPtrIter:
case AdvancePackedPtrIter:
case LdPtrIterKey:
case LdPtrIterVal:
case EqPtrIter:
assertx(!inst->isControlFlow());
return true;
// These may raise oom, but its still ok to delete them if the
// result is unused
case ConcatIntStr:
case ConcatStrInt:
case ConcatStrStr:
case ConcatStr3:
case ConcatStr4:
case AddNewElem:
case AddNewElemKeyset:
case AddNewElemVec:
return true;
// Some of these conversion functions can run arbitrary PHP code.
case ConvObjToDbl:
case ConvTVToDbl:
case ConvObjToInt:
case ConvTVToInt:
case ConvTVToBool:
case ConvObjToBool:
case ConvObjToStr:
case ConvResToStr:
case ConvTVToStr:
case ConvArrToVec:
case ConvDictToVec:
case ConvKeysetToVec:
case ConvObjToVec:
case ConvArrToDict:
case ConvVecToDict:
case ConvKeysetToDict:
case ConvObjToDict:
case ConvArrToKeyset:
case ConvVecToKeyset:
case ConvDictToKeyset:
case ConvObjToKeyset:
case ConvArrToVArr:
case ConvVecToVArr:
case ConvDictToVArr:
case ConvKeysetToVArr:
case ConvObjToVArr:
case ConvArrToDArr:
case ConvVecToDArr:
case ConvDictToDArr:
case ConvKeysetToDArr:
case ConvObjToDArr:
case LdOutAddr:
return !opcodeMayRaise(inst->op()) &&
(!inst->consumesReferences() || inst->producesReference());
case ConvClsMethToDArr:
case ConvClsMethToDict:
case ConvClsMethToKeyset:
case ConvClsMethToVArr:
case ConvClsMethToVec: {
bool consumeRef = use_lowptr ? false : inst->consumesReferences();
return !opcodeMayRaise(inst->op()) &&
(!consumeRef || inst->producesReference());
}
case DbgTraceCall:
case AKExistsObj:
case StStk:
case StOutValue:
case CheckIter:
case CheckType:
case CheckNullptr:
case CheckTypeMem:
case CheckMixedArrayKeys:
case CheckSmashableClass:
case CheckLoc:
case CheckStk:
case CheckMBase:
case AssertLoc:
case AssertStk:
case AssertMBase:
case CheckImplicitContextNull:
case CheckInit:
case CheckInitMem:
case CheckCold:
case CheckInOuts:
case EndGuards:
case CheckNonNull:
case DivDbl:
case DivInt:
case AddIntO:
case SubIntO:
case MulIntO:
case GtObj:
case GteObj:
case LtObj:
case LteObj:
case EqObj:
case NeqObj:
case CmpObj:
case GtArr:
case GteArr:
case LtArr:
case LteArr:
case EqArr:
case NeqArr:
case CmpArr:
case GtVec:
case GteVec:
case LtVec:
case LteVec:
case EqVec:
case NeqVec:
case CmpVec:
case EqDict:
case NeqDict:
case JmpZero:
case JmpNZero:
case JmpSSwitchDest:
case JmpSwitchDest:
case ProfileSwitchDest:
case CheckSurpriseFlags:
case CheckSurpriseAndStack:
case HandleRequestSurprise:
case ReturnHook:
case SuspendHookAwaitEF:
case SuspendHookAwaitEG:
case SuspendHookAwaitR:
case SuspendHookCreateCont:
case SuspendHookYield:
case EndBlock:
case Unreachable:
case Jmp:
case DefLabel:
case LdLocPseudoMain:
case LdPairElem:
case DefCls:
case LdClsCtor:
case LdCls:
case LdClsCached:
case LdClsCachedSafe:
case LdClsTypeCns:
case LdClsTypeCnsClsName:
case LdRecDescCached:
case LdRecDescCachedSafe:
case LdCns:
case IsTypeStructCached:
case LookupCnsE:
case LdClsCns:
case InitClsCns:
case LdSubClsCns:
case LdSubClsCnsClsName:
case LdTypeCns:
case CheckSubClsCns:
case LdClsCnsVecLen:
case LookupClsMethodFCache:
case LookupClsMethodCache:
case LookupClsMethod:
case LdGblAddr:
case LdGblAddrDef:
case LdClsPropAddrOrNull:
case LdClsPropAddrOrRaise:
case LdInitRDSAddr:
case LdInitPropAddr:
case LdObjMethodD:
case LdObjMethodS:
case LdObjInvoke:
case LdFunc:
case LdFuncCached:
case LookupFuncCached:
case AllocObj:
case AllocObjReified:
case NewClsMeth:
case FuncCred:
case InitProps:
case PropTypeRedefineCheck:
case InitSProps:
case InitObjProps:
case InitObjMemoSlots:
case LockObj:
case DebugBacktrace:
case DebugBacktraceFast:
case InitThrowableFileAndLine:
case ConstructInstance:
case InitMixedLayoutArray:
case InitPackedLayoutArray:
case InitPackedLayoutArrayLoop:
case NewKeysetArray:
case NewRecord:
case NewStructDArray:
case NewStructDict:
case Clone:
case InlineReturn:
case InlineCall:
case CallUnpack:
case Call:
case NativeImpl:
case CallBuiltin:
case RetCtrl:
case AsyncFuncRet:
case AsyncFuncRetSlow:
case AsyncSwitchFast:
case GenericRetDecRefs:
case StClsInitElem:
case StMem:
case StImplicitContext:
case StIterBase:
case StIterType:
case StIterEnd:
case StIterPos:
case StLoc:
case StLocPseudoMain:
case StLocRange:
case EagerSyncVMRegs:
case ReqBindJmp:
case ReqRetranslate:
case ReqRetranslateOpt:
case IncRef:
case DecRef:
case DecRefNZ:
case ProfileDecRef:
case DefFP:
case DefFuncEntryFP:
case DefFrameRelSP:
case DefRegSP:
case Count:
case VerifyParamCls:
case VerifyParamCallable:
case VerifyParamFail:
case VerifyParamFailHard:
case VerifyReifiedLocalType:
case VerifyReifiedReturnType:
case VerifyRetCallable:
case VerifyRetCls:
case VerifyRetFail:
case VerifyRetFailHard:
case VerifyProp:
case VerifyPropAll:
case VerifyPropCls:
case VerifyPropCoerce:
case VerifyPropCoerceAll:
case VerifyPropFail:
case VerifyPropFailHard:
case VerifyParamRecDesc:
case VerifyRetRecDesc:
case VerifyPropRecDesc:
case RaiseClsMethPropConvertNotice:
case RaiseUninitLoc:
case RaiseUndefProp:
case RaiseTooManyArg:
case RaiseError:
case RaiseErrorOnInvalidIsAsExpressionType:
case RaiseWarning:
case RaiseNotice:
case ThrowArrayIndexException:
case ThrowArrayKeyException:
case RaiseArraySerializeNotice:
case RaiseHackArrCompatNotice:
case RaiseForbiddenDynCall:
case RaiseForbiddenDynConstruct:
case RaiseRxCallViolation:
case RaiseStrToClassNotice:
case CheckClsMethFunc:
case CheckClsReifiedGenericMismatch:
case CheckFunReifiedGenericMismatch:
case PrintStr:
case PrintInt:
case PrintBool:
case GetMemoKey:
case LdSwitchObjIndex:
case LdSSwitchDestSlow:
case InterpOne:
case InterpOneCF:
case OODeclExists:
case StClosureArg:
case CreateGen:
case CreateAGen:
case CreateAAWH:
case CreateAFWH:
case CreateAGWH:
case AFWHPrepareChild:
case StArResumeAddr:
case ContEnter:
case ContPreNext:
case ContStartedCheck:
case ContValid:
case ContStarted:
case ContArIncKey:
case ContArIncIdx:
case ContArUpdateIdx:
case LdContResumeAddr:
case StContArState:
case StContArValue:
case StContArKey:
case AFWHBlockOn:
case AFWHPushTailFrame:
case CountWHNotDone:
case IncStat:
case IncProfCounter:
case IncCallCounter:
case DbgAssertRefCount:
case DbgAssertFunc:
case DbgCheckLocalsDecRefd:
case RBTraceEntry:
case RBTraceMsg:
case ZeroErrorLevel:
case RestoreErrorLevel:
case IterInit:
case IterInitK:
case LIterInit:
case LIterInitK:
case IterNext:
case IterNextK:
case LIterNext:
case LIterNextK:
case IterFree:
case KillIter:
case BaseG:
case PropX:
case PropQ:
case PropDX:
case CGetProp:
case CGetPropQ:
case SetProp:
case UnsetProp:
case SetOpProp:
case IncDecProp:
case IssetProp:
case ElemX:
case ProfileMixedArrayAccess:
case CheckMixedArrayOffset:
case CheckMissingKeyInArrLike:
case CheckArrayCOW:
case ProfileDictAccess:
case CheckDictOffset:
case ProfileKeysetAccess:
case CheckKeysetOffset:
case ElemArrayD:
case ElemArrayU:
case ElemMixedArrayK:
case ElemVecD:
case ElemVecU:
case ElemDictD:
case ElemDictU:
case ElemDictK:
case ElemKeysetU:
case ElemKeysetK:
case ElemDX:
case ElemUX:
case ArrayGet:
case MixedArrayGetK:
case DictGet:
case KeysetGet:
case StringGet:
case OrdStrIdx:
case MapGet:
case CGetElem:
case ArraySet:
case VecSet:
case DictSet:
case MapSet:
case VectorSet:
case SetElem:
case SetRange:
case SetRangeRev:
case UnsetElem:
case SetOpElem:
case IncDecElem:
case SetNewElem:
case SetNewElemArray:
case SetNewElemVec:
case SetNewElemKeyset:
case ReservePackedArrayDataNewElem:
case VectorIsset:
case PairIsset:
case MapIsset:
case IssetElem:
case ProfileType:
case ProfileCall:
case ProfileMethod:
case ProfileSubClsCns:
case CheckPackedArrayDataBounds:
case LdVectorSize:
case BeginCatch:
case EndCatch:
case EnterTCUnwind:
case UnwindCheckSideExit:
case DbgTrashStk:
case DbgTrashFrame:
case DbgTrashMem:
case DbgTrashRetVal:
case EnterPrologue:
case CheckStackOverflow:
case CheckSurpriseFlagsEnter:
case JmpPlaceholder:
case ThrowOutOfBounds:
case ThrowInvalidArrayKey:
case ThrowInvalidOperation:
case ThrowCallReifiedFunctionWithoutGenerics:
case ThrowDivisionByZeroException:
case ThrowHasThisNeedStatic:
case ThrowLateInitPropError:
case ThrowMissingArg:
case ThrowMissingThis:
case ThrowParameterWrongType:
case ThrowParamInOutMismatch:
case ThrowParamInOutMismatchRange:
case StMBase:
case FinishMemberOp:
case BeginInlining:
case EndInlining:
case SyncReturnBC:
case SetOpTV:
case OutlineSetOp:
case ConjureUse:
case LdClsMethodFCacheFunc:
case LdClsMethodCacheFunc:
case ProfileInstanceCheck:
case MemoGetStaticValue:
case MemoGetStaticCache:
case MemoGetLSBValue:
case MemoGetLSBCache:
case MemoGetInstanceValue:
case MemoGetInstanceCache:
case MemoSetStaticValue:
case MemoSetStaticCache:
case MemoSetLSBValue:
case MemoSetLSBCache:
case MemoSetInstanceValue:
case MemoSetInstanceCache:
case ThrowAsTypeStructException:
case RecordReifiedGenericsAndGetTSList:
case ResolveTypeStruct:
case CheckRDSInitialized:
case MarkRDSInitialized:
case ProfileProp:
case ProfileIsTypeStruct:
case StFrameCtx:
case StFrameFunc:
case StFrameMeta:
return false;
case SameArr:
case NSameArr:
case SameVec:
case NSameVec:
case SameDict:
case NSameDict:
case IsTypeStruct:
return !opcodeMayRaise(inst->op());
}
not_reached();
}
/* DceFlags tracks the state of one instruction during dead code analysis. */
struct DceFlags {
DceFlags()
: m_state(DEAD)
{}
bool isDead() const { return m_state == DEAD; }
void setDead() { m_state = DEAD; }
void setLive() { m_state = LIVE; }
std::string toString() const {
std::array<const char*,2> const names = {{
"DEAD",
"LIVE",
}};
return folly::format(
"{}",
m_state < names.size() ? names[m_state] : "<invalid>"
).str();
}
private:
enum {
DEAD = 0,
LIVE,
};
uint8_t m_state:1;
};
static_assert(sizeof(DceFlags) == 1, "sizeof(DceFlags) should be 1 byte");
// DCE state indexed by instr->id().
typedef StateVector<IRInstruction, DceFlags> DceState;
typedef StateVector<SSATmp, uint32_t> UseCounts;
typedef jit::vector<IRInstruction*> WorkList;
void removeDeadInstructions(IRUnit& unit, const DceState& state) {
postorderWalk(
unit,
[&](Block* block) {
auto const next = block->next();
auto const bcctx = block->back().bcctx();
block->remove_if(
[&] (const IRInstruction& inst) {
ONTRACE(
4,
if (state[inst].isDead()) {
FTRACE(1, "Removing dead instruction {}\n", inst.toString());
}
);
auto const dead = state[inst].isDead();
assertx(!dead || !inst.taken() || inst.taken()->isCatch());
return dead;
}
);
if (block->empty() || !block->back().isBlockEnd()) {
assertx(next);
block->push_back(unit.gen(Jmp, bcctx, next));
}
}
);
}
// removeUnreachable erases unreachable blocks from unit, and returns
// a sorted list of the remaining blocks.
BlockList prepareBlocks(IRUnit& unit) {
FTRACE(1, "RemoveUnreachable:vvvvvvvvvvvvvvvvvvvv\n");
SCOPE_EXIT { FTRACE(1, "RemoveUnreachable:^^^^^^^^^^^^^^^^^^^^\n"); };
auto const blocks = rpoSortCfg(unit);
// 1. perform copy propagation on every instruction
for (auto block : blocks) {
for (auto& inst : *block) {
copyProp(&inst);
}
}
// 2. erase unreachable blocks and get an rpo sorted list of what remains.
bool needsReflow = removeUnreachable(unit);
// 3. if we removed any whole blocks that ended in Jmp instructions, reflow
// all types in case they change the incoming types of DefLabel
// instructions.
if (needsReflow) reflowTypes(unit);
return blocks;
}
WorkList initInstructions(const IRUnit& unit, const BlockList& blocks,
DceState& state) {
TRACE(1, "DCE(initInstructions):vvvvvvvvvvvvvvvvvvvv\n");
// Mark reachable, essential, instructions live and enqueue them.
WorkList wl;
wl.reserve(unit.numInsts());
forEachInst(blocks, [&] (IRInstruction* inst) {
if (!canDCE(inst)) {
state[inst].setLive();
wl.push_back(inst);
}
});
TRACE(1, "DCE:^^^^^^^^^^^^^^^^^^^^\n");
return wl;
}
//////////////////////////////////////////////////////////////////////
void processCatchBlock(IRUnit& unit, DceState& state, Block* block,
FPRelOffset stackTop, const UseCounts& uses) {
using Bits = std::bitset<64>;
auto const stackSize = (stackTop.offset < -64) ? 64 : -stackTop.offset;
if (stackSize == 0) return;
auto const stackBase = stackTop + stackSize;
// subtract 1 because we want the cells at offsets -1, -2, ... -stackSize
auto const stackRange = AStack { stackBase - 1, stackSize };
Bits usedLocations = {};
// stores that are only read by the EndCatch
jit::fast_set<IRInstruction*> candidateStores;
// Any IncRefs we see; if they correspond to stores above, we can
// replace the store with a store of Null, and kill the IncRef.
jit::fast_map<SSATmp*, std::vector<Block::iterator>> candidateIncRefs;
auto const range =
[&] (const AliasClass& cls) -> std::pair<int, int> {
if (!cls.maybe(stackRange)) return {};
auto const stk = cls.stack();
if (!stk) return { 0, stackSize };
if (stk->offset < stackTop) {
auto const delta = stackTop.offset - stk->offset.offset;
if (delta >= stk->size) return {};
return { 0, stk->size - delta };
}
auto const base = stk->offset.offset - stackTop.offset;
if (base >= stackSize) return {};
auto const end = base + stk->size < stackSize ?
base + stk->size : stackSize;
return { base, end };
};
auto const process_stack =
[&] (const AliasClass& cls) {
auto r = range(cls);
while (r.first < r.second) {
usedLocations.set(r.first++);
}
return false;
};
auto const do_store =
[&] (const AliasClass& cls, IRInstruction* store) {
if (!store->is(StStk)) return false;
auto const stk = cls.is_stack();
if (!stk) return process_stack(cls);
auto const r = range(cls);
if (r.first != r.second) {
assertx(r.second == r.first + 1);
if (!usedLocations.test(r.first)) {
usedLocations.set(r.first);
candidateStores.insert(store);
}
}
return false;
};
auto done = false;
for (auto inst = block->end(); inst != block->begin(); ) {
--inst;
if (inst->is(EndCatch)) {
continue;
}
if (inst->is(IncRef)) {
candidateIncRefs[inst->src(0)].push_back(inst);
continue;
}
if (done) continue;
auto const effects = canonicalize(memory_effects(*inst));
done = match<bool>(
effects,
[&] (IrrelevantEffects) { return false; },
[&] (UnknownEffects) { return true; },
[&] (ReturnEffects x) { return true; },
[&] (CallEffects x) { return true; },
[&] (GeneralEffects x) {
return
process_stack(x.loads) ||
process_stack(x.stores) ||
process_stack(x.kills);
},
[&] (PureLoad x) { return process_stack(x.src); },
[&] (PureStore x) { return do_store(x.dst, &*inst); },
[&] (ExitEffects x) { return process_stack(x.live); },
[&] (PureInlineCall x) {
return
process_stack(x.base) ||
process_stack(x.actrec);
},
[&] (PureInlineReturn x) { return process_stack(x.base); }
);
}
for (auto store : candidateStores) {
auto const src = store->src(1);
auto const it = candidateIncRefs.find(src);
if (it != candidateIncRefs.end()) {
FTRACE(3, "Erasing {} for {}\n",
it->second.back()->toString(), store->toString());
block->erase(it->second.back());
if (it->second.size() > 1) {
it->second.pop_back();
} else {
candidateIncRefs.erase(it);
}
} else {
auto const srcInst = src->inst();
if (!srcInst->producesReference() ||
!canDCE(srcInst) ||
uses[src] != 1) {
continue;
}
FTRACE(3, "Erasing {} for {}\n",
srcInst->toString(), store->toString());
state[srcInst].setDead();
}
store->setSrc(1, unit.cns(TInitNull));
}
}
/*
* A store to the stack which is post-dominated by the EndCatch and
* not otherwise read is only there to ensure the unwinder DecRefs the
* value it contains. If there's also an IncRef of the value in the
* catch trace we can just store InitNull to the stack location and
* drop the IncRef (and later, maybe adjust the sp of the
* catch-trace's owner so we don't even have to do the store).
*/
void optimizeCatchBlocks(const BlockList& blocks,
DceState& state,
IRUnit& unit,
const UseCounts& uses) {
for (auto block : blocks) {
if (block->back().is(EndCatch) &&
block->back().extra<EndCatch>()->mode !=
EndCatchData::CatchMode::SideExit &&
block->front().is(BeginCatch)) {
auto const astk = AStack {
block->back().src(1), block->back().extra<EndCatch>()->offset, 0
};
processCatchBlock(unit, state, block, astk.offset, uses);
}