-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
WinEHPrepare.cpp
3673 lines (3273 loc) · 148 KB
/
WinEHPrepare.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
//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass lowers LLVM IR exception handling into something closer to what the
// backend wants for functions using a personality function from a runtime
// provided by MSVC. Functions with other personality functions are left alone
// and may be prepared by other passes. In particular, all supported MSVC
// personality functions require cleanup code to be outlined, and the C++
// personality requires catch handler code to be outlined.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/LibCallSemantics.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/CodeGen/WinEHFuncInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include <memory>
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "winehprepare"
static cl::opt<bool> DisableDemotion(
"disable-demotion", cl::Hidden,
cl::desc(
"Clone multicolor basic blocks but do not demote cross funclet values"),
cl::init(false));
static cl::opt<bool> DisableCleanups(
"disable-cleanups", cl::Hidden,
cl::desc("Do not remove implausible terminators or other similar cleanups"),
cl::init(false));
namespace {
// This map is used to model frame variable usage during outlining, to
// construct a structure type to hold the frame variables in a frame
// allocation block, and to remap the frame variable allocas (including
// spill locations as needed) to GEPs that get the variable from the
// frame allocation structure.
typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
// quite null.
AllocaInst *getCatchObjectSentinel() {
return static_cast<AllocaInst *>(nullptr) + 1;
}
typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
class LandingPadActions;
class LandingPadMap;
typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
class WinEHPrepare : public FunctionPass {
public:
static char ID; // Pass identification, replacement for typeid.
WinEHPrepare(const TargetMachine *TM = nullptr)
: FunctionPass(ID) {
if (TM)
TheTriple = TM->getTargetTriple();
}
bool runOnFunction(Function &Fn) override;
bool doFinalization(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
const char *getPassName() const override {
return "Windows exception handling preparation";
}
private:
bool prepareExceptionHandlers(Function &F,
SmallVectorImpl<LandingPadInst *> &LPads);
void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
void promoteLandingPadValues(LandingPadInst *LPad);
void demoteValuesLiveAcrossHandlers(Function &F,
SmallVectorImpl<LandingPadInst *> &LPads);
void findSEHEHReturnPoints(Function &F,
SetVector<BasicBlock *> &EHReturnBlocks);
void findCXXEHReturnPoints(Function &F,
SetVector<BasicBlock *> &EHReturnBlocks);
void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
SetVector<BasicBlock*> &Targets);
void completeNestedLandingPad(Function *ParentFn,
LandingPadInst *OutlinedLPad,
const LandingPadInst *OriginalLPad,
FrameVarInfoMap &VarInfo);
Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
const Twine &Name, Module *M, Value *&ParentFP);
bool outlineHandler(ActionHandler *Action, Function *SrcFn,
LandingPadInst *LPad, BasicBlock *StartBB,
FrameVarInfoMap &VarInfo);
void addStubInvokeToHandlerIfNeeded(Function *Handler);
void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
VisitedBlockSet &VisitedBlocks);
void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
BasicBlock *EndBB);
void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
void
insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
AllocaInst *insertPHILoads(PHINode *PN, Function &F);
void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
DenseMap<BasicBlock *, Value *> &Loads, Function &F);
void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
Function &F);
bool prepareExplicitEH(Function &F,
SmallVectorImpl<BasicBlock *> &EntryBlocks);
void replaceTerminatePadWithCleanup(Function &F);
void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
void demotePHIsOnFunclets(Function &F);
void demoteUsesBetweenFunclets(Function &F);
void demoteArgumentUses(Function &F);
void cloneCommonBlocks(Function &F,
SmallVectorImpl<BasicBlock *> &EntryBlocks);
void removeImplausibleTerminators(Function &F);
void cleanupPreparedFunclets(Function &F);
void verifyPreparedFunclets(Function &F);
Triple TheTriple;
// All fields are reset by runOnFunction.
DominatorTree *DT = nullptr;
const TargetLibraryInfo *LibInfo = nullptr;
EHPersonality Personality = EHPersonality::Unknown;
CatchHandlerMapTy CatchHandlerMap;
CleanupHandlerMapTy CleanupHandlerMap;
DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
SmallPtrSet<BasicBlock *, 4> NormalBlocks;
SmallPtrSet<BasicBlock *, 4> EHBlocks;
SetVector<BasicBlock *> EHReturnBlocks;
// This maps landing pad instructions found in outlined handlers to
// the landing pad instruction in the parent function from which they
// were cloned. The cloned/nested landing pad is used as the key
// because the landing pad may be cloned into multiple handlers.
// This map will be used to add the llvm.eh.actions call to the nested
// landing pads after all handlers have been outlined.
DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
// This maps blocks in the parent function which are destinations of
// catch handlers to cloned blocks in (other) outlined handlers. This
// handles the case where a nested landing pads has a catch handler that
// returns to a handler function rather than the parent function.
// The original block is used as the key here because there should only
// ever be one handler function from which the cloned block is not pruned.
// The original block will be pruned from the parent function after all
// handlers have been outlined. This map will be used to adjust the
// return instructions of handlers which return to the block that was
// outlined into a handler. This is done after all handlers have been
// outlined but before the outlined code is pruned from the parent function.
DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
// Map from outlined handler to call to parent local address. Only used for
// 32-bit EH.
DenseMap<Function *, Value *> HandlerToParentFP;
AllocaInst *SEHExceptionCodeSlot = nullptr;
std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
};
class WinEHFrameVariableMaterializer : public ValueMaterializer {
public:
WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
FrameVarInfoMap &FrameVarInfo);
~WinEHFrameVariableMaterializer() override {}
Value *materializeValueFor(Value *V) override;
void escapeCatchObject(Value *V);
private:
FrameVarInfoMap &FrameVarInfo;
IRBuilder<> Builder;
};
class LandingPadMap {
public:
LandingPadMap() : OriginLPad(nullptr) {}
void mapLandingPad(const LandingPadInst *LPad);
bool isInitialized() { return OriginLPad != nullptr; }
bool isOriginLandingPadBlock(const BasicBlock *BB) const;
bool isLandingPadSpecificInst(const Instruction *Inst) const;
void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
Value *SelectorValue) const;
private:
const LandingPadInst *OriginLPad;
// We will normally only see one of each of these instructions, but
// if more than one occurs for some reason we can handle that.
TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
};
class WinEHCloningDirectorBase : public CloningDirector {
public:
WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
: Materializer(HandlerFn, ParentFP, VarInfo),
SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
LPadMap(LPadMap), ParentFP(ParentFP) {}
CloningAction handleInstruction(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) override;
virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) = 0;
virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) = 0;
virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) = 0;
virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
const IndirectBrInst *IBr,
BasicBlock *NewBB) = 0;
virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
const InvokeInst *Invoke,
BasicBlock *NewBB) = 0;
virtual CloningAction handleResume(ValueToValueMapTy &VMap,
const ResumeInst *Resume,
BasicBlock *NewBB) = 0;
virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
const CmpInst *Compare,
BasicBlock *NewBB) = 0;
virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
const LandingPadInst *LPad,
BasicBlock *NewBB) = 0;
ValueMaterializer *getValueMaterializer() override { return &Materializer; }
protected:
WinEHFrameVariableMaterializer Materializer;
Type *SelectorIDType;
Type *Int8PtrType;
LandingPadMap &LPadMap;
/// The value representing the parent frame pointer.
Value *ParentFP;
};
class WinEHCatchDirector : public WinEHCloningDirectorBase {
public:
WinEHCatchDirector(
Function *CatchFn, Value *ParentFP, Value *Selector,
FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
: WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
CurrentSelector(Selector->stripPointerCasts()),
ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
DT(DT), EHBlocks(EHBlocks) {}
CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) override;
CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
BasicBlock *NewBB) override;
CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) override;
CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
const IndirectBrInst *IBr,
BasicBlock *NewBB) override;
CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
BasicBlock *NewBB) override;
CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
BasicBlock *NewBB) override;
CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
BasicBlock *NewBB) override;
CloningAction handleLandingPad(ValueToValueMapTy &VMap,
const LandingPadInst *LPad,
BasicBlock *NewBB) override;
Value *getExceptionVar() { return ExceptionObjectVar; }
TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
private:
Value *CurrentSelector;
Value *ExceptionObjectVar;
TinyPtrVector<BasicBlock *> ReturnTargets;
// This will be a reference to the field of the same name in the WinEHPrepare
// object which instantiates this WinEHCatchDirector object.
DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
DominatorTree *DT;
SmallPtrSetImpl<BasicBlock *> &EHBlocks;
};
class WinEHCleanupDirector : public WinEHCloningDirectorBase {
public:
WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
: WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
LPadMap) {}
CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) override;
CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
BasicBlock *NewBB) override;
CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
const Instruction *Inst,
BasicBlock *NewBB) override;
CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
const IndirectBrInst *IBr,
BasicBlock *NewBB) override;
CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
BasicBlock *NewBB) override;
CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
BasicBlock *NewBB) override;
CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
BasicBlock *NewBB) override;
CloningAction handleLandingPad(ValueToValueMapTy &VMap,
const LandingPadInst *LPad,
BasicBlock *NewBB) override;
};
class LandingPadActions {
public:
LandingPadActions() : HasCleanupHandlers(false) {}
void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
void insertCleanupHandler(CleanupHandler *Action) {
Actions.push_back(Action);
HasCleanupHandlers = true;
}
bool includesCleanup() const { return HasCleanupHandlers; }
SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
private:
// Note that this class does not own the ActionHandler objects in this vector.
// The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
// in the WinEHPrepare class.
SmallVector<ActionHandler *, 4> Actions;
bool HasCleanupHandlers;
};
} // end anonymous namespace
char WinEHPrepare::ID = 0;
INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
false, false)
FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
return new WinEHPrepare(TM);
}
static bool
findExceptionalConstructs(Function &Fn,
SmallVectorImpl<LandingPadInst *> &LPads,
SmallVectorImpl<ResumeInst *> &Resumes,
SmallVectorImpl<BasicBlock *> &EntryBlocks) {
bool ForExplicitEH = false;
for (BasicBlock &BB : Fn) {
Instruction *First = BB.getFirstNonPHI();
if (auto *LP = dyn_cast<LandingPadInst>(First)) {
LPads.push_back(LP);
} else if (First->isEHPad()) {
if (!ForExplicitEH)
EntryBlocks.push_back(&Fn.getEntryBlock());
if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
EntryBlocks.push_back(&BB);
ForExplicitEH = true;
}
if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
Resumes.push_back(Resume);
}
return ForExplicitEH;
}
bool WinEHPrepare::runOnFunction(Function &Fn) {
if (!Fn.hasPersonalityFn())
return false;
// No need to prepare outlined handlers.
if (Fn.hasFnAttribute("wineh-parent"))
return false;
// Classify the personality to see what kind of preparation we need.
Personality = classifyEHPersonality(Fn.getPersonalityFn());
// Do nothing if this is not a funclet-based personality.
if (!isFuncletEHPersonality(Personality))
return false;
SmallVector<LandingPadInst *, 4> LPads;
SmallVector<ResumeInst *, 4> Resumes;
SmallVector<BasicBlock *, 4> EntryBlocks;
bool ForExplicitEH =
findExceptionalConstructs(Fn, LPads, Resumes, EntryBlocks);
if (ForExplicitEH)
return prepareExplicitEH(Fn, EntryBlocks);
// No need to prepare functions that lack landing pads.
if (LPads.empty())
return false;
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
// If there were any landing pads, prepareExceptionHandlers will make changes.
prepareExceptionHandlers(Fn, LPads);
return true;
}
bool WinEHPrepare::doFinalization(Module &M) { return false; }
void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
}
static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
Constant *&Selector, BasicBlock *&NextBB);
// Finds blocks reachable from the starting set Worklist. Does not follow unwind
// edges or blocks listed in StopPoints.
static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
SetVector<BasicBlock *> &Worklist,
const SetVector<BasicBlock *> *StopPoints) {
while (!Worklist.empty()) {
BasicBlock *BB = Worklist.pop_back_val();
// Don't cross blocks that we should stop at.
if (StopPoints && StopPoints->count(BB))
continue;
if (!ReachableBBs.insert(BB).second)
continue; // Already visited.
// Don't follow unwind edges of invokes.
if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Worklist.insert(II->getNormalDest());
continue;
}
// Otherwise, follow all successors.
Worklist.insert(succ_begin(BB), succ_end(BB));
}
}
// Attempt to find an instruction where a block can be split before
// a call to llvm.eh.begincatch and its operands. If the block
// begins with the begincatch call or one of its adjacent operands
// the block will not be split.
static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
IntrinsicInst *II) {
// If the begincatch call is already the first instruction in the block,
// don't split.
Instruction *FirstNonPHI = BB->getFirstNonPHI();
if (II == FirstNonPHI)
return nullptr;
// If either operand is in the same basic block as the instruction and
// isn't used by another instruction before the begincatch call, include it
// in the split block.
auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
Instruction *I = II->getPrevNode();
Instruction *LastI = II;
while (I == Op0 || I == Op1) {
// If the block begins with one of the operands and there are no other
// instructions between the operand and the begincatch call, don't split.
if (I == FirstNonPHI)
return nullptr;
LastI = I;
I = I->getPrevNode();
}
// If there is at least one instruction in the block before the begincatch
// call and its operands, split the block at either the begincatch or
// its operand.
return LastI;
}
/// Find all points where exceptional control rejoins normal control flow via
/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
void WinEHPrepare::findCXXEHReturnPoints(
Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = BBI;
for (Instruction &I : *BB) {
if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Instruction *SplitPt =
findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
if (SplitPt) {
// Split the block before the llvm.eh.begincatch call to allow
// cleanup and catch code to be distinguished later.
// Do not update BBI because we still need to process the
// portion of the block that we are splitting off.
SplitBlock(BB, SplitPt, DT);
break;
}
}
if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
// Split the block after the call to llvm.eh.endcatch if there is
// anything other than an unconditional branch, or if the successor
// starts with a phi.
auto *Br = dyn_cast<BranchInst>(I.getNextNode());
if (!Br || !Br->isUnconditional() ||
isa<PHINode>(Br->getSuccessor(0)->begin())) {
DEBUG(dbgs() << "splitting block " << BB->getName()
<< " with llvm.eh.endcatch\n");
BBI = SplitBlock(BB, I.getNextNode(), DT);
}
// The next BB is normal control flow.
EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
break;
}
}
}
}
static bool isCatchAllLandingPad(const BasicBlock *BB) {
const LandingPadInst *LP = BB->getLandingPadInst();
if (!LP)
return false;
unsigned N = LP->getNumClauses();
return (N > 0 && LP->isCatch(N - 1) &&
isa<ConstantPointerNull>(LP->getClause(N - 1)));
}
/// Find all points where exceptions control rejoins normal control flow via
/// selector dispatch.
void WinEHPrepare::findSEHEHReturnPoints(
Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = BBI;
// If the landingpad is a catch-all, treat the whole lpad as if it is
// reachable from normal control flow.
// FIXME: This is imprecise. We need a better way of identifying where a
// catch-all starts and cleanups stop. As far as LLVM is concerned, there
// is no difference.
if (isCatchAllLandingPad(BB)) {
EHReturnBlocks.insert(BB);
continue;
}
BasicBlock *CatchHandler;
BasicBlock *NextBB;
Constant *Selector;
if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
// Split the edge if there are multiple predecessors. This creates a place
// where we can insert EH recovery code.
if (!CatchHandler->getSinglePredecessor()) {
DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
<< " to " << CatchHandler->getName() << '\n');
BBI = CatchHandler = SplitCriticalEdge(
BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
}
EHReturnBlocks.insert(CatchHandler);
}
}
}
void WinEHPrepare::identifyEHBlocks(Function &F,
SmallVectorImpl<LandingPadInst *> &LPads) {
DEBUG(dbgs() << "Demoting values live across exception handlers in function "
<< F.getName() << '\n');
// Build a set of all non-exceptional blocks and exceptional blocks.
// - Non-exceptional blocks are blocks reachable from the entry block while
// not following invoke unwind edges.
// - Exceptional blocks are blocks reachable from landingpads. Analysis does
// not follow llvm.eh.endcatch blocks, which mark a transition from
// exceptional to normal control.
if (Personality == EHPersonality::MSVC_CXX)
findCXXEHReturnPoints(F, EHReturnBlocks);
else
findSEHEHReturnPoints(F, EHReturnBlocks);
DEBUG({
dbgs() << "identified the following blocks as EH return points:\n";
for (BasicBlock *BB : EHReturnBlocks)
dbgs() << " " << BB->getName() << '\n';
});
// Join points should not have phis at this point, unless they are a
// landingpad, in which case we will demote their phis later.
#ifndef NDEBUG
for (BasicBlock *BB : EHReturnBlocks)
assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
"non-lpad EH return block has phi");
#endif
// Normal blocks are the blocks reachable from the entry block and all EH
// return points.
SetVector<BasicBlock *> Worklist;
Worklist = EHReturnBlocks;
Worklist.insert(&F.getEntryBlock());
findReachableBlocks(NormalBlocks, Worklist, nullptr);
DEBUG({
dbgs() << "marked the following blocks as normal:\n";
for (BasicBlock *BB : NormalBlocks)
dbgs() << " " << BB->getName() << '\n';
});
// Exceptional blocks are the blocks reachable from landingpads that don't
// cross EH return points.
Worklist.clear();
for (auto *LPI : LPads)
Worklist.insert(LPI->getParent());
findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
DEBUG({
dbgs() << "marked the following blocks as exceptional:\n";
for (BasicBlock *BB : EHBlocks)
dbgs() << " " << BB->getName() << '\n';
});
}
/// Ensure that all values live into and out of exception handlers are stored
/// in memory.
/// FIXME: This falls down when values are defined in one handler and live into
/// another handler. For example, a cleanup defines a value used only by a
/// catch handler.
void WinEHPrepare::demoteValuesLiveAcrossHandlers(
Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
DEBUG(dbgs() << "Demoting values live across exception handlers in function "
<< F.getName() << '\n');
// identifyEHBlocks() should have been called before this function.
assert(!NormalBlocks.empty());
// Try to avoid demoting EH pointer and selector values. They get in the way
// of our pattern matching.
SmallPtrSet<Instruction *, 10> EHVals;
for (BasicBlock &BB : F) {
LandingPadInst *LP = BB.getLandingPadInst();
if (!LP)
continue;
EHVals.insert(LP);
for (User *U : LP->users()) {
auto *EI = dyn_cast<ExtractValueInst>(U);
if (!EI)
continue;
EHVals.insert(EI);
for (User *U2 : EI->users()) {
if (auto *PN = dyn_cast<PHINode>(U2))
EHVals.insert(PN);
}
}
}
SetVector<Argument *> ArgsToDemote;
SetVector<Instruction *> InstrsToDemote;
for (BasicBlock &BB : F) {
bool IsNormalBB = NormalBlocks.count(&BB);
bool IsEHBB = EHBlocks.count(&BB);
if (!IsNormalBB && !IsEHBB)
continue; // Blocks that are neither normal nor EH are unreachable.
for (Instruction &I : BB) {
for (Value *Op : I.operands()) {
// Don't demote static allocas, constants, and labels.
if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
continue;
auto *AI = dyn_cast<AllocaInst>(Op);
if (AI && AI->isStaticAlloca())
continue;
if (auto *Arg = dyn_cast<Argument>(Op)) {
if (IsEHBB) {
DEBUG(dbgs() << "Demoting argument " << *Arg
<< " used by EH instr: " << I << "\n");
ArgsToDemote.insert(Arg);
}
continue;
}
// Don't demote EH values.
auto *OpI = cast<Instruction>(Op);
if (EHVals.count(OpI))
continue;
BasicBlock *OpBB = OpI->getParent();
// If a value is produced and consumed in the same BB, we don't need to
// demote it.
if (OpBB == &BB)
continue;
bool IsOpNormalBB = NormalBlocks.count(OpBB);
bool IsOpEHBB = EHBlocks.count(OpBB);
if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
DEBUG({
dbgs() << "Demoting instruction live in-out from EH:\n";
dbgs() << "Instr: " << *OpI << '\n';
dbgs() << "User: " << I << '\n';
});
InstrsToDemote.insert(OpI);
}
}
}
}
// Demote values live into and out of handlers.
// FIXME: This demotion is inefficient. We should insert spills at the point
// of definition, insert one reload in each handler that uses the value, and
// insert reloads in the BB used to rejoin normal control flow.
Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
for (Instruction *I : InstrsToDemote)
DemoteRegToStack(*I, false, AllocaInsertPt);
// Demote arguments separately, and only for uses in EH blocks.
for (Argument *Arg : ArgsToDemote) {
auto *Slot = new AllocaInst(Arg->getType(), nullptr,
Arg->getName() + ".reg2mem", AllocaInsertPt);
SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
for (User *U : Users) {
auto *I = dyn_cast<Instruction>(U);
if (I && EHBlocks.count(I->getParent())) {
auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
U->replaceUsesOfWith(Arg, Reload);
}
}
new StoreInst(Arg, Slot, AllocaInsertPt);
}
// Demote landingpad phis, as the landingpad will be removed from the machine
// CFG.
for (LandingPadInst *LPI : LPads) {
BasicBlock *BB = LPI->getParent();
while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
DemotePHIToStack(Phi, AllocaInsertPt);
}
DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
<< ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
}
bool WinEHPrepare::prepareExceptionHandlers(
Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
// Don't run on functions that are already prepared.
for (LandingPadInst *LPad : LPads) {
BasicBlock *LPadBB = LPad->getParent();
for (Instruction &Inst : *LPadBB)
if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
return false;
}
identifyEHBlocks(F, LPads);
demoteValuesLiveAcrossHandlers(F, LPads);
// These containers are used to re-map frame variables that are used in
// outlined catch and cleanup handlers. They will be populated as the
// handlers are outlined.
FrameVarInfoMap FrameVarInfo;
bool HandlersOutlined = false;
Module *M = F.getParent();
LLVMContext &Context = M->getContext();
// Create a new function to receive the handler contents.
PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
Type *Int32Type = Type::getInt32Ty(Context);
Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
if (isAsynchronousEHPersonality(Personality)) {
// FIXME: Switch the ehptr type to i32 and then switch this.
SEHExceptionCodeSlot =
new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
F.getEntryBlock().getFirstInsertionPt());
}
// In order to handle the case where one outlined catch handler returns
// to a block within another outlined catch handler that would otherwise
// be unreachable, we need to outline the nested landing pad before we
// outline the landing pad which encloses it.
if (!isAsynchronousEHPersonality(Personality))
std::sort(LPads.begin(), LPads.end(),
[this](LandingPadInst *const &L, LandingPadInst *const &R) {
return DT->properlyDominates(R->getParent(), L->getParent());
});
// This container stores the llvm.eh.recover and IndirectBr instructions
// that make up the body of each landing pad after it has been outlined.
// We need to defer the population of the target list for the indirectbr
// until all landing pads have been outlined so that we can handle the
// case of blocks in the target that are reached only from nested
// landing pads.
SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
for (LandingPadInst *LPad : LPads) {
// Look for evidence that this landingpad has already been processed.
bool LPadHasActionList = false;
BasicBlock *LPadBB = LPad->getParent();
for (Instruction &Inst : *LPadBB) {
if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
LPadHasActionList = true;
break;
}
}
// If we've already outlined the handlers for this landingpad,
// there's nothing more to do here.
if (LPadHasActionList)
continue;
// If either of the values in the aggregate returned by the landing pad is
// extracted and stored to memory, promote the stored value to a register.
promoteLandingPadValues(LPad);
LandingPadActions Actions;
mapLandingPadBlocks(LPad, Actions);
HandlersOutlined |= !Actions.actions().empty();
for (ActionHandler *Action : Actions) {
if (Action->hasBeenProcessed())
continue;
BasicBlock *StartBB = Action->getStartBlock();
// SEH doesn't do any outlining for catches. Instead, pass the handler
// basic block addr to llvm.eh.actions and list the block as a return
// target.
if (isAsynchronousEHPersonality(Personality)) {
if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
processSEHCatchHandler(CatchAction, StartBB);
continue;
}
}
outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
}
// Split the block after the landingpad instruction so that it is just a
// call to llvm.eh.actions followed by indirectbr.
assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
SplitBlock(LPadBB, LPad->getNextNode(), DT);
// Erase the branch inserted by the split so we can insert indirectbr.
LPadBB->getTerminator()->eraseFromParent();
// Replace all extracted values with undef and ultimately replace the
// landingpad with undef.
SmallVector<Instruction *, 4> SEHCodeUses;
SmallVector<Instruction *, 4> EHUndefs;
for (User *U : LPad->users()) {
auto *E = dyn_cast<ExtractValueInst>(U);
if (!E)
continue;
assert(E->getNumIndices() == 1 &&
"Unexpected operation: extracting both landing pad values");
unsigned Idx = *E->idx_begin();
assert((Idx == 0 || Idx == 1) && "unexpected index");
if (Idx == 0 && isAsynchronousEHPersonality(Personality))
SEHCodeUses.push_back(E);
else
EHUndefs.push_back(E);
}
for (Instruction *E : EHUndefs) {
E->replaceAllUsesWith(UndefValue::get(E->getType()));
E->eraseFromParent();
}
LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
// Rewrite uses of the exception pointer to loads of an alloca.
while (!SEHCodeUses.empty()) {
Instruction *E = SEHCodeUses.pop_back_val();
SmallVector<Use *, 4> Uses;
for (Use &U : E->uses())
Uses.push_back(&U);
for (Use *U : Uses) {
auto *I = cast<Instruction>(U->getUser());
if (isa<ResumeInst>(I))
continue;
if (auto *Phi = dyn_cast<PHINode>(I))
SEHCodeUses.push_back(Phi);
else
U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
}
E->replaceAllUsesWith(UndefValue::get(E->getType()));
E->eraseFromParent();
}
// Add a call to describe the actions for this landing pad.
std::vector<Value *> ActionArgs;
for (ActionHandler *Action : Actions) {
// Action codes from docs are: 0 cleanup, 1 catch.
if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
ActionArgs.push_back(CatchAction->getSelector());
// Find the frame escape index of the exception object alloca in the
// parent.
int FrameEscapeIdx = -1;
Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
auto I = FrameVarInfo.find(EHObj);
assert(I != FrameVarInfo.end() &&
"failed to map llvm.eh.begincatch var");
FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
}
ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
} else {
ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
}
ActionArgs.push_back(Action->getHandlerBlockOrFunc());
}
CallInst *Recover =
CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
SetVector<BasicBlock *> ReturnTargets;
for (ActionHandler *Action : Actions) {
if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
const auto &CatchTargets = CatchAction->getReturnTargets();
ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
}
}
IndirectBrInst *Branch =
IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
for (BasicBlock *Target : ReturnTargets)
Branch->addDestination(Target);
if (!isAsynchronousEHPersonality(Personality)) {
// C++ EH must repopulate the targets later to handle the case of
// targets that are reached indirectly through nested landing pads.
LPadImpls.push_back(std::make_pair(Recover, Branch));
}
} // End for each landingpad
// If nothing got outlined, there is no more processing to be done.
if (!HandlersOutlined)
return false;
// Replace any nested landing pad stubs with the correct action handler.
// This must be done before we remove unreachable blocks because it
// cleans up references to outlined blocks that will be deleted.
for (auto &LPadPair : NestedLPtoOriginalLP)
completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
NestedLPtoOriginalLP.clear();
// Update the indirectbr instructions' target lists if necessary.
SetVector<BasicBlock*> CheckedTargets;
SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
for (auto &LPadImplPair : LPadImpls) {
IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
IndirectBrInst *Branch = LPadImplPair.second;
// Get a list of handlers called by
parseEHActions(Recover, ActionList);
// Add an indirect branch listing possible successors of the catch handlers.
SetVector<BasicBlock *> ReturnTargets;