Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1 | //===-- WinEHPrepare - Prepare exception handling for code generation ---===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass lowers LLVM IR exception handling into something closer to what the |
Reid Kleckner | 0738a9c | 2015-05-05 17:44:16 +0000 | [diff] [blame] | 11 | // backend wants for functions using a personality function from a runtime |
| 12 | // provided by MSVC. Functions with other personality functions are left alone |
| 13 | // and may be prepared by other passes. In particular, all supported MSVC |
| 14 | // personality functions require cleanup code to be outlined, and the C++ |
| 15 | // personality requires catch handler code to be outlined. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 16 | // |
| 17 | //===----------------------------------------------------------------------===// |
| 18 | |
| 19 | #include "llvm/CodeGen/Passes.h" |
| 20 | #include "llvm/ADT/MapVector.h" |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/STLExtras.h" |
Benjamin Kramer | a8d61b1 | 2015-03-23 18:57:17 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/SmallSet.h" |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 23 | #include "llvm/ADT/SetVector.h" |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/Triple.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/TinyPtrVector.h" |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/CFG.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/LibCallSemantics.h" |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/TargetLibraryInfo.h" |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 29 | #include "llvm/CodeGen/WinEHFuncInfo.h" |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 30 | #include "llvm/IR/Dominators.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Function.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
| 33 | #include "llvm/IR/Instructions.h" |
| 34 | #include "llvm/IR/IntrinsicInst.h" |
| 35 | #include "llvm/IR/Module.h" |
| 36 | #include "llvm/IR/PatternMatch.h" |
| 37 | #include "llvm/Pass.h" |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 38 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | a8d61b1 | 2015-03-23 18:57:17 +0000 | [diff] [blame] | 39 | #include "llvm/Support/raw_ostream.h" |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 41 | #include "llvm/Transforms/Utils/Cloning.h" |
| 42 | #include "llvm/Transforms/Utils/Local.h" |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 43 | #include "llvm/Transforms/Utils/PromoteMemToReg.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 44 | #include <memory> |
| 45 | |
| 46 | using namespace llvm; |
| 47 | using namespace llvm::PatternMatch; |
| 48 | |
| 49 | #define DEBUG_TYPE "winehprepare" |
| 50 | |
| 51 | namespace { |
| 52 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 53 | // This map is used to model frame variable usage during outlining, to |
| 54 | // construct a structure type to hold the frame variables in a frame |
| 55 | // allocation block, and to remap the frame variable allocas (including |
| 56 | // spill locations as needed) to GEPs that get the variable from the |
| 57 | // frame allocation structure. |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 58 | typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 59 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 60 | // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't |
| 61 | // quite null. |
| 62 | AllocaInst *getCatchObjectSentinel() { |
| 63 | return static_cast<AllocaInst *>(nullptr) + 1; |
| 64 | } |
| 65 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 66 | typedef SmallSet<BasicBlock *, 4> VisitedBlockSet; |
| 67 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 68 | class LandingPadActions; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 69 | class LandingPadMap; |
| 70 | |
| 71 | typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy; |
| 72 | typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy; |
| 73 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 74 | class WinEHPrepare : public FunctionPass { |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 75 | public: |
| 76 | static char ID; // Pass identification, replacement for typeid. |
| 77 | WinEHPrepare(const TargetMachine *TM = nullptr) |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 78 | : FunctionPass(ID) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 79 | if (TM) |
Daniel Sanders | 110bf6d | 2015-06-24 13:25:57 +0000 | [diff] [blame] | 80 | TheTriple = TM->getTargetTriple(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 81 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 82 | |
| 83 | bool runOnFunction(Function &Fn) override; |
| 84 | |
| 85 | bool doFinalization(Module &M) override; |
| 86 | |
| 87 | void getAnalysisUsage(AnalysisUsage &AU) const override; |
| 88 | |
| 89 | const char *getPassName() const override { |
| 90 | return "Windows exception handling preparation"; |
| 91 | } |
| 92 | |
| 93 | private: |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 94 | bool prepareExceptionHandlers(Function &F, |
| 95 | SmallVectorImpl<LandingPadInst *> &LPads); |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 96 | void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 97 | void promoteLandingPadValues(LandingPadInst *LPad); |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 98 | void demoteValuesLiveAcrossHandlers(Function &F, |
| 99 | SmallVectorImpl<LandingPadInst *> &LPads); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 100 | void findSEHEHReturnPoints(Function &F, |
| 101 | SetVector<BasicBlock *> &EHReturnBlocks); |
| 102 | void findCXXEHReturnPoints(Function &F, |
| 103 | SetVector<BasicBlock *> &EHReturnBlocks); |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 104 | void getPossibleReturnTargets(Function *ParentF, Function *HandlerF, |
| 105 | SetVector<BasicBlock*> &Targets); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 106 | void completeNestedLandingPad(Function *ParentFn, |
| 107 | LandingPadInst *OutlinedLPad, |
| 108 | const LandingPadInst *OriginalLPad, |
| 109 | FrameVarInfoMap &VarInfo); |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 110 | Function *createHandlerFunc(Function *ParentFn, Type *RetTy, |
| 111 | const Twine &Name, Module *M, Value *&ParentFP); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 112 | bool outlineHandler(ActionHandler *Action, Function *SrcFn, |
| 113 | LandingPadInst *LPad, BasicBlock *StartBB, |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 114 | FrameVarInfoMap &VarInfo); |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 115 | void addStubInvokeToHandlerIfNeeded(Function *Handler); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 116 | |
| 117 | void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions); |
| 118 | CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB, |
| 119 | VisitedBlockSet &VisitedBlocks); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 120 | void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB, |
| 121 | BasicBlock *EndBB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 122 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 123 | void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB); |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 124 | void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot); |
| 125 | void |
| 126 | insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot, |
| 127 | SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist); |
| 128 | AllocaInst *insertPHILoads(PHINode *PN, Function &F); |
| 129 | void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot, |
| 130 | DenseMap<BasicBlock *, Value *> &Loads, Function &F); |
| 131 | void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB, |
| 132 | Function &F); |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 133 | bool prepareExplicitEH(Function &F); |
| 134 | void numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB); |
| 135 | |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 136 | Triple TheTriple; |
| 137 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 138 | // All fields are reset by runOnFunction. |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 139 | DominatorTree *DT = nullptr; |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 140 | const TargetLibraryInfo *LibInfo = nullptr; |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 141 | EHPersonality Personality = EHPersonality::Unknown; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 142 | CatchHandlerMapTy CatchHandlerMap; |
| 143 | CleanupHandlerMapTy CleanupHandlerMap; |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 144 | DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 145 | SmallPtrSet<BasicBlock *, 4> NormalBlocks; |
| 146 | SmallPtrSet<BasicBlock *, 4> EHBlocks; |
| 147 | SetVector<BasicBlock *> EHReturnBlocks; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 148 | |
| 149 | // This maps landing pad instructions found in outlined handlers to |
| 150 | // the landing pad instruction in the parent function from which they |
| 151 | // were cloned. The cloned/nested landing pad is used as the key |
| 152 | // because the landing pad may be cloned into multiple handlers. |
| 153 | // This map will be used to add the llvm.eh.actions call to the nested |
| 154 | // landing pads after all handlers have been outlined. |
| 155 | DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP; |
| 156 | |
| 157 | // This maps blocks in the parent function which are destinations of |
| 158 | // catch handlers to cloned blocks in (other) outlined handlers. This |
| 159 | // handles the case where a nested landing pads has a catch handler that |
| 160 | // returns to a handler function rather than the parent function. |
| 161 | // The original block is used as the key here because there should only |
| 162 | // ever be one handler function from which the cloned block is not pruned. |
| 163 | // The original block will be pruned from the parent function after all |
| 164 | // handlers have been outlined. This map will be used to adjust the |
| 165 | // return instructions of handlers which return to the block that was |
| 166 | // outlined into a handler. This is done after all handlers have been |
| 167 | // outlined but before the outlined code is pruned from the parent function. |
| 168 | DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks; |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 169 | |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 170 | // Map from outlined handler to call to parent local address. Only used for |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 171 | // 32-bit EH. |
| 172 | DenseMap<Function *, Value *> HandlerToParentFP; |
| 173 | |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 174 | AllocaInst *SEHExceptionCodeSlot = nullptr; |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 175 | |
| 176 | std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors; |
| 177 | std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 178 | }; |
| 179 | |
| 180 | class WinEHFrameVariableMaterializer : public ValueMaterializer { |
| 181 | public: |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 182 | WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP, |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 183 | FrameVarInfoMap &FrameVarInfo); |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 184 | ~WinEHFrameVariableMaterializer() override {} |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 185 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 186 | Value *materializeValueFor(Value *V) override; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 187 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 188 | void escapeCatchObject(Value *V); |
| 189 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 190 | private: |
| 191 | FrameVarInfoMap &FrameVarInfo; |
| 192 | IRBuilder<> Builder; |
| 193 | }; |
| 194 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 195 | class LandingPadMap { |
| 196 | public: |
| 197 | LandingPadMap() : OriginLPad(nullptr) {} |
| 198 | void mapLandingPad(const LandingPadInst *LPad); |
| 199 | |
| 200 | bool isInitialized() { return OriginLPad != nullptr; } |
| 201 | |
Andrew Kaylor | f7118ae | 2015-03-27 22:31:12 +0000 | [diff] [blame] | 202 | bool isOriginLandingPadBlock(const BasicBlock *BB) const; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 203 | bool isLandingPadSpecificInst(const Instruction *Inst) const; |
| 204 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 205 | void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue, |
| 206 | Value *SelectorValue) const; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 207 | |
| 208 | private: |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 209 | const LandingPadInst *OriginLPad; |
| 210 | // We will normally only see one of each of these instructions, but |
| 211 | // if more than one occurs for some reason we can handle that. |
| 212 | TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs; |
| 213 | TinyPtrVector<const ExtractValueInst *> ExtractedSelectors; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 214 | }; |
| 215 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 216 | class WinEHCloningDirectorBase : public CloningDirector { |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 217 | public: |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 218 | WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP, |
| 219 | FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap) |
| 220 | : Materializer(HandlerFn, ParentFP, VarInfo), |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 221 | SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())), |
| 222 | Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())), |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 223 | LPadMap(LPadMap), ParentFP(ParentFP) {} |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 224 | |
| 225 | CloningAction handleInstruction(ValueToValueMapTy &VMap, |
| 226 | const Instruction *Inst, |
| 227 | BasicBlock *NewBB) override; |
| 228 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 229 | virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap, |
| 230 | const Instruction *Inst, |
| 231 | BasicBlock *NewBB) = 0; |
| 232 | virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap, |
| 233 | const Instruction *Inst, |
| 234 | BasicBlock *NewBB) = 0; |
| 235 | virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, |
| 236 | const Instruction *Inst, |
| 237 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 238 | virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap, |
| 239 | const IndirectBrInst *IBr, |
| 240 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 241 | virtual CloningAction handleInvoke(ValueToValueMapTy &VMap, |
| 242 | const InvokeInst *Invoke, |
| 243 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 244 | virtual CloningAction handleResume(ValueToValueMapTy &VMap, |
| 245 | const ResumeInst *Resume, |
| 246 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 247 | virtual CloningAction handleCompare(ValueToValueMapTy &VMap, |
| 248 | const CmpInst *Compare, |
| 249 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 250 | virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap, |
| 251 | const LandingPadInst *LPad, |
| 252 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 253 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 254 | ValueMaterializer *getValueMaterializer() override { return &Materializer; } |
| 255 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 256 | protected: |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 257 | WinEHFrameVariableMaterializer Materializer; |
| 258 | Type *SelectorIDType; |
| 259 | Type *Int8PtrType; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 260 | LandingPadMap &LPadMap; |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 261 | |
| 262 | /// The value representing the parent frame pointer. |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 263 | Value *ParentFP; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 264 | }; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 265 | |
| 266 | class WinEHCatchDirector : public WinEHCloningDirectorBase { |
| 267 | public: |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 268 | WinEHCatchDirector( |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 269 | Function *CatchFn, Value *ParentFP, Value *Selector, |
| 270 | FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap, |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 271 | DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads, |
| 272 | DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks) |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 273 | : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap), |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 274 | CurrentSelector(Selector->stripPointerCasts()), |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 275 | ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads), |
| 276 | DT(DT), EHBlocks(EHBlocks) {} |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 277 | |
| 278 | CloningAction handleBeginCatch(ValueToValueMapTy &VMap, |
| 279 | const Instruction *Inst, |
| 280 | BasicBlock *NewBB) override; |
| 281 | CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst, |
| 282 | BasicBlock *NewBB) override; |
| 283 | CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, |
| 284 | const Instruction *Inst, |
| 285 | BasicBlock *NewBB) override; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 286 | CloningAction handleIndirectBr(ValueToValueMapTy &VMap, |
| 287 | const IndirectBrInst *IBr, |
| 288 | BasicBlock *NewBB) override; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 289 | CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke, |
| 290 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 291 | CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume, |
| 292 | BasicBlock *NewBB) override; |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 293 | CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare, |
| 294 | BasicBlock *NewBB) override; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 295 | CloningAction handleLandingPad(ValueToValueMapTy &VMap, |
| 296 | const LandingPadInst *LPad, |
| 297 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 298 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 299 | Value *getExceptionVar() { return ExceptionObjectVar; } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 300 | TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; } |
| 301 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 302 | private: |
| 303 | Value *CurrentSelector; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 304 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 305 | Value *ExceptionObjectVar; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 306 | TinyPtrVector<BasicBlock *> ReturnTargets; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 307 | |
| 308 | // This will be a reference to the field of the same name in the WinEHPrepare |
| 309 | // object which instantiates this WinEHCatchDirector object. |
| 310 | DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 311 | DominatorTree *DT; |
| 312 | SmallPtrSetImpl<BasicBlock *> &EHBlocks; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 313 | }; |
| 314 | |
| 315 | class WinEHCleanupDirector : public WinEHCloningDirectorBase { |
| 316 | public: |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 317 | WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP, |
| 318 | FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap) |
| 319 | : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo, |
| 320 | LPadMap) {} |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 321 | |
| 322 | CloningAction handleBeginCatch(ValueToValueMapTy &VMap, |
| 323 | const Instruction *Inst, |
| 324 | BasicBlock *NewBB) override; |
| 325 | CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst, |
| 326 | BasicBlock *NewBB) override; |
| 327 | CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, |
| 328 | const Instruction *Inst, |
| 329 | BasicBlock *NewBB) override; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 330 | CloningAction handleIndirectBr(ValueToValueMapTy &VMap, |
| 331 | const IndirectBrInst *IBr, |
| 332 | BasicBlock *NewBB) override; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 333 | CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke, |
| 334 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 335 | CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume, |
| 336 | BasicBlock *NewBB) override; |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 337 | CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare, |
| 338 | BasicBlock *NewBB) override; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 339 | CloningAction handleLandingPad(ValueToValueMapTy &VMap, |
| 340 | const LandingPadInst *LPad, |
| 341 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 342 | }; |
| 343 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 344 | class LandingPadActions { |
| 345 | public: |
| 346 | LandingPadActions() : HasCleanupHandlers(false) {} |
| 347 | |
| 348 | void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); } |
| 349 | void insertCleanupHandler(CleanupHandler *Action) { |
| 350 | Actions.push_back(Action); |
| 351 | HasCleanupHandlers = true; |
| 352 | } |
| 353 | |
| 354 | bool includesCleanup() const { return HasCleanupHandlers; } |
| 355 | |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 356 | SmallVectorImpl<ActionHandler *> &actions() { return Actions; } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 357 | SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); } |
| 358 | SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); } |
| 359 | |
| 360 | private: |
| 361 | // Note that this class does not own the ActionHandler objects in this vector. |
| 362 | // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap |
| 363 | // in the WinEHPrepare class. |
| 364 | SmallVector<ActionHandler *, 4> Actions; |
| 365 | bool HasCleanupHandlers; |
| 366 | }; |
| 367 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 368 | } // end anonymous namespace |
| 369 | |
| 370 | char WinEHPrepare::ID = 0; |
Reid Kleckner | 47c8e7a | 2015-03-12 00:36:20 +0000 | [diff] [blame] | 371 | INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions", |
| 372 | false, false) |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 373 | |
| 374 | FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) { |
| 375 | return new WinEHPrepare(TM); |
| 376 | } |
| 377 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 378 | bool WinEHPrepare::runOnFunction(Function &Fn) { |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 379 | if (!Fn.hasPersonalityFn()) |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 380 | return false; |
| 381 | |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 382 | // No need to prepare outlined handlers. |
| 383 | if (Fn.hasFnAttribute("wineh-parent")) |
David Majnemer | 09e1fdb | 2015-08-06 21:13:51 +0000 | [diff] [blame] | 384 | return false; |
| 385 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 386 | // Classify the personality to see what kind of preparation we need. |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 387 | Personality = classifyEHPersonality(Fn.getPersonalityFn()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 388 | |
Reid Kleckner | 47c8e7a | 2015-03-12 00:36:20 +0000 | [diff] [blame] | 389 | // Do nothing if this is not an MSVC personality. |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 390 | if (!isMSVCEHPersonality(Personality)) |
Reid Kleckner | 47c8e7a | 2015-03-12 00:36:20 +0000 | [diff] [blame] | 391 | return false; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 392 | |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 393 | SmallVector<LandingPadInst *, 4> LPads; |
| 394 | SmallVector<ResumeInst *, 4> Resumes; |
| 395 | bool ForExplicitEH = false; |
| 396 | for (BasicBlock &BB : Fn) { |
| 397 | if (auto *LP = BB.getLandingPadInst()) { |
| 398 | LPads.push_back(LP); |
| 399 | } else if (BB.getFirstNonPHI()->isEHPad()) { |
| 400 | ForExplicitEH = true; |
| 401 | break; |
| 402 | } |
| 403 | if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator())) |
| 404 | Resumes.push_back(Resume); |
| 405 | } |
| 406 | |
| 407 | if (ForExplicitEH) |
| 408 | return prepareExplicitEH(Fn); |
| 409 | |
| 410 | // No need to prepare functions that lack landing pads. |
| 411 | if (LPads.empty()) |
| 412 | return false; |
| 413 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 414 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 415 | LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 416 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 417 | // If there were any landing pads, prepareExceptionHandlers will make changes. |
| 418 | prepareExceptionHandlers(Fn, LPads); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 419 | return true; |
| 420 | } |
| 421 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 422 | bool WinEHPrepare::doFinalization(Module &M) { return false; } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 423 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 424 | void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const { |
| 425 | AU.addRequired<DominatorTreeWrapperPass>(); |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 426 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 427 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 428 | |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 429 | static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler, |
| 430 | Constant *&Selector, BasicBlock *&NextBB); |
| 431 | |
| 432 | // Finds blocks reachable from the starting set Worklist. Does not follow unwind |
| 433 | // edges or blocks listed in StopPoints. |
| 434 | static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs, |
| 435 | SetVector<BasicBlock *> &Worklist, |
| 436 | const SetVector<BasicBlock *> *StopPoints) { |
| 437 | while (!Worklist.empty()) { |
| 438 | BasicBlock *BB = Worklist.pop_back_val(); |
| 439 | |
| 440 | // Don't cross blocks that we should stop at. |
| 441 | if (StopPoints && StopPoints->count(BB)) |
| 442 | continue; |
| 443 | |
| 444 | if (!ReachableBBs.insert(BB).second) |
| 445 | continue; // Already visited. |
| 446 | |
| 447 | // Don't follow unwind edges of invokes. |
| 448 | if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { |
| 449 | Worklist.insert(II->getNormalDest()); |
| 450 | continue; |
| 451 | } |
| 452 | |
| 453 | // Otherwise, follow all successors. |
| 454 | Worklist.insert(succ_begin(BB), succ_end(BB)); |
| 455 | } |
| 456 | } |
| 457 | |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 458 | // Attempt to find an instruction where a block can be split before |
| 459 | // a call to llvm.eh.begincatch and its operands. If the block |
| 460 | // begins with the begincatch call or one of its adjacent operands |
| 461 | // the block will not be split. |
| 462 | static Instruction *findBeginCatchSplitPoint(BasicBlock *BB, |
| 463 | IntrinsicInst *II) { |
| 464 | // If the begincatch call is already the first instruction in the block, |
| 465 | // don't split. |
| 466 | Instruction *FirstNonPHI = BB->getFirstNonPHI(); |
| 467 | if (II == FirstNonPHI) |
| 468 | return nullptr; |
| 469 | |
| 470 | // If either operand is in the same basic block as the instruction and |
| 471 | // isn't used by another instruction before the begincatch call, include it |
| 472 | // in the split block. |
| 473 | auto *Op0 = dyn_cast<Instruction>(II->getOperand(0)); |
| 474 | auto *Op1 = dyn_cast<Instruction>(II->getOperand(1)); |
| 475 | |
| 476 | Instruction *I = II->getPrevNode(); |
| 477 | Instruction *LastI = II; |
| 478 | |
| 479 | while (I == Op0 || I == Op1) { |
| 480 | // If the block begins with one of the operands and there are no other |
| 481 | // instructions between the operand and the begincatch call, don't split. |
| 482 | if (I == FirstNonPHI) |
| 483 | return nullptr; |
| 484 | |
| 485 | LastI = I; |
| 486 | I = I->getPrevNode(); |
| 487 | } |
| 488 | |
| 489 | // If there is at least one instruction in the block before the begincatch |
| 490 | // call and its operands, split the block at either the begincatch or |
| 491 | // its operand. |
| 492 | return LastI; |
| 493 | } |
| 494 | |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 495 | /// Find all points where exceptional control rejoins normal control flow via |
| 496 | /// llvm.eh.endcatch. Add them to the normal bb reachability worklist. |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 497 | void WinEHPrepare::findCXXEHReturnPoints( |
| 498 | Function &F, SetVector<BasicBlock *> &EHReturnBlocks) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 499 | for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { |
| 500 | BasicBlock *BB = BBI; |
| 501 | for (Instruction &I : *BB) { |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 502 | if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) { |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 503 | Instruction *SplitPt = |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 504 | findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I)); |
| 505 | if (SplitPt) { |
| 506 | // Split the block before the llvm.eh.begincatch call to allow |
| 507 | // cleanup and catch code to be distinguished later. |
| 508 | // Do not update BBI because we still need to process the |
| 509 | // portion of the block that we are splitting off. |
Andrew Kaylor | a33f159 | 2015-04-29 17:21:26 +0000 | [diff] [blame] | 510 | SplitBlock(BB, SplitPt, DT); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 511 | break; |
| 512 | } |
| 513 | } |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 514 | if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) { |
| 515 | // Split the block after the call to llvm.eh.endcatch if there is |
| 516 | // anything other than an unconditional branch, or if the successor |
| 517 | // starts with a phi. |
| 518 | auto *Br = dyn_cast<BranchInst>(I.getNextNode()); |
| 519 | if (!Br || !Br->isUnconditional() || |
| 520 | isa<PHINode>(Br->getSuccessor(0)->begin())) { |
| 521 | DEBUG(dbgs() << "splitting block " << BB->getName() |
| 522 | << " with llvm.eh.endcatch\n"); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 523 | BBI = SplitBlock(BB, I.getNextNode(), DT); |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 524 | } |
| 525 | // The next BB is normal control flow. |
| 526 | EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0)); |
| 527 | break; |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | static bool isCatchAllLandingPad(const BasicBlock *BB) { |
| 534 | const LandingPadInst *LP = BB->getLandingPadInst(); |
| 535 | if (!LP) |
| 536 | return false; |
| 537 | unsigned N = LP->getNumClauses(); |
| 538 | return (N > 0 && LP->isCatch(N - 1) && |
| 539 | isa<ConstantPointerNull>(LP->getClause(N - 1))); |
| 540 | } |
| 541 | |
| 542 | /// Find all points where exceptions control rejoins normal control flow via |
| 543 | /// selector dispatch. |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 544 | void WinEHPrepare::findSEHEHReturnPoints( |
| 545 | Function &F, SetVector<BasicBlock *> &EHReturnBlocks) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 546 | for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { |
| 547 | BasicBlock *BB = BBI; |
| 548 | // If the landingpad is a catch-all, treat the whole lpad as if it is |
| 549 | // reachable from normal control flow. |
| 550 | // FIXME: This is imprecise. We need a better way of identifying where a |
| 551 | // catch-all starts and cleanups stop. As far as LLVM is concerned, there |
| 552 | // is no difference. |
| 553 | if (isCatchAllLandingPad(BB)) { |
| 554 | EHReturnBlocks.insert(BB); |
| 555 | continue; |
| 556 | } |
| 557 | |
| 558 | BasicBlock *CatchHandler; |
| 559 | BasicBlock *NextBB; |
| 560 | Constant *Selector; |
| 561 | if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) { |
Reid Kleckner | ed012db | 2015-07-08 18:08:52 +0000 | [diff] [blame] | 562 | // Split the edge if there are multiple predecessors. This creates a place |
| 563 | // where we can insert EH recovery code. |
| 564 | if (!CatchHandler->getSinglePredecessor()) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 565 | DEBUG(dbgs() << "splitting EH return edge from " << BB->getName() |
| 566 | << " to " << CatchHandler->getName() << '\n'); |
| 567 | BBI = CatchHandler = SplitCriticalEdge( |
| 568 | BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler)); |
| 569 | } |
| 570 | EHReturnBlocks.insert(CatchHandler); |
| 571 | } |
| 572 | } |
| 573 | } |
| 574 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 575 | void WinEHPrepare::identifyEHBlocks(Function &F, |
| 576 | SmallVectorImpl<LandingPadInst *> &LPads) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 577 | DEBUG(dbgs() << "Demoting values live across exception handlers in function " |
| 578 | << F.getName() << '\n'); |
| 579 | |
| 580 | // Build a set of all non-exceptional blocks and exceptional blocks. |
| 581 | // - Non-exceptional blocks are blocks reachable from the entry block while |
| 582 | // not following invoke unwind edges. |
| 583 | // - Exceptional blocks are blocks reachable from landingpads. Analysis does |
| 584 | // not follow llvm.eh.endcatch blocks, which mark a transition from |
| 585 | // exceptional to normal control. |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 586 | |
| 587 | if (Personality == EHPersonality::MSVC_CXX) |
| 588 | findCXXEHReturnPoints(F, EHReturnBlocks); |
| 589 | else |
| 590 | findSEHEHReturnPoints(F, EHReturnBlocks); |
| 591 | |
| 592 | DEBUG({ |
| 593 | dbgs() << "identified the following blocks as EH return points:\n"; |
| 594 | for (BasicBlock *BB : EHReturnBlocks) |
| 595 | dbgs() << " " << BB->getName() << '\n'; |
| 596 | }); |
| 597 | |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 598 | // Join points should not have phis at this point, unless they are a |
| 599 | // landingpad, in which case we will demote their phis later. |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 600 | #ifndef NDEBUG |
| 601 | for (BasicBlock *BB : EHReturnBlocks) |
| 602 | assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) && |
| 603 | "non-lpad EH return block has phi"); |
| 604 | #endif |
| 605 | |
| 606 | // Normal blocks are the blocks reachable from the entry block and all EH |
| 607 | // return points. |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 608 | SetVector<BasicBlock *> Worklist; |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 609 | Worklist = EHReturnBlocks; |
| 610 | Worklist.insert(&F.getEntryBlock()); |
| 611 | findReachableBlocks(NormalBlocks, Worklist, nullptr); |
| 612 | DEBUG({ |
| 613 | dbgs() << "marked the following blocks as normal:\n"; |
| 614 | for (BasicBlock *BB : NormalBlocks) |
| 615 | dbgs() << " " << BB->getName() << '\n'; |
| 616 | }); |
| 617 | |
| 618 | // Exceptional blocks are the blocks reachable from landingpads that don't |
| 619 | // cross EH return points. |
| 620 | Worklist.clear(); |
| 621 | for (auto *LPI : LPads) |
| 622 | Worklist.insert(LPI->getParent()); |
| 623 | findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks); |
| 624 | DEBUG({ |
| 625 | dbgs() << "marked the following blocks as exceptional:\n"; |
| 626 | for (BasicBlock *BB : EHBlocks) |
| 627 | dbgs() << " " << BB->getName() << '\n'; |
| 628 | }); |
| 629 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 630 | } |
| 631 | |
| 632 | /// Ensure that all values live into and out of exception handlers are stored |
| 633 | /// in memory. |
| 634 | /// FIXME: This falls down when values are defined in one handler and live into |
| 635 | /// another handler. For example, a cleanup defines a value used only by a |
| 636 | /// catch handler. |
| 637 | void WinEHPrepare::demoteValuesLiveAcrossHandlers( |
| 638 | Function &F, SmallVectorImpl<LandingPadInst *> &LPads) { |
| 639 | DEBUG(dbgs() << "Demoting values live across exception handlers in function " |
| 640 | << F.getName() << '\n'); |
| 641 | |
| 642 | // identifyEHBlocks() should have been called before this function. |
| 643 | assert(!NormalBlocks.empty()); |
| 644 | |
Reid Kleckner | 7ea7708 | 2015-07-10 22:21:54 +0000 | [diff] [blame] | 645 | // Try to avoid demoting EH pointer and selector values. They get in the way |
| 646 | // of our pattern matching. |
| 647 | SmallPtrSet<Instruction *, 10> EHVals; |
| 648 | for (BasicBlock &BB : F) { |
| 649 | LandingPadInst *LP = BB.getLandingPadInst(); |
| 650 | if (!LP) |
| 651 | continue; |
| 652 | EHVals.insert(LP); |
| 653 | for (User *U : LP->users()) { |
| 654 | auto *EI = dyn_cast<ExtractValueInst>(U); |
| 655 | if (!EI) |
| 656 | continue; |
| 657 | EHVals.insert(EI); |
| 658 | for (User *U2 : EI->users()) { |
| 659 | if (auto *PN = dyn_cast<PHINode>(U2)) |
| 660 | EHVals.insert(PN); |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 665 | SetVector<Argument *> ArgsToDemote; |
| 666 | SetVector<Instruction *> InstrsToDemote; |
| 667 | for (BasicBlock &BB : F) { |
| 668 | bool IsNormalBB = NormalBlocks.count(&BB); |
| 669 | bool IsEHBB = EHBlocks.count(&BB); |
| 670 | if (!IsNormalBB && !IsEHBB) |
| 671 | continue; // Blocks that are neither normal nor EH are unreachable. |
| 672 | for (Instruction &I : BB) { |
| 673 | for (Value *Op : I.operands()) { |
| 674 | // Don't demote static allocas, constants, and labels. |
| 675 | if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op)) |
| 676 | continue; |
| 677 | auto *AI = dyn_cast<AllocaInst>(Op); |
| 678 | if (AI && AI->isStaticAlloca()) |
| 679 | continue; |
| 680 | |
| 681 | if (auto *Arg = dyn_cast<Argument>(Op)) { |
| 682 | if (IsEHBB) { |
| 683 | DEBUG(dbgs() << "Demoting argument " << *Arg |
| 684 | << " used by EH instr: " << I << "\n"); |
| 685 | ArgsToDemote.insert(Arg); |
| 686 | } |
| 687 | continue; |
| 688 | } |
| 689 | |
Reid Kleckner | 7ea7708 | 2015-07-10 22:21:54 +0000 | [diff] [blame] | 690 | // Don't demote EH values. |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 691 | auto *OpI = cast<Instruction>(Op); |
Reid Kleckner | 7ea7708 | 2015-07-10 22:21:54 +0000 | [diff] [blame] | 692 | if (EHVals.count(OpI)) |
| 693 | continue; |
| 694 | |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 695 | BasicBlock *OpBB = OpI->getParent(); |
| 696 | // If a value is produced and consumed in the same BB, we don't need to |
| 697 | // demote it. |
| 698 | if (OpBB == &BB) |
| 699 | continue; |
| 700 | bool IsOpNormalBB = NormalBlocks.count(OpBB); |
| 701 | bool IsOpEHBB = EHBlocks.count(OpBB); |
| 702 | if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) { |
| 703 | DEBUG({ |
| 704 | dbgs() << "Demoting instruction live in-out from EH:\n"; |
| 705 | dbgs() << "Instr: " << *OpI << '\n'; |
| 706 | dbgs() << "User: " << I << '\n'; |
| 707 | }); |
| 708 | InstrsToDemote.insert(OpI); |
| 709 | } |
| 710 | } |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | // Demote values live into and out of handlers. |
| 715 | // FIXME: This demotion is inefficient. We should insert spills at the point |
| 716 | // of definition, insert one reload in each handler that uses the value, and |
| 717 | // insert reloads in the BB used to rejoin normal control flow. |
| 718 | Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt(); |
| 719 | for (Instruction *I : InstrsToDemote) |
| 720 | DemoteRegToStack(*I, false, AllocaInsertPt); |
| 721 | |
| 722 | // Demote arguments separately, and only for uses in EH blocks. |
| 723 | for (Argument *Arg : ArgsToDemote) { |
| 724 | auto *Slot = new AllocaInst(Arg->getType(), nullptr, |
| 725 | Arg->getName() + ".reg2mem", AllocaInsertPt); |
| 726 | SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end()); |
| 727 | for (User *U : Users) { |
| 728 | auto *I = dyn_cast<Instruction>(U); |
| 729 | if (I && EHBlocks.count(I->getParent())) { |
| 730 | auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I); |
| 731 | U->replaceUsesOfWith(Arg, Reload); |
| 732 | } |
| 733 | } |
| 734 | new StoreInst(Arg, Slot, AllocaInsertPt); |
| 735 | } |
| 736 | |
| 737 | // Demote landingpad phis, as the landingpad will be removed from the machine |
| 738 | // CFG. |
| 739 | for (LandingPadInst *LPI : LPads) { |
| 740 | BasicBlock *BB = LPI->getParent(); |
| 741 | while (auto *Phi = dyn_cast<PHINode>(BB->begin())) |
| 742 | DemotePHIToStack(Phi, AllocaInsertPt); |
| 743 | } |
| 744 | |
| 745 | DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and " |
| 746 | << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n"); |
| 747 | } |
| 748 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 749 | bool WinEHPrepare::prepareExceptionHandlers( |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 750 | Function &F, SmallVectorImpl<LandingPadInst *> &LPads) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 751 | // Don't run on functions that are already prepared. |
| 752 | for (LandingPadInst *LPad : LPads) { |
| 753 | BasicBlock *LPadBB = LPad->getParent(); |
| 754 | for (Instruction &Inst : *LPadBB) |
| 755 | if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) |
| 756 | return false; |
| 757 | } |
| 758 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 759 | identifyEHBlocks(F, LPads); |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 760 | demoteValuesLiveAcrossHandlers(F, LPads); |
| 761 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 762 | // These containers are used to re-map frame variables that are used in |
| 763 | // outlined catch and cleanup handlers. They will be populated as the |
| 764 | // handlers are outlined. |
| 765 | FrameVarInfoMap FrameVarInfo; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 766 | |
| 767 | bool HandlersOutlined = false; |
| 768 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 769 | Module *M = F.getParent(); |
| 770 | LLVMContext &Context = M->getContext(); |
| 771 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 772 | // Create a new function to receive the handler contents. |
| 773 | PointerType *Int8PtrType = Type::getInt8PtrTy(Context); |
| 774 | Type *Int32Type = Type::getInt32Ty(Context); |
Reid Kleckner | 52b0779 | 2015-03-12 01:45:37 +0000 | [diff] [blame] | 775 | Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 776 | |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 777 | if (isAsynchronousEHPersonality(Personality)) { |
| 778 | // FIXME: Switch the ehptr type to i32 and then switch this. |
| 779 | SEHExceptionCodeSlot = |
| 780 | new AllocaInst(Int8PtrType, nullptr, "seh_exception_code", |
| 781 | F.getEntryBlock().getFirstInsertionPt()); |
| 782 | } |
| 783 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 784 | // In order to handle the case where one outlined catch handler returns |
| 785 | // to a block within another outlined catch handler that would otherwise |
| 786 | // be unreachable, we need to outline the nested landing pad before we |
| 787 | // outline the landing pad which encloses it. |
Manuel Klimek | b00d42c | 2015-05-21 15:38:25 +0000 | [diff] [blame] | 788 | if (!isAsynchronousEHPersonality(Personality)) |
| 789 | std::sort(LPads.begin(), LPads.end(), |
| 790 | [this](LandingPadInst *const &L, LandingPadInst *const &R) { |
| 791 | return DT->properlyDominates(R->getParent(), L->getParent()); |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 792 | }); |
| 793 | |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 794 | // This container stores the llvm.eh.recover and IndirectBr instructions |
| 795 | // that make up the body of each landing pad after it has been outlined. |
| 796 | // We need to defer the population of the target list for the indirectbr |
| 797 | // until all landing pads have been outlined so that we can handle the |
| 798 | // case of blocks in the target that are reached only from nested |
| 799 | // landing pads. |
| 800 | SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls; |
| 801 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 802 | for (LandingPadInst *LPad : LPads) { |
| 803 | // Look for evidence that this landingpad has already been processed. |
| 804 | bool LPadHasActionList = false; |
| 805 | BasicBlock *LPadBB = LPad->getParent(); |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 806 | for (Instruction &Inst : *LPadBB) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 807 | if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) { |
| 808 | LPadHasActionList = true; |
| 809 | break; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 810 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 811 | } |
| 812 | |
| 813 | // If we've already outlined the handlers for this landingpad, |
| 814 | // there's nothing more to do here. |
| 815 | if (LPadHasActionList) |
| 816 | continue; |
| 817 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 818 | // If either of the values in the aggregate returned by the landing pad is |
| 819 | // extracted and stored to memory, promote the stored value to a register. |
| 820 | promoteLandingPadValues(LPad); |
| 821 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 822 | LandingPadActions Actions; |
| 823 | mapLandingPadBlocks(LPad, Actions); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 824 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 825 | HandlersOutlined |= !Actions.actions().empty(); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 826 | for (ActionHandler *Action : Actions) { |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 827 | if (Action->hasBeenProcessed()) |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 828 | continue; |
| 829 | BasicBlock *StartBB = Action->getStartBlock(); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 830 | |
| 831 | // SEH doesn't do any outlining for catches. Instead, pass the handler |
| 832 | // basic block addr to llvm.eh.actions and list the block as a return |
| 833 | // target. |
| 834 | if (isAsynchronousEHPersonality(Personality)) { |
| 835 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 836 | processSEHCatchHandler(CatchAction, StartBB); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 837 | continue; |
| 838 | } |
| 839 | } |
| 840 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 841 | outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo); |
| 842 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 843 | |
Reid Kleckner | 2c3ccaa | 2015-04-24 16:22:19 +0000 | [diff] [blame] | 844 | // Split the block after the landingpad instruction so that it is just a |
| 845 | // call to llvm.eh.actions followed by indirectbr. |
| 846 | assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed"); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 847 | SplitBlock(LPadBB, LPad->getNextNode(), DT); |
Reid Kleckner | 2c3ccaa | 2015-04-24 16:22:19 +0000 | [diff] [blame] | 848 | // Erase the branch inserted by the split so we can insert indirectbr. |
| 849 | LPadBB->getTerminator()->eraseFromParent(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 850 | |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 851 | // Replace all extracted values with undef and ultimately replace the |
| 852 | // landingpad with undef. |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 853 | SmallVector<Instruction *, 4> SEHCodeUses; |
| 854 | SmallVector<Instruction *, 4> EHUndefs; |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 855 | for (User *U : LPad->users()) { |
| 856 | auto *E = dyn_cast<ExtractValueInst>(U); |
| 857 | if (!E) |
| 858 | continue; |
| 859 | assert(E->getNumIndices() == 1 && |
| 860 | "Unexpected operation: extracting both landing pad values"); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 861 | unsigned Idx = *E->idx_begin(); |
| 862 | assert((Idx == 0 || Idx == 1) && "unexpected index"); |
| 863 | if (Idx == 0 && isAsynchronousEHPersonality(Personality)) |
| 864 | SEHCodeUses.push_back(E); |
| 865 | else |
| 866 | EHUndefs.push_back(E); |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 867 | } |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 868 | for (Instruction *E : EHUndefs) { |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 869 | E->replaceAllUsesWith(UndefValue::get(E->getType())); |
| 870 | E->eraseFromParent(); |
| 871 | } |
| 872 | LPad->replaceAllUsesWith(UndefValue::get(LPad->getType())); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 873 | |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 874 | // Rewrite uses of the exception pointer to loads of an alloca. |
Reid Kleckner | 7ea7708 | 2015-07-10 22:21:54 +0000 | [diff] [blame] | 875 | while (!SEHCodeUses.empty()) { |
| 876 | Instruction *E = SEHCodeUses.pop_back_val(); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 877 | SmallVector<Use *, 4> Uses; |
| 878 | for (Use &U : E->uses()) |
| 879 | Uses.push_back(&U); |
| 880 | for (Use *U : Uses) { |
| 881 | auto *I = cast<Instruction>(U->getUser()); |
| 882 | if (isa<ResumeInst>(I)) |
| 883 | continue; |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 884 | if (auto *Phi = dyn_cast<PHINode>(I)) |
Reid Kleckner | 7ea7708 | 2015-07-10 22:21:54 +0000 | [diff] [blame] | 885 | SEHCodeUses.push_back(Phi); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 886 | else |
Reid Kleckner | 7ea7708 | 2015-07-10 22:21:54 +0000 | [diff] [blame] | 887 | U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I)); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 888 | } |
| 889 | E->replaceAllUsesWith(UndefValue::get(E->getType())); |
| 890 | E->eraseFromParent(); |
| 891 | } |
| 892 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 893 | // Add a call to describe the actions for this landing pad. |
| 894 | std::vector<Value *> ActionArgs; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 895 | for (ActionHandler *Action : Actions) { |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 896 | // Action codes from docs are: 0 cleanup, 1 catch. |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 897 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 898 | ActionArgs.push_back(ConstantInt::get(Int32Type, 1)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 899 | ActionArgs.push_back(CatchAction->getSelector()); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 900 | // Find the frame escape index of the exception object alloca in the |
| 901 | // parent. |
| 902 | int FrameEscapeIdx = -1; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 903 | Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar()); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 904 | if (EHObj && !isa<ConstantPointerNull>(EHObj)) { |
| 905 | auto I = FrameVarInfo.find(EHObj); |
| 906 | assert(I != FrameVarInfo.end() && |
| 907 | "failed to map llvm.eh.begincatch var"); |
| 908 | FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I); |
| 909 | } |
| 910 | ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 911 | } else { |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 912 | ActionArgs.push_back(ConstantInt::get(Int32Type, 0)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 913 | } |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 914 | ActionArgs.push_back(Action->getHandlerBlockOrFunc()); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 915 | } |
| 916 | CallInst *Recover = |
Reid Kleckner | 2c3ccaa | 2015-04-24 16:22:19 +0000 | [diff] [blame] | 917 | CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 918 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 919 | SetVector<BasicBlock *> ReturnTargets; |
| 920 | for (ActionHandler *Action : Actions) { |
| 921 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 922 | const auto &CatchTargets = CatchAction->getReturnTargets(); |
| 923 | ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end()); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 924 | } |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 925 | } |
| 926 | IndirectBrInst *Branch = |
| 927 | IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB); |
| 928 | for (BasicBlock *Target : ReturnTargets) |
| 929 | Branch->addDestination(Target); |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 930 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 931 | if (!isAsynchronousEHPersonality(Personality)) { |
| 932 | // C++ EH must repopulate the targets later to handle the case of |
| 933 | // targets that are reached indirectly through nested landing pads. |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 934 | LPadImpls.push_back(std::make_pair(Recover, Branch)); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 935 | } |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 936 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 937 | } // End for each landingpad |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 938 | |
| 939 | // If nothing got outlined, there is no more processing to be done. |
| 940 | if (!HandlersOutlined) |
| 941 | return false; |
| 942 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 943 | // Replace any nested landing pad stubs with the correct action handler. |
| 944 | // This must be done before we remove unreachable blocks because it |
| 945 | // cleans up references to outlined blocks that will be deleted. |
| 946 | for (auto &LPadPair : NestedLPtoOriginalLP) |
| 947 | completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo); |
Andrew Kaylor | 67d3c03 | 2015-04-08 20:57:22 +0000 | [diff] [blame] | 948 | NestedLPtoOriginalLP.clear(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 949 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 950 | // Update the indirectbr instructions' target lists if necessary. |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 951 | SetVector<BasicBlock*> CheckedTargets; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 952 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 953 | for (auto &LPadImplPair : LPadImpls) { |
| 954 | IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first); |
| 955 | IndirectBrInst *Branch = LPadImplPair.second; |
| 956 | |
| 957 | // Get a list of handlers called by |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 958 | parseEHActions(Recover, ActionList); |
| 959 | |
| 960 | // Add an indirect branch listing possible successors of the catch handlers. |
| 961 | SetVector<BasicBlock *> ReturnTargets; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 962 | for (const auto &Action : ActionList) { |
| 963 | if (auto *CA = dyn_cast<CatchHandler>(Action.get())) { |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 964 | Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc()); |
| 965 | getPossibleReturnTargets(&F, Handler, ReturnTargets); |
| 966 | } |
| 967 | } |
Andrew Kaylor | 0ddaf2b | 2015-05-12 00:13:51 +0000 | [diff] [blame] | 968 | ActionList.clear(); |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 969 | // Clear any targets we already knew about. |
| 970 | for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) { |
| 971 | BasicBlock *KnownTarget = Branch->getDestination(I); |
| 972 | if (ReturnTargets.count(KnownTarget)) |
| 973 | ReturnTargets.remove(KnownTarget); |
| 974 | } |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 975 | for (BasicBlock *Target : ReturnTargets) { |
| 976 | Branch->addDestination(Target); |
| 977 | // The target may be a block that we excepted to get pruned. |
| 978 | // If it is, it may contain a call to llvm.eh.endcatch. |
| 979 | if (CheckedTargets.insert(Target)) { |
| 980 | // Earlier preparations guarantee that all calls to llvm.eh.endcatch |
| 981 | // will be followed by an unconditional branch. |
| 982 | auto *Br = dyn_cast<BranchInst>(Target->getTerminator()); |
| 983 | if (Br && Br->isUnconditional() && |
| 984 | Br != Target->getFirstNonPHIOrDbgOrLifetime()) { |
| 985 | Instruction *Prev = Br->getPrevNode(); |
| 986 | if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>())) |
| 987 | Prev->eraseFromParent(); |
| 988 | } |
| 989 | } |
| 990 | } |
| 991 | } |
| 992 | LPadImpls.clear(); |
| 993 | |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 994 | F.addFnAttr("wineh-parent", F.getName()); |
| 995 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 996 | // Delete any blocks that were only used by handlers that were outlined above. |
| 997 | removeUnreachableBlocks(F); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 998 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 999 | BasicBlock *Entry = &F.getEntryBlock(); |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1000 | IRBuilder<> Builder(F.getParent()->getContext()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1001 | Builder.SetInsertPoint(Entry->getFirstInsertionPt()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1002 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1003 | Function *FrameEscapeFn = |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1004 | Intrinsic::getDeclaration(M, Intrinsic::localescape); |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1005 | Function *RecoverFrameFn = |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1006 | Intrinsic::getDeclaration(M, Intrinsic::localrecover); |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1007 | SmallVector<Value *, 8> AllocasToEscape; |
| 1008 | |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1009 | // Scan the entry block for an existing call to llvm.localescape. We need to |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1010 | // keep escaping those objects. |
| 1011 | for (Instruction &I : F.front()) { |
| 1012 | auto *II = dyn_cast<IntrinsicInst>(&I); |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1013 | if (II && II->getIntrinsicID() == Intrinsic::localescape) { |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1014 | auto Args = II->arg_operands(); |
| 1015 | AllocasToEscape.append(Args.begin(), Args.end()); |
| 1016 | II->eraseFromParent(); |
| 1017 | break; |
| 1018 | } |
| 1019 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1020 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1021 | // Finally, replace all of the temporary allocas for frame variables used in |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1022 | // the outlined handlers with calls to llvm.localrecover. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1023 | for (auto &VarInfoEntry : FrameVarInfo) { |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 1024 | Value *ParentVal = VarInfoEntry.first; |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1025 | TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second; |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 1026 | AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal); |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 1027 | |
Reid Kleckner | b401941 | 2015-04-06 18:50:38 +0000 | [diff] [blame] | 1028 | // FIXME: We should try to sink unescaped allocas from the parent frame into |
| 1029 | // the child frame. If the alloca is escaped, we have to use the lifetime |
| 1030 | // markers to ensure that the alloca is only live within the child frame. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1031 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1032 | // Add this alloca to the list of things to escape. |
| 1033 | AllocasToEscape.push_back(ParentAlloca); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1034 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1035 | // Next replace all outlined allocas that are mapped to it. |
| 1036 | for (AllocaInst *TempAlloca : Allocas) { |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 1037 | if (TempAlloca == getCatchObjectSentinel()) |
| 1038 | continue; // Skip catch parameter sentinels. |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1039 | Function *HandlerFn = TempAlloca->getParent()->getParent(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1040 | llvm::Value *FP = HandlerToParentFP[HandlerFn]; |
| 1041 | assert(FP); |
| 1042 | |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1043 | // FIXME: Sink this localrecover into the blocks where it is used. |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1044 | Builder.SetInsertPoint(TempAlloca); |
| 1045 | Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc()); |
| 1046 | Value *RecoverArgs[] = { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1047 | Builder.CreateBitCast(&F, Int8PtrType, ""), FP, |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1048 | llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)}; |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1049 | Instruction *RecoveredAlloca = |
| 1050 | Builder.CreateCall(RecoverFrameFn, RecoverArgs); |
| 1051 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1052 | // Add a pointer bitcast if the alloca wasn't an i8. |
| 1053 | if (RecoveredAlloca->getType() != TempAlloca->getType()) { |
| 1054 | RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8"); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1055 | RecoveredAlloca = cast<Instruction>( |
| 1056 | Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType())); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1057 | } |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1058 | TempAlloca->replaceAllUsesWith(RecoveredAlloca); |
| 1059 | TempAlloca->removeFromParent(); |
| 1060 | RecoveredAlloca->takeName(TempAlloca); |
| 1061 | delete TempAlloca; |
| 1062 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1063 | } // End for each FrameVarInfo entry. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1064 | |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 1065 | // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1066 | // block. |
| 1067 | Builder.SetInsertPoint(&F.getEntryBlock().back()); |
| 1068 | Builder.CreateCall(FrameEscapeFn, AllocasToEscape); |
| 1069 | |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1070 | if (SEHExceptionCodeSlot) { |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 1071 | if (isAllocaPromotable(SEHExceptionCodeSlot)) { |
| 1072 | SmallPtrSet<BasicBlock *, 4> UserBlocks; |
| 1073 | for (User *U : SEHExceptionCodeSlot->users()) { |
| 1074 | if (auto *Inst = dyn_cast<Instruction>(U)) |
| 1075 | UserBlocks.insert(Inst->getParent()); |
| 1076 | } |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1077 | PromoteMemToReg(SEHExceptionCodeSlot, *DT); |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 1078 | // After the promotion, kill off dead instructions. |
| 1079 | for (BasicBlock *BB : UserBlocks) |
| 1080 | SimplifyInstructionsInBlock(BB, LibInfo); |
| 1081 | } |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1082 | } |
| 1083 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1084 | // Clean up the handler action maps we created for this function |
| 1085 | DeleteContainerSeconds(CatchHandlerMap); |
| 1086 | CatchHandlerMap.clear(); |
| 1087 | DeleteContainerSeconds(CleanupHandlerMap); |
| 1088 | CleanupHandlerMap.clear(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1089 | HandlerToParentFP.clear(); |
| 1090 | DT = nullptr; |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 1091 | LibInfo = nullptr; |
Ahmed Bougacha | ed363c5 | 2015-05-06 01:28:58 +0000 | [diff] [blame] | 1092 | SEHExceptionCodeSlot = nullptr; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1093 | EHBlocks.clear(); |
| 1094 | NormalBlocks.clear(); |
| 1095 | EHReturnBlocks.clear(); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1096 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1097 | return HandlersOutlined; |
| 1098 | } |
| 1099 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1100 | void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) { |
| 1101 | // If the return values of the landing pad instruction are extracted and |
| 1102 | // stored to memory, we want to promote the store locations to reg values. |
| 1103 | SmallVector<AllocaInst *, 2> EHAllocas; |
| 1104 | |
| 1105 | // The landingpad instruction returns an aggregate value. Typically, its |
| 1106 | // value will be passed to a pair of extract value instructions and the |
| 1107 | // results of those extracts are often passed to store instructions. |
| 1108 | // In unoptimized code the stored value will often be loaded and then stored |
| 1109 | // again. |
| 1110 | for (auto *U : LPad->users()) { |
| 1111 | ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U); |
| 1112 | if (!Extract) |
| 1113 | continue; |
| 1114 | |
| 1115 | for (auto *EU : Extract->users()) { |
| 1116 | if (auto *Store = dyn_cast<StoreInst>(EU)) { |
| 1117 | auto *AV = cast<AllocaInst>(Store->getPointerOperand()); |
| 1118 | EHAllocas.push_back(AV); |
| 1119 | } |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | // We can't do this without a dominator tree. |
| 1124 | assert(DT); |
| 1125 | |
| 1126 | if (!EHAllocas.empty()) { |
| 1127 | PromoteMemToReg(EHAllocas, *DT); |
| 1128 | EHAllocas.clear(); |
| 1129 | } |
Reid Kleckner | 8676214 | 2015-04-16 00:02:04 +0000 | [diff] [blame] | 1130 | |
| 1131 | // After promotion, some extracts may be trivially dead. Remove them. |
| 1132 | SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end()); |
| 1133 | for (auto *U : Users) |
| 1134 | RecursivelyDeleteTriviallyDeadInstructions(U); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1135 | } |
| 1136 | |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 1137 | void WinEHPrepare::getPossibleReturnTargets(Function *ParentF, |
| 1138 | Function *HandlerF, |
| 1139 | SetVector<BasicBlock*> &Targets) { |
| 1140 | for (BasicBlock &BB : *HandlerF) { |
| 1141 | // If the handler contains landing pads, check for any |
| 1142 | // handlers that may return directly to a block in the |
| 1143 | // parent function. |
| 1144 | if (auto *LPI = BB.getLandingPadInst()) { |
| 1145 | IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode()); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1146 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 1147 | parseEHActions(Recover, ActionList); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1148 | for (const auto &Action : ActionList) { |
| 1149 | if (auto *CH = dyn_cast<CatchHandler>(Action.get())) { |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 1150 | Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc()); |
| 1151 | getPossibleReturnTargets(ParentF, NestedF, Targets); |
| 1152 | } |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); |
| 1157 | if (!Ret) |
| 1158 | continue; |
| 1159 | |
| 1160 | // Handler functions must always return a block address. |
| 1161 | BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue()); |
| 1162 | |
| 1163 | // If this is the handler for a nested landing pad, the |
| 1164 | // return address may have been remapped to a block in the |
| 1165 | // parent handler. We're not interested in those. |
| 1166 | if (BA->getFunction() != ParentF) |
| 1167 | continue; |
| 1168 | |
| 1169 | Targets.insert(BA->getBasicBlock()); |
| 1170 | } |
| 1171 | } |
| 1172 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1173 | void WinEHPrepare::completeNestedLandingPad(Function *ParentFn, |
| 1174 | LandingPadInst *OutlinedLPad, |
| 1175 | const LandingPadInst *OriginalLPad, |
| 1176 | FrameVarInfoMap &FrameVarInfo) { |
| 1177 | // Get the nested block and erase the unreachable instruction that was |
| 1178 | // temporarily inserted as its terminator. |
| 1179 | LLVMContext &Context = ParentFn->getContext(); |
| 1180 | BasicBlock *OutlinedBB = OutlinedLPad->getParent(); |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1181 | // If the nested landing pad was outlined before the landing pad that enclosed |
| 1182 | // it, it will already be in outlined form. In that case, we just need to see |
| 1183 | // if the returns and the enclosing branch instruction need to be updated. |
| 1184 | IndirectBrInst *Branch = |
| 1185 | dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator()); |
| 1186 | if (!Branch) { |
| 1187 | // If the landing pad wasn't in outlined form, it should be a stub with |
| 1188 | // an unreachable terminator. |
| 1189 | assert(isa<UnreachableInst>(OutlinedBB->getTerminator())); |
| 1190 | OutlinedBB->getTerminator()->eraseFromParent(); |
| 1191 | // That should leave OutlinedLPad as the last instruction in its block. |
| 1192 | assert(&OutlinedBB->back() == OutlinedLPad); |
| 1193 | } |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1194 | |
| 1195 | // The original landing pad will have already had its action intrinsic |
| 1196 | // built by the outlining loop. We need to clone that into the outlined |
| 1197 | // location. It may also be necessary to add references to the exception |
| 1198 | // variables to the outlined handler in which this landing pad is nested |
| 1199 | // and remap return instructions in the nested handlers that should return |
| 1200 | // to an address in the outlined handler. |
| 1201 | Function *OutlinedHandlerFn = OutlinedBB->getParent(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1202 | BasicBlock::const_iterator II = OriginalLPad; |
| 1203 | ++II; |
| 1204 | // The instruction after the landing pad should now be a call to eh.actions. |
| 1205 | const Instruction *Recover = II; |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1206 | const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1207 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1208 | // Remap the return target in the nested handler. |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1209 | SmallVector<BlockAddress *, 4> ActionTargets; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1210 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1211 | parseEHActions(EHActions, ActionList); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1212 | for (const auto &Action : ActionList) { |
| 1213 | auto *Catch = dyn_cast<CatchHandler>(Action.get()); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1214 | if (!Catch) |
| 1215 | continue; |
| 1216 | // The dyn_cast to function here selects C++ catch handlers and skips |
| 1217 | // SEH catch handlers. |
| 1218 | auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc()); |
| 1219 | if (!Handler) |
| 1220 | continue; |
| 1221 | // Visit all the return instructions, looking for places that return |
| 1222 | // to a location within OutlinedHandlerFn. |
| 1223 | for (BasicBlock &NestedHandlerBB : *Handler) { |
| 1224 | auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator()); |
| 1225 | if (!Ret) |
| 1226 | continue; |
| 1227 | |
| 1228 | // Handler functions must always return a block address. |
| 1229 | BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue()); |
| 1230 | // The original target will have been in the main parent function, |
| 1231 | // but if it is the address of a block that has been outlined, it |
| 1232 | // should be a block that was outlined into OutlinedHandlerFn. |
| 1233 | assert(BA->getFunction() == ParentFn); |
| 1234 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1235 | // Ignore targets that aren't part of an outlined handler function. |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1236 | if (!LPadTargetBlocks.count(BA->getBasicBlock())) |
| 1237 | continue; |
| 1238 | |
| 1239 | // If the return value is the address ofF a block that we |
| 1240 | // previously outlined into the parent handler function, replace |
| 1241 | // the return instruction and add the mapped target to the list |
| 1242 | // of possible return addresses. |
| 1243 | BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()]; |
| 1244 | assert(MappedBB->getParent() == OutlinedHandlerFn); |
| 1245 | BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB); |
| 1246 | Ret->eraseFromParent(); |
| 1247 | ReturnInst::Create(Context, NewBA, &NestedHandlerBB); |
| 1248 | ActionTargets.push_back(NewBA); |
| 1249 | } |
| 1250 | } |
Andrew Kaylor | 7a0cec3 | 2015-04-03 21:44:17 +0000 | [diff] [blame] | 1251 | ActionList.clear(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1252 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1253 | if (Branch) { |
| 1254 | // If the landing pad was already in outlined form, just update its targets. |
| 1255 | for (unsigned int I = Branch->getNumDestinations(); I > 0; --I) |
| 1256 | Branch->removeDestination(I); |
| 1257 | // Add the previously collected action targets. |
| 1258 | for (auto *Target : ActionTargets) |
| 1259 | Branch->addDestination(Target->getBasicBlock()); |
| 1260 | } else { |
| 1261 | // If the landing pad was previously stubbed out, fill in its outlined form. |
| 1262 | IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone()); |
| 1263 | OutlinedBB->getInstList().push_back(NewEHActions); |
| 1264 | |
| 1265 | // Insert an indirect branch into the outlined landing pad BB. |
| 1266 | IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB); |
| 1267 | // Add the previously collected action targets. |
| 1268 | for (auto *Target : ActionTargets) |
| 1269 | IBr->addDestination(Target->getBasicBlock()); |
| 1270 | } |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1271 | } |
| 1272 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1273 | // This function examines a block to determine whether the block ends with a |
| 1274 | // conditional branch to a catch handler based on a selector comparison. |
| 1275 | // This function is used both by the WinEHPrepare::findSelectorComparison() and |
| 1276 | // WinEHCleanupDirector::handleTypeIdFor(). |
| 1277 | static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler, |
| 1278 | Constant *&Selector, BasicBlock *&NextBB) { |
| 1279 | ICmpInst::Predicate Pred; |
| 1280 | BasicBlock *TBB, *FBB; |
| 1281 | Value *LHS, *RHS; |
| 1282 | |
| 1283 | if (!match(BB->getTerminator(), |
| 1284 | m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB))) |
| 1285 | return false; |
| 1286 | |
| 1287 | if (!match(LHS, |
| 1288 | m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) && |
| 1289 | !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector)))) |
| 1290 | return false; |
| 1291 | |
| 1292 | if (Pred == CmpInst::ICMP_EQ) { |
| 1293 | CatchHandler = TBB; |
| 1294 | NextBB = FBB; |
| 1295 | return true; |
| 1296 | } |
| 1297 | |
| 1298 | if (Pred == CmpInst::ICMP_NE) { |
| 1299 | CatchHandler = FBB; |
| 1300 | NextBB = TBB; |
| 1301 | return true; |
| 1302 | } |
| 1303 | |
| 1304 | return false; |
| 1305 | } |
| 1306 | |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 1307 | static bool isCatchBlock(BasicBlock *BB) { |
| 1308 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 1309 | II != IE; ++II) { |
| 1310 | if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>())) |
| 1311 | return true; |
| 1312 | } |
| 1313 | return false; |
| 1314 | } |
| 1315 | |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1316 | static BasicBlock *createStubLandingPad(Function *Handler) { |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1317 | // FIXME: Finish this! |
| 1318 | LLVMContext &Context = Handler->getContext(); |
| 1319 | BasicBlock *StubBB = BasicBlock::Create(Context, "stub"); |
| 1320 | Handler->getBasicBlockList().push_back(StubBB); |
| 1321 | IRBuilder<> Builder(StubBB); |
| 1322 | LandingPadInst *LPad = Builder.CreateLandingPad( |
| 1323 | llvm::StructType::get(Type::getInt8PtrTy(Context), |
| 1324 | Type::getInt32Ty(Context), nullptr), |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1325 | 0); |
Andrew Kaylor | 43e1d76 | 2015-04-23 00:20:44 +0000 | [diff] [blame] | 1326 | // Insert a call to llvm.eh.actions so that we don't try to outline this lpad. |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1327 | Function *ActionIntrin = |
| 1328 | Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 1329 | Builder.CreateCall(ActionIntrin, {}, "recover"); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1330 | LPad->setCleanup(true); |
| 1331 | Builder.CreateUnreachable(); |
| 1332 | return StubBB; |
| 1333 | } |
| 1334 | |
| 1335 | // Cycles through the blocks in an outlined handler function looking for an |
| 1336 | // invoke instruction and inserts an invoke of llvm.donothing with an empty |
| 1337 | // landing pad if none is found. The code that generates the .xdata tables for |
| 1338 | // the handler needs at least one landing pad to identify the parent function's |
| 1339 | // personality. |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1340 | void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) { |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1341 | ReturnInst *Ret = nullptr; |
Andrew Kaylor | 5f71552 | 2015-04-23 18:37:39 +0000 | [diff] [blame] | 1342 | UnreachableInst *Unreached = nullptr; |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1343 | for (BasicBlock &BB : *Handler) { |
| 1344 | TerminatorInst *Terminator = BB.getTerminator(); |
| 1345 | // If we find an invoke, there is nothing to be done. |
| 1346 | auto *II = dyn_cast<InvokeInst>(Terminator); |
| 1347 | if (II) |
| 1348 | return; |
| 1349 | // If we've already recorded a return instruction, keep looking for invokes. |
Andrew Kaylor | 5f71552 | 2015-04-23 18:37:39 +0000 | [diff] [blame] | 1350 | if (!Ret) |
| 1351 | Ret = dyn_cast<ReturnInst>(Terminator); |
| 1352 | // If we haven't recorded an unreachable instruction, try this terminator. |
| 1353 | if (!Unreached) |
| 1354 | Unreached = dyn_cast<UnreachableInst>(Terminator); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1355 | } |
| 1356 | |
| 1357 | // If we got this far, the handler contains no invokes. We should have seen |
Andrew Kaylor | 5f71552 | 2015-04-23 18:37:39 +0000 | [diff] [blame] | 1358 | // at least one return or unreachable instruction. We'll insert an invoke of |
| 1359 | // llvm.donothing ahead of that instruction. |
| 1360 | assert(Ret || Unreached); |
| 1361 | TerminatorInst *Term; |
| 1362 | if (Ret) |
| 1363 | Term = Ret; |
| 1364 | else |
| 1365 | Term = Unreached; |
| 1366 | BasicBlock *OldRetBB = Term->getParent(); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 1367 | BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1368 | // SplitBlock adds an unconditional branch instruction at the end of the |
| 1369 | // parent block. We want to replace that with an invoke call, so we can |
| 1370 | // erase it now. |
| 1371 | OldRetBB->getTerminator()->eraseFromParent(); |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1372 | BasicBlock *StubLandingPad = createStubLandingPad(Handler); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1373 | Function *F = |
| 1374 | Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing); |
| 1375 | InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB); |
| 1376 | } |
| 1377 | |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1378 | // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering |
| 1379 | // usually doesn't build LLVM IR, so that's probably the wrong place. |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 1380 | Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy, |
| 1381 | const Twine &Name, Module *M, |
| 1382 | Value *&ParentFP) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1383 | // x64 uses a two-argument prototype where the parent FP is the second |
| 1384 | // argument. x86 uses no arguments, just the incoming EBP value. |
| 1385 | LLVMContext &Context = M->getContext(); |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 1386 | Type *Int8PtrType = Type::getInt8PtrTy(Context); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1387 | FunctionType *FnType; |
| 1388 | if (TheTriple.getArch() == Triple::x86_64) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1389 | Type *ArgTys[2] = {Int8PtrType, Int8PtrType}; |
| 1390 | FnType = FunctionType::get(RetTy, ArgTys, false); |
| 1391 | } else { |
| 1392 | FnType = FunctionType::get(RetTy, None, false); |
| 1393 | } |
| 1394 | |
| 1395 | Function *Handler = |
| 1396 | Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M); |
| 1397 | BasicBlock *Entry = BasicBlock::Create(Context, "entry"); |
| 1398 | Handler->getBasicBlockList().push_front(Entry); |
| 1399 | if (TheTriple.getArch() == Triple::x86_64) { |
| 1400 | ParentFP = &(Handler->getArgumentList().back()); |
| 1401 | } else { |
| 1402 | assert(M); |
| 1403 | Function *FrameAddressFn = |
| 1404 | Intrinsic::getDeclaration(M, Intrinsic::frameaddress); |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 1405 | Function *RecoverFPFn = |
| 1406 | Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp); |
| 1407 | IRBuilder<> Builder(&Handler->getEntryBlock()); |
| 1408 | Value *EBP = |
| 1409 | Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp"); |
| 1410 | Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType); |
| 1411 | ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP}); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1412 | } |
| 1413 | return Handler; |
| 1414 | } |
| 1415 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1416 | bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn, |
| 1417 | LandingPadInst *LPad, BasicBlock *StartBB, |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1418 | FrameVarInfoMap &VarInfo) { |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1419 | Module *M = SrcFn->getParent(); |
| 1420 | LLVMContext &Context = M->getContext(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1421 | Type *Int8PtrType = Type::getInt8PtrTy(Context); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1422 | |
| 1423 | // Create a new function to receive the handler contents. |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1424 | Value *ParentFP; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1425 | Function *Handler; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1426 | if (Action->getType() == Catch) { |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 1427 | Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M, |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1428 | ParentFP); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1429 | } else { |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 1430 | Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context), |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1431 | SrcFn->getName() + ".cleanup", M, ParentFP); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1432 | } |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1433 | Handler->setPersonalityFn(SrcFn->getPersonalityFn()); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1434 | HandlerToParentFP[Handler] = ParentFP; |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 1435 | Handler->addFnAttr("wineh-parent", SrcFn->getName()); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1436 | BasicBlock *Entry = &Handler->getEntryBlock(); |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 1437 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1438 | // Generate a standard prolog to setup the frame recovery structure. |
| 1439 | IRBuilder<> Builder(Context); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1440 | Builder.SetInsertPoint(Entry); |
| 1441 | Builder.SetCurrentDebugLocation(LPad->getDebugLoc()); |
| 1442 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1443 | std::unique_ptr<WinEHCloningDirectorBase> Director; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1444 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1445 | ValueToValueMapTy VMap; |
| 1446 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1447 | LandingPadMap &LPadMap = LPadMaps[LPad]; |
| 1448 | if (!LPadMap.isInitialized()) |
| 1449 | LPadMap.mapLandingPad(LPad); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1450 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 1451 | Constant *Sel = CatchAction->getSelector(); |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1452 | Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo, |
| 1453 | LPadMap, NestedLPtoOriginalLP, DT, |
| 1454 | EHBlocks)); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1455 | LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType), |
| 1456 | ConstantInt::get(Type::getInt32Ty(Context), 1)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1457 | } else { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1458 | Director.reset( |
| 1459 | new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap)); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1460 | LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType), |
| 1461 | UndefValue::get(Type::getInt32Ty(Context))); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1462 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1463 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1464 | SmallVector<ReturnInst *, 8> Returns; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1465 | ClonedCodeInfo OutlinedFunctionInfo; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1466 | |
Andrew Kaylor | 3170e56 | 2015-03-20 21:42:54 +0000 | [diff] [blame] | 1467 | // If the start block contains PHI nodes, we need to map them. |
| 1468 | BasicBlock::iterator II = StartBB->begin(); |
| 1469 | while (auto *PN = dyn_cast<PHINode>(II)) { |
| 1470 | bool Mapped = false; |
| 1471 | // Look for PHI values that we have already mapped (such as the selector). |
| 1472 | for (Value *Val : PN->incoming_values()) { |
| 1473 | if (VMap.count(Val)) { |
| 1474 | VMap[PN] = VMap[Val]; |
| 1475 | Mapped = true; |
| 1476 | } |
| 1477 | } |
| 1478 | // If we didn't find a match for this value, map it as an undef. |
| 1479 | if (!Mapped) { |
| 1480 | VMap[PN] = UndefValue::get(PN->getType()); |
| 1481 | } |
| 1482 | ++II; |
| 1483 | } |
| 1484 | |
Andrew Kaylor | 00e5d9e | 2015-04-20 22:53:42 +0000 | [diff] [blame] | 1485 | // The landing pad value may be used by PHI nodes. It will ultimately be |
| 1486 | // eliminated, but we need it in the map for intermediate handling. |
| 1487 | VMap[LPad] = UndefValue::get(LPad->getType()); |
| 1488 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1489 | // Skip over PHIs and, if applicable, landingpad instructions. |
Andrew Kaylor | 3170e56 | 2015-03-20 21:42:54 +0000 | [diff] [blame] | 1490 | II = StartBB->getFirstInsertionPt(); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1491 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1492 | CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1493 | /*ModuleLevelChanges=*/false, Returns, "", |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1494 | &OutlinedFunctionInfo, Director.get()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1495 | |
Andrew Kaylor | 5dacfd8 | 2015-04-24 23:10:38 +0000 | [diff] [blame] | 1496 | // Move all the instructions in the cloned "entry" block into our entry block. |
| 1497 | // Depending on how the parent function was laid out, the block that will |
| 1498 | // correspond to the outlined entry block may not be the first block in the |
| 1499 | // list. We can recognize it, however, as the cloned block which has no |
| 1500 | // predecessors. Any other block wouldn't have been cloned if it didn't |
| 1501 | // have a predecessor which was also cloned. |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1502 | Function::iterator ClonedIt = std::next(Function::iterator(Entry)); |
Andrew Kaylor | 5dacfd8 | 2015-04-24 23:10:38 +0000 | [diff] [blame] | 1503 | while (!pred_empty(ClonedIt)) |
| 1504 | ++ClonedIt; |
| 1505 | BasicBlock *ClonedEntryBB = ClonedIt; |
| 1506 | assert(ClonedEntryBB); |
| 1507 | Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList()); |
| 1508 | ClonedEntryBB->eraseFromParent(); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1509 | |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1510 | // Make sure we can identify the handler's personality later. |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 1511 | addStubInvokeToHandlerIfNeeded(Handler); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1512 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1513 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 1514 | WinEHCatchDirector *CatchDirector = |
| 1515 | reinterpret_cast<WinEHCatchDirector *>(Director.get()); |
| 1516 | CatchAction->setExceptionVar(CatchDirector->getExceptionVar()); |
| 1517 | CatchAction->setReturnTargets(CatchDirector->getReturnTargets()); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1518 | |
| 1519 | // Look for blocks that are not part of the landing pad that we just |
| 1520 | // outlined but terminate with a call to llvm.eh.endcatch and a |
| 1521 | // branch to a block that is in the handler we just outlined. |
| 1522 | // These blocks will be part of a nested landing pad that intends to |
| 1523 | // return to an address in this handler. This case is best handled |
| 1524 | // after both landing pads have been outlined, so for now we'll just |
| 1525 | // save the association of the blocks in LPadTargetBlocks. The |
| 1526 | // return instructions which are created from these branches will be |
| 1527 | // replaced after all landing pads have been outlined. |
Richard Trieu | 6b1aa5f | 2015-04-15 01:21:15 +0000 | [diff] [blame] | 1528 | for (const auto MapEntry : VMap) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1529 | // VMap maps all values and blocks that were just cloned, but dead |
| 1530 | // blocks which were pruned will map to nullptr. |
| 1531 | if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr) |
| 1532 | continue; |
| 1533 | const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first); |
| 1534 | for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) { |
| 1535 | auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator()); |
| 1536 | if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1) |
| 1537 | continue; |
| 1538 | BasicBlock::iterator II = const_cast<BranchInst *>(Branch); |
| 1539 | --II; |
| 1540 | if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) { |
| 1541 | // This would indicate that a nested landing pad wants to return |
| 1542 | // to a block that is outlined into two different handlers. |
| 1543 | assert(!LPadTargetBlocks.count(MappedBB)); |
| 1544 | LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second); |
| 1545 | } |
| 1546 | } |
| 1547 | } |
| 1548 | } // End if (CatchAction) |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1549 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1550 | Action->setHandlerBlockOrFunc(Handler); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1551 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1552 | return true; |
| 1553 | } |
| 1554 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1555 | /// This BB must end in a selector dispatch. All we need to do is pass the |
| 1556 | /// handler block to llvm.eh.actions and list it as a possible indirectbr |
| 1557 | /// target. |
| 1558 | void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction, |
| 1559 | BasicBlock *StartBB) { |
| 1560 | BasicBlock *HandlerBB; |
| 1561 | BasicBlock *NextBB; |
| 1562 | Constant *Selector; |
| 1563 | bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB); |
| 1564 | if (Res) { |
| 1565 | // If this was EH dispatch, this must be a conditional branch to the handler |
| 1566 | // block. |
| 1567 | // FIXME: Handle instructions in the dispatch block. Currently we drop them, |
| 1568 | // leading to crashes if some optimization hoists stuff here. |
| 1569 | assert(CatchAction->getSelector() && HandlerBB && |
| 1570 | "expected catch EH dispatch"); |
| 1571 | } else { |
| 1572 | // This must be a catch-all. Split the block after the landingpad. |
| 1573 | assert(CatchAction->getSelector()->isNullValue() && "expected catch-all"); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 1574 | HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1575 | } |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1576 | IRBuilder<> Builder(HandlerBB->getFirstInsertionPt()); |
| 1577 | Function *EHCodeFn = Intrinsic::getDeclaration( |
| 1578 | StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 1579 | Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode"); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1580 | Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType()); |
| 1581 | Builder.CreateStore(Code, SEHExceptionCodeSlot); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1582 | CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB)); |
| 1583 | TinyPtrVector<BasicBlock *> Targets(HandlerBB); |
| 1584 | CatchAction->setReturnTargets(Targets); |
| 1585 | } |
| 1586 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1587 | void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) { |
| 1588 | // Each instance of this class should only ever be used to map a single |
| 1589 | // landing pad. |
| 1590 | assert(OriginLPad == nullptr || OriginLPad == LPad); |
| 1591 | |
| 1592 | // If the landing pad has already been mapped, there's nothing more to do. |
| 1593 | if (OriginLPad == LPad) |
| 1594 | return; |
| 1595 | |
| 1596 | OriginLPad = LPad; |
| 1597 | |
| 1598 | // The landingpad instruction returns an aggregate value. Typically, its |
| 1599 | // value will be passed to a pair of extract value instructions and the |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1600 | // results of those extracts will have been promoted to reg values before |
| 1601 | // this routine is called. |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1602 | for (auto *U : LPad->users()) { |
| 1603 | const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U); |
| 1604 | if (!Extract) |
| 1605 | continue; |
| 1606 | assert(Extract->getNumIndices() == 1 && |
| 1607 | "Unexpected operation: extracting both landing pad values"); |
| 1608 | unsigned int Idx = *(Extract->idx_begin()); |
| 1609 | assert((Idx == 0 || Idx == 1) && |
| 1610 | "Unexpected operation: extracting an unknown landing pad element"); |
| 1611 | if (Idx == 0) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1612 | ExtractedEHPtrs.push_back(Extract); |
| 1613 | } else if (Idx == 1) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1614 | ExtractedSelectors.push_back(Extract); |
| 1615 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1616 | } |
| 1617 | } |
| 1618 | |
Andrew Kaylor | f7118ae | 2015-03-27 22:31:12 +0000 | [diff] [blame] | 1619 | bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const { |
| 1620 | return BB->getLandingPadInst() == OriginLPad; |
| 1621 | } |
| 1622 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1623 | bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const { |
| 1624 | if (Inst == OriginLPad) |
| 1625 | return true; |
| 1626 | for (auto *Extract : ExtractedEHPtrs) { |
| 1627 | if (Inst == Extract) |
| 1628 | return true; |
| 1629 | } |
| 1630 | for (auto *Extract : ExtractedSelectors) { |
| 1631 | if (Inst == Extract) |
| 1632 | return true; |
| 1633 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1634 | return false; |
| 1635 | } |
| 1636 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1637 | void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue, |
| 1638 | Value *SelectorValue) const { |
| 1639 | // Remap all landing pad extract instructions to the specified values. |
| 1640 | for (auto *Extract : ExtractedEHPtrs) |
| 1641 | VMap[Extract] = EHPtrValue; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1642 | for (auto *Extract : ExtractedSelectors) |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1643 | VMap[Extract] = SelectorValue; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1644 | } |
| 1645 | |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 1646 | static bool isLocalAddressCall(const Value *V) { |
| 1647 | return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>()); |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1648 | } |
| 1649 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1650 | CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction( |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1651 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1652 | // If this is one of the boilerplate landing pad instructions, skip it. |
| 1653 | // The instruction will have already been remapped in VMap. |
| 1654 | if (LPadMap.isLandingPadSpecificInst(Inst)) |
| 1655 | return CloningDirector::SkipInstruction; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1656 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1657 | // Nested landing pads that have not already been outlined will be cloned as |
| 1658 | // stubs, with just the landingpad instruction and an unreachable instruction. |
| 1659 | // When all landingpads have been outlined, we'll replace this with the |
| 1660 | // llvm.eh.actions call and indirect branch created when the landing pad was |
| 1661 | // outlined. |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1662 | if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) { |
| 1663 | return handleLandingPad(VMap, LPad, NewBB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1664 | } |
| 1665 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1666 | // Nested landing pads that have already been outlined will be cloned in their |
| 1667 | // outlined form, but we need to intercept the ibr instruction to filter out |
| 1668 | // targets that do not return to the handler we are outlining. |
| 1669 | if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) { |
| 1670 | return handleIndirectBr(VMap, IBr, NewBB); |
| 1671 | } |
| 1672 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1673 | if (auto *Invoke = dyn_cast<InvokeInst>(Inst)) |
| 1674 | return handleInvoke(VMap, Invoke, NewBB); |
| 1675 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1676 | if (auto *Resume = dyn_cast<ResumeInst>(Inst)) |
| 1677 | return handleResume(VMap, Resume, NewBB); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1678 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1679 | if (auto *Cmp = dyn_cast<CmpInst>(Inst)) |
| 1680 | return handleCompare(VMap, Cmp, NewBB); |
| 1681 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1682 | if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) |
| 1683 | return handleBeginCatch(VMap, Inst, NewBB); |
| 1684 | if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) |
| 1685 | return handleEndCatch(VMap, Inst, NewBB); |
| 1686 | if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) |
| 1687 | return handleTypeIdFor(VMap, Inst, NewBB); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1688 | |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 1689 | // When outlining llvm.localaddress(), remap that to the second argument, |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1690 | // which is the FP of the parent. |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 1691 | if (isLocalAddressCall(Inst)) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1692 | VMap[Inst] = ParentFP; |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1693 | return CloningDirector::SkipInstruction; |
| 1694 | } |
| 1695 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1696 | // Continue with the default cloning behavior. |
| 1697 | return CloningDirector::CloneInstruction; |
| 1698 | } |
| 1699 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1700 | CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad( |
| 1701 | ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) { |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1702 | // If the instruction after the landing pad is a call to llvm.eh.actions |
| 1703 | // the landing pad has already been outlined. In this case, we should |
| 1704 | // clone it because it may return to a block in the handler we are |
| 1705 | // outlining now that would otherwise be unreachable. The landing pads |
| 1706 | // are sorted before outlining begins to enable this case to work |
| 1707 | // properly. |
| 1708 | const Instruction *NextI = LPad->getNextNode(); |
| 1709 | if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>())) |
| 1710 | return CloningDirector::CloneInstruction; |
| 1711 | |
| 1712 | // If the landing pad hasn't been outlined yet, the landing pad we are |
| 1713 | // outlining now does not dominate it and so it cannot return to a block |
| 1714 | // in this handler. In that case, we can just insert a stub landing |
| 1715 | // pad now and patch it up later. |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1716 | Instruction *NewInst = LPad->clone(); |
| 1717 | if (LPad->hasName()) |
| 1718 | NewInst->setName(LPad->getName()); |
| 1719 | // Save this correlation for later processing. |
| 1720 | NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad; |
| 1721 | VMap[LPad] = NewInst; |
| 1722 | BasicBlock::InstListType &InstList = NewBB->getInstList(); |
| 1723 | InstList.push_back(NewInst); |
| 1724 | InstList.push_back(new UnreachableInst(NewBB->getContext())); |
| 1725 | return CloningDirector::StopCloningBB; |
| 1726 | } |
| 1727 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1728 | CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch( |
| 1729 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
| 1730 | // The argument to the call is some form of the first element of the |
| 1731 | // landingpad aggregate value, but that doesn't matter. It isn't used |
| 1732 | // here. |
Reid Kleckner | 4236653 | 2015-03-03 23:20:30 +0000 | [diff] [blame] | 1733 | // The second argument is an outparameter where the exception object will be |
| 1734 | // stored. Typically the exception object is a scalar, but it can be an |
| 1735 | // aggregate when catching by value. |
| 1736 | // FIXME: Leave something behind to indicate where the exception object lives |
| 1737 | // for this handler. Should it be part of llvm.eh.actions? |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1738 | assert(ExceptionObjectVar == nullptr && "Multiple calls to " |
| 1739 | "llvm.eh.begincatch found while " |
| 1740 | "outlining catch handler."); |
| 1741 | ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts(); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 1742 | if (isa<ConstantPointerNull>(ExceptionObjectVar)) |
| 1743 | return CloningDirector::SkipInstruction; |
Reid Kleckner | aab30e1 | 2015-04-03 18:18:06 +0000 | [diff] [blame] | 1744 | assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() && |
| 1745 | "catch parameter is not static alloca"); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 1746 | Materializer.escapeCatchObject(ExceptionObjectVar); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1747 | return CloningDirector::SkipInstruction; |
| 1748 | } |
| 1749 | |
| 1750 | CloningDirector::CloningAction |
| 1751 | WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap, |
| 1752 | const Instruction *Inst, BasicBlock *NewBB) { |
| 1753 | auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst); |
| 1754 | // It might be interesting to track whether or not we are inside a catch |
| 1755 | // function, but that might make the algorithm more brittle than it needs |
| 1756 | // to be. |
| 1757 | |
| 1758 | // The end catch call can occur in one of two places: either in a |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1759 | // landingpad block that is part of the catch handlers exception mechanism, |
Andrew Kaylor | f7118ae | 2015-03-27 22:31:12 +0000 | [diff] [blame] | 1760 | // or at the end of the catch block. However, a catch-all handler may call |
| 1761 | // end catch from the original landing pad. If the call occurs in a nested |
| 1762 | // landing pad block, we must skip it and continue so that the landing pad |
| 1763 | // gets cloned. |
| 1764 | auto *ParentBB = IntrinCall->getParent(); |
| 1765 | if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB)) |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1766 | return CloningDirector::SkipInstruction; |
| 1767 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1768 | // If an end catch occurs anywhere else we want to terminate the handler |
| 1769 | // with a return to the code that follows the endcatch call. If the |
| 1770 | // next instruction is not an unconditional branch, we need to split the |
| 1771 | // block to provide a clear target for the return instruction. |
| 1772 | BasicBlock *ContinueBB; |
| 1773 | auto Next = std::next(BasicBlock::const_iterator(IntrinCall)); |
| 1774 | const BranchInst *Branch = dyn_cast<BranchInst>(Next); |
| 1775 | if (!Branch || !Branch->isUnconditional()) { |
| 1776 | // We're interrupting the cloning process at this location, so the |
| 1777 | // const_cast we're doing here will not cause a problem. |
| 1778 | ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB), |
| 1779 | const_cast<Instruction *>(cast<Instruction>(Next))); |
| 1780 | } else { |
| 1781 | ContinueBB = Branch->getSuccessor(0); |
| 1782 | } |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1783 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1784 | ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB); |
| 1785 | ReturnTargets.push_back(ContinueBB); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1786 | |
| 1787 | // We just added a terminator to the cloned block. |
| 1788 | // Tell the caller to stop processing the current basic block so that |
| 1789 | // the branch instruction will be skipped. |
| 1790 | return CloningDirector::StopCloningBB; |
| 1791 | } |
| 1792 | |
| 1793 | CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor( |
| 1794 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
| 1795 | auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst); |
| 1796 | Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts(); |
| 1797 | // This causes a replacement that will collapse the landing pad CFG based |
| 1798 | // on the filter function we intend to match. |
| 1799 | if (Selector == CurrentSelector) |
| 1800 | VMap[Inst] = ConstantInt::get(SelectorIDType, 1); |
| 1801 | else |
| 1802 | VMap[Inst] = ConstantInt::get(SelectorIDType, 0); |
| 1803 | // Tell the caller not to clone this instruction. |
| 1804 | return CloningDirector::SkipInstruction; |
| 1805 | } |
| 1806 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1807 | CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr( |
| 1808 | ValueToValueMapTy &VMap, |
| 1809 | const IndirectBrInst *IBr, |
| 1810 | BasicBlock *NewBB) { |
| 1811 | // If this indirect branch is not part of a landing pad block, just clone it. |
| 1812 | const BasicBlock *ParentBB = IBr->getParent(); |
| 1813 | if (!ParentBB->isLandingPad()) |
| 1814 | return CloningDirector::CloneInstruction; |
| 1815 | |
| 1816 | // If it is part of a landing pad, we want to filter out target blocks |
| 1817 | // that are not part of the handler we are outlining. |
| 1818 | const LandingPadInst *LPad = ParentBB->getLandingPadInst(); |
| 1819 | |
| 1820 | // Save this correlation for later processing. |
| 1821 | NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad; |
| 1822 | |
| 1823 | // We should only get here for landing pads that have already been outlined. |
| 1824 | assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>())); |
| 1825 | |
| 1826 | // Copy the indirectbr, but only include targets that were previously |
| 1827 | // identified as EH blocks and are dominated by the nested landing pad. |
| 1828 | SetVector<const BasicBlock *> ReturnTargets; |
| 1829 | for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) { |
| 1830 | auto *TargetBB = IBr->getDestination(I); |
| 1831 | if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) && |
| 1832 | DT->dominates(ParentBB, TargetBB)) { |
| 1833 | DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n"); |
| 1834 | ReturnTargets.insert(TargetBB); |
| 1835 | } |
| 1836 | } |
| 1837 | IndirectBrInst *NewBranch = |
| 1838 | IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()), |
| 1839 | ReturnTargets.size(), NewBB); |
| 1840 | for (auto *Target : ReturnTargets) |
| 1841 | NewBranch->addDestination(const_cast<BasicBlock*>(Target)); |
| 1842 | |
| 1843 | // The operands and targets of the branch instruction are remapped later |
| 1844 | // because it is a terminator. Tell the cloning code to clone the |
| 1845 | // blocks we just added to the target list. |
| 1846 | return CloningDirector::CloneSuccessors; |
| 1847 | } |
| 1848 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1849 | CloningDirector::CloningAction |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1850 | WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap, |
| 1851 | const InvokeInst *Invoke, BasicBlock *NewBB) { |
| 1852 | return CloningDirector::CloneInstruction; |
| 1853 | } |
| 1854 | |
| 1855 | CloningDirector::CloningAction |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1856 | WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap, |
| 1857 | const ResumeInst *Resume, BasicBlock *NewBB) { |
| 1858 | // Resume instructions shouldn't be reachable from catch handlers. |
| 1859 | // We still need to handle it, but it will be pruned. |
| 1860 | BasicBlock::InstListType &InstList = NewBB->getInstList(); |
| 1861 | InstList.push_back(new UnreachableInst(NewBB->getContext())); |
| 1862 | return CloningDirector::StopCloningBB; |
| 1863 | } |
| 1864 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1865 | CloningDirector::CloningAction |
| 1866 | WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap, |
| 1867 | const CmpInst *Compare, BasicBlock *NewBB) { |
| 1868 | const IntrinsicInst *IntrinCall = nullptr; |
| 1869 | if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) { |
| 1870 | IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0)); |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1871 | } else if (match(Compare->getOperand(1), |
| 1872 | m_Intrinsic<Intrinsic::eh_typeid_for>())) { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1873 | IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1)); |
| 1874 | } |
| 1875 | if (IntrinCall) { |
| 1876 | Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts(); |
| 1877 | // This causes a replacement that will collapse the landing pad CFG based |
| 1878 | // on the filter function we intend to match. |
| 1879 | if (Selector == CurrentSelector->stripPointerCasts()) { |
| 1880 | VMap[Compare] = ConstantInt::get(SelectorIDType, 1); |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1881 | } else { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1882 | VMap[Compare] = ConstantInt::get(SelectorIDType, 0); |
| 1883 | } |
| 1884 | return CloningDirector::SkipInstruction; |
| 1885 | } |
| 1886 | return CloningDirector::CloneInstruction; |
| 1887 | } |
| 1888 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1889 | CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad( |
| 1890 | ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) { |
| 1891 | // The MS runtime will terminate the process if an exception occurs in a |
| 1892 | // cleanup handler, so we shouldn't encounter landing pads in the actual |
| 1893 | // cleanup code, but they may appear in catch blocks. Depending on where |
| 1894 | // we started cloning we may see one, but it will get dropped during dead |
| 1895 | // block pruning. |
| 1896 | Instruction *NewInst = new UnreachableInst(NewBB->getContext()); |
| 1897 | VMap[LPad] = NewInst; |
| 1898 | BasicBlock::InstListType &InstList = NewBB->getInstList(); |
| 1899 | InstList.push_back(NewInst); |
| 1900 | return CloningDirector::StopCloningBB; |
| 1901 | } |
| 1902 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1903 | CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch( |
| 1904 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1905 | // Cleanup code may flow into catch blocks or the catch block may be part |
| 1906 | // of a branch that will be optimized away. We'll insert a return |
| 1907 | // instruction now, but it may be pruned before the cloning process is |
| 1908 | // complete. |
| 1909 | ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1910 | return CloningDirector::StopCloningBB; |
| 1911 | } |
| 1912 | |
| 1913 | CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch( |
| 1914 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1915 | // Cleanup handlers nested within catch handlers may begin with a call to |
| 1916 | // eh.endcatch. We can just ignore that instruction. |
| 1917 | return CloningDirector::SkipInstruction; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1918 | } |
| 1919 | |
| 1920 | CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor( |
| 1921 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1922 | // If we encounter a selector comparison while cloning a cleanup handler, |
| 1923 | // we want to stop cloning immediately. Anything after the dispatch |
| 1924 | // will be outlined into a different handler. |
| 1925 | BasicBlock *CatchHandler; |
| 1926 | Constant *Selector; |
| 1927 | BasicBlock *NextBB; |
| 1928 | if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()), |
| 1929 | CatchHandler, Selector, NextBB)) { |
| 1930 | ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); |
| 1931 | return CloningDirector::StopCloningBB; |
| 1932 | } |
| 1933 | // If eg.typeid.for is called for any other reason, it can be ignored. |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1934 | VMap[Inst] = ConstantInt::get(SelectorIDType, 0); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1935 | return CloningDirector::SkipInstruction; |
| 1936 | } |
| 1937 | |
Andrew Kaylor | a6c5b96 | 2015-05-20 23:22:24 +0000 | [diff] [blame] | 1938 | CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr( |
| 1939 | ValueToValueMapTy &VMap, |
| 1940 | const IndirectBrInst *IBr, |
| 1941 | BasicBlock *NewBB) { |
| 1942 | // No special handling is required for cleanup cloning. |
| 1943 | return CloningDirector::CloneInstruction; |
| 1944 | } |
| 1945 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1946 | CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke( |
| 1947 | ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) { |
| 1948 | // All invokes in cleanup handlers can be replaced with calls. |
| 1949 | SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3); |
| 1950 | // Insert a normal call instruction... |
| 1951 | CallInst *NewCall = |
| 1952 | CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs, |
| 1953 | Invoke->getName(), NewBB); |
| 1954 | NewCall->setCallingConv(Invoke->getCallingConv()); |
| 1955 | NewCall->setAttributes(Invoke->getAttributes()); |
| 1956 | NewCall->setDebugLoc(Invoke->getDebugLoc()); |
| 1957 | VMap[Invoke] = NewCall; |
| 1958 | |
Reid Kleckner | 6e48a82 | 2015-04-10 16:26:42 +0000 | [diff] [blame] | 1959 | // Remap the operands. |
| 1960 | llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer); |
| 1961 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1962 | // Insert an unconditional branch to the normal destination. |
| 1963 | BranchInst::Create(Invoke->getNormalDest(), NewBB); |
| 1964 | |
| 1965 | // The unwind destination won't be cloned into the new function, so |
| 1966 | // we don't need to clean up its phi nodes. |
| 1967 | |
| 1968 | // We just added a terminator to the cloned block. |
| 1969 | // Tell the caller to stop processing the current basic block. |
Reid Kleckner | 6e48a82 | 2015-04-10 16:26:42 +0000 | [diff] [blame] | 1970 | return CloningDirector::CloneSuccessors; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1971 | } |
| 1972 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1973 | CloningDirector::CloningAction WinEHCleanupDirector::handleResume( |
| 1974 | ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) { |
| 1975 | ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); |
| 1976 | |
| 1977 | // We just added a terminator to the cloned block. |
| 1978 | // Tell the caller to stop processing the current basic block so that |
| 1979 | // the branch instruction will be skipped. |
| 1980 | return CloningDirector::StopCloningBB; |
| 1981 | } |
| 1982 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1983 | CloningDirector::CloningAction |
| 1984 | WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap, |
| 1985 | const CmpInst *Compare, BasicBlock *NewBB) { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1986 | if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) || |
| 1987 | match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) { |
| 1988 | VMap[Compare] = ConstantInt::get(SelectorIDType, 1); |
| 1989 | return CloningDirector::SkipInstruction; |
| 1990 | } |
| 1991 | return CloningDirector::CloneInstruction; |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1992 | } |
| 1993 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1994 | WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer( |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1995 | Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo) |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1996 | : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1997 | BasicBlock *EntryBB = &OutlinedFn->getEntryBlock(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1998 | |
| 1999 | // New allocas should be inserted in the entry block, but after the parent FP |
| 2000 | // is established if it is an instruction. |
| 2001 | Instruction *InsertPoint = EntryBB->getFirstInsertionPt(); |
| 2002 | if (auto *FPInst = dyn_cast<Instruction>(ParentFP)) |
| 2003 | InsertPoint = FPInst->getNextNode(); |
| 2004 | Builder.SetInsertPoint(EntryBB, InsertPoint); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 2005 | } |
| 2006 | |
| 2007 | Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 2008 | // If we're asked to materialize a static alloca, we temporarily create an |
| 2009 | // alloca in the outlined function and add this to the FrameVarInfo map. When |
| 2010 | // all the outlining is complete, we'll replace these temporary allocas with |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 2011 | // calls to llvm.localrecover. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 2012 | if (auto *AV = dyn_cast<AllocaInst>(V)) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 2013 | assert(AV->isStaticAlloca() && |
| 2014 | "cannot materialize un-demoted dynamic alloca"); |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 2015 | AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone()); |
| 2016 | Builder.Insert(NewAlloca, AV->getName()); |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 2017 | FrameVarInfo[AV].push_back(NewAlloca); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 2018 | return NewAlloca; |
| 2019 | } |
| 2020 | |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 2021 | if (isa<Instruction>(V) || isa<Argument>(V)) { |
Reid Kleckner | d1b38c4 | 2015-05-06 18:45:24 +0000 | [diff] [blame] | 2022 | Function *Parent = isa<Instruction>(V) |
| 2023 | ? cast<Instruction>(V)->getParent()->getParent() |
| 2024 | : cast<Argument>(V)->getParent(); |
| 2025 | errs() |
| 2026 | << "Failed to demote instruction used in exception handler of function " |
| 2027 | << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n"; |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 2028 | errs() << " " << *V << '\n'; |
| 2029 | report_fatal_error("WinEHPrepare failed to demote instruction"); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 2030 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 2031 | |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 2032 | // Don't materialize other values. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 2033 | return nullptr; |
| 2034 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2035 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 2036 | void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) { |
| 2037 | // Catch parameter objects have to live in the parent frame. When we see a use |
| 2038 | // of a catch parameter, add a sentinel to the multimap to indicate that it's |
| 2039 | // used from another handler. This will prevent us from trying to sink the |
| 2040 | // alloca into the handler and ensure that the catch parameter is present in |
Reid Kleckner | 6038179 | 2015-07-07 22:25:32 +0000 | [diff] [blame] | 2041 | // the call to llvm.localescape. |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 2042 | FrameVarInfo[V].push_back(getCatchObjectSentinel()); |
| 2043 | } |
| 2044 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2045 | // This function maps the catch and cleanup handlers that are reachable from the |
| 2046 | // specified landing pad. The landing pad sequence will have this basic shape: |
| 2047 | // |
| 2048 | // <cleanup handler> |
| 2049 | // <selector comparison> |
| 2050 | // <catch handler> |
| 2051 | // <cleanup handler> |
| 2052 | // <selector comparison> |
| 2053 | // <catch handler> |
| 2054 | // <cleanup handler> |
| 2055 | // ... |
| 2056 | // |
| 2057 | // Any of the cleanup slots may be absent. The cleanup slots may be occupied by |
| 2058 | // any arbitrary control flow, but all paths through the cleanup code must |
| 2059 | // eventually reach the next selector comparison and no path can skip to a |
| 2060 | // different selector comparisons, though some paths may terminate abnormally. |
| 2061 | // Therefore, we will use a depth first search from the start of any given |
| 2062 | // cleanup block and stop searching when we find the next selector comparison. |
| 2063 | // |
| 2064 | // If the landingpad instruction does not have a catch clause, we will assume |
| 2065 | // that any instructions other than selector comparisons and catch handlers can |
| 2066 | // be ignored. In practice, these will only be the boilerplate instructions. |
| 2067 | // |
| 2068 | // The catch handlers may also have any control structure, but we are only |
| 2069 | // interested in the start of the catch handlers, so we don't need to actually |
| 2070 | // follow the flow of the catch handlers. The start of the catch handlers can |
| 2071 | // be located from the compare instructions, but they can be skipped in the |
| 2072 | // flow by following the contrary branch. |
| 2073 | void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad, |
| 2074 | LandingPadActions &Actions) { |
| 2075 | unsigned int NumClauses = LPad->getNumClauses(); |
| 2076 | unsigned int HandlersFound = 0; |
| 2077 | BasicBlock *BB = LPad->getParent(); |
| 2078 | |
| 2079 | DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n"); |
| 2080 | |
| 2081 | if (NumClauses == 0) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2082 | findCleanupHandlers(Actions, BB, nullptr); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2083 | return; |
| 2084 | } |
| 2085 | |
| 2086 | VisitedBlockSet VisitedBlocks; |
| 2087 | |
| 2088 | while (HandlersFound != NumClauses) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2089 | BasicBlock *NextBB = nullptr; |
| 2090 | |
Andrew Kaylor | 20ae2a3 | 2015-04-23 22:38:36 +0000 | [diff] [blame] | 2091 | // Skip over filter clauses. |
| 2092 | if (LPad->isFilter(HandlersFound)) { |
| 2093 | ++HandlersFound; |
| 2094 | continue; |
| 2095 | } |
| 2096 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2097 | // See if the clause we're looking for is a catch-all. |
| 2098 | // If so, the catch begins immediately. |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 2099 | Constant *ExpectedSelector = |
| 2100 | LPad->getClause(HandlersFound)->stripPointerCasts(); |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 2101 | if (isa<ConstantPointerNull>(ExpectedSelector)) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2102 | // The catch all must occur last. |
| 2103 | assert(HandlersFound == NumClauses - 1); |
| 2104 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 2105 | // There can be additional selector dispatches in the call chain that we |
| 2106 | // need to ignore. |
| 2107 | BasicBlock *CatchBlock = nullptr; |
| 2108 | Constant *Selector; |
| 2109 | while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) { |
| 2110 | DEBUG(dbgs() << " Found extra catch dispatch in block " |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 2111 | << CatchBlock->getName() << "\n"); |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 2112 | BB = NextBB; |
| 2113 | } |
| 2114 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2115 | // Add the catch handler to the action list. |
Andrew Kaylor | f18771b | 2015-04-20 18:48:45 +0000 | [diff] [blame] | 2116 | CatchHandler *Action = nullptr; |
| 2117 | if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) { |
| 2118 | // If the CatchHandlerMap already has an entry for this BB, re-use it. |
| 2119 | Action = CatchHandlerMap[BB]; |
| 2120 | assert(Action->getSelector() == ExpectedSelector); |
| 2121 | } else { |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 2122 | // We don't expect a selector dispatch, but there may be a call to |
| 2123 | // llvm.eh.begincatch, which separates catch handling code from |
| 2124 | // cleanup code in the same control flow. This call looks for the |
| 2125 | // begincatch intrinsic. |
| 2126 | Action = findCatchHandler(BB, NextBB, VisitedBlocks); |
| 2127 | if (Action) { |
| 2128 | // For C++ EH, check if there is any interesting cleanup code before |
| 2129 | // we begin the catch. This is important because cleanups cannot |
| 2130 | // rethrow exceptions but code called from catches can. For SEH, it |
| 2131 | // isn't important if some finally code before a catch-all is executed |
| 2132 | // out of line or after recovering from the exception. |
| 2133 | if (Personality == EHPersonality::MSVC_CXX) |
| 2134 | findCleanupHandlers(Actions, BB, BB); |
| 2135 | } else { |
| 2136 | // If an action was not found, it means that the control flows |
| 2137 | // directly into the catch-all handler and there is no cleanup code. |
| 2138 | // That's an expected situation and we must create a catch action. |
| 2139 | // Since this is a catch-all handler, the selector won't actually |
| 2140 | // appear in the code anywhere. ExpectedSelector here is the constant |
| 2141 | // null ptr that we got from the landing pad instruction. |
| 2142 | Action = new CatchHandler(BB, ExpectedSelector, nullptr); |
| 2143 | CatchHandlerMap[BB] = Action; |
| 2144 | } |
Andrew Kaylor | f18771b | 2015-04-20 18:48:45 +0000 | [diff] [blame] | 2145 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2146 | Actions.insertCatchHandler(Action); |
| 2147 | DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n"); |
| 2148 | ++HandlersFound; |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2149 | |
| 2150 | // Once we reach a catch-all, don't expect to hit a resume instruction. |
| 2151 | BB = nullptr; |
| 2152 | break; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2153 | } |
| 2154 | |
| 2155 | CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks); |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 2156 | assert(CatchAction); |
| 2157 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2158 | // See if there is any interesting code executed before the dispatch. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2159 | findCleanupHandlers(Actions, BB, CatchAction->getStartBlock()); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2160 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 2161 | // When the source program contains multiple nested try blocks the catch |
| 2162 | // handlers can get strung together in such a way that we can encounter |
| 2163 | // a dispatch for a selector that we've already had a handler for. |
| 2164 | if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) { |
| 2165 | ++HandlersFound; |
| 2166 | |
| 2167 | // Add the catch handler to the action list. |
| 2168 | DEBUG(dbgs() << " Found catch dispatch in block " |
| 2169 | << CatchAction->getStartBlock()->getName() << "\n"); |
| 2170 | Actions.insertCatchHandler(CatchAction); |
| 2171 | } else { |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 2172 | // Under some circumstances optimized IR will flow unconditionally into a |
| 2173 | // handler block without checking the selector. This can only happen if |
| 2174 | // the landing pad has a catch-all handler and the handler for the |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 2175 | // preceding catch clause is identical to the catch-call handler |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 2176 | // (typically an empty catch). In this case, the handler must be shared |
| 2177 | // by all remaining clauses. |
| 2178 | if (isa<ConstantPointerNull>( |
| 2179 | CatchAction->getSelector()->stripPointerCasts())) { |
| 2180 | DEBUG(dbgs() << " Applying early catch-all handler in block " |
| 2181 | << CatchAction->getStartBlock()->getName() |
| 2182 | << " to all remaining clauses.\n"); |
| 2183 | Actions.insertCatchHandler(CatchAction); |
| 2184 | return; |
| 2185 | } |
| 2186 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 2187 | DEBUG(dbgs() << " Found extra catch dispatch in block " |
| 2188 | << CatchAction->getStartBlock()->getName() << "\n"); |
| 2189 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2190 | |
| 2191 | // Move on to the block after the catch handler. |
| 2192 | BB = NextBB; |
| 2193 | } |
| 2194 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2195 | // If we didn't wind up in a catch-all, see if there is any interesting code |
| 2196 | // executed before the resume. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2197 | findCleanupHandlers(Actions, BB, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2198 | |
| 2199 | // It's possible that some optimization moved code into a landingpad that |
| 2200 | // wasn't |
| 2201 | // previously being used for cleanup. If that happens, we need to execute |
| 2202 | // that |
| 2203 | // extra code from a cleanup handler. |
| 2204 | if (Actions.includesCleanup() && !LPad->isCleanup()) |
| 2205 | LPad->setCleanup(true); |
| 2206 | } |
| 2207 | |
| 2208 | // This function searches starting with the input block for the next |
| 2209 | // block that terminates with a branch whose condition is based on a selector |
| 2210 | // comparison. This may be the input block. See the mapLandingPadBlocks |
| 2211 | // comments for a discussion of control flow assumptions. |
| 2212 | // |
| 2213 | CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB, |
| 2214 | BasicBlock *&NextBB, |
| 2215 | VisitedBlockSet &VisitedBlocks) { |
| 2216 | // See if we've already found a catch handler use it. |
| 2217 | // Call count() first to avoid creating a null entry for blocks |
| 2218 | // we haven't seen before. |
| 2219 | if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) { |
| 2220 | CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]); |
| 2221 | NextBB = Action->getNextBB(); |
| 2222 | return Action; |
| 2223 | } |
| 2224 | |
| 2225 | // VisitedBlocks applies only to the current search. We still |
| 2226 | // need to consider blocks that we've visited while mapping other |
| 2227 | // landing pads. |
| 2228 | VisitedBlocks.insert(BB); |
| 2229 | |
| 2230 | BasicBlock *CatchBlock = nullptr; |
| 2231 | Constant *Selector = nullptr; |
| 2232 | |
| 2233 | // If this is the first time we've visited this block from any landing pad |
| 2234 | // look to see if it is a selector dispatch block. |
| 2235 | if (!CatchHandlerMap.count(BB)) { |
| 2236 | if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) { |
| 2237 | CatchHandler *Action = new CatchHandler(BB, Selector, NextBB); |
| 2238 | CatchHandlerMap[BB] = Action; |
| 2239 | return Action; |
| 2240 | } |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 2241 | // If we encounter a block containing an llvm.eh.begincatch before we |
| 2242 | // find a selector dispatch block, the handler is assumed to be |
| 2243 | // reached unconditionally. This happens for catch-all blocks, but |
| 2244 | // it can also happen for other catch handlers that have been combined |
| 2245 | // with the catch-all handler during optimization. |
| 2246 | if (isCatchBlock(BB)) { |
| 2247 | PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext()); |
| 2248 | Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy); |
| 2249 | CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr); |
| 2250 | CatchHandlerMap[BB] = Action; |
| 2251 | return Action; |
| 2252 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2253 | } |
| 2254 | |
| 2255 | // Visit each successor, looking for the dispatch. |
| 2256 | // FIXME: We expect to find the dispatch quickly, so this will probably |
| 2257 | // work better as a breadth first search. |
| 2258 | for (BasicBlock *Succ : successors(BB)) { |
| 2259 | if (VisitedBlocks.count(Succ)) |
| 2260 | continue; |
| 2261 | |
| 2262 | CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks); |
| 2263 | if (Action) |
| 2264 | return Action; |
| 2265 | } |
| 2266 | return nullptr; |
| 2267 | } |
| 2268 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2269 | // These are helper functions to combine repeated code from findCleanupHandlers. |
| 2270 | static void createCleanupHandler(LandingPadActions &Actions, |
| 2271 | CleanupHandlerMapTy &CleanupHandlerMap, |
| 2272 | BasicBlock *BB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2273 | CleanupHandler *Action = new CleanupHandler(BB); |
| 2274 | CleanupHandlerMap[BB] = Action; |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2275 | Actions.insertCleanupHandler(Action); |
| 2276 | DEBUG(dbgs() << " Found cleanup code in block " |
| 2277 | << Action->getStartBlock()->getName() << "\n"); |
| 2278 | } |
| 2279 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2280 | static CallSite matchOutlinedFinallyCall(BasicBlock *BB, |
| 2281 | Instruction *MaybeCall) { |
| 2282 | // Look for finally blocks that Clang has already outlined for us. |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 2283 | // %fp = call i8* @llvm.localaddress() |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2284 | // call void @"fin$parent"(iN 1, i8* %fp) |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 2285 | if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator()) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2286 | MaybeCall = MaybeCall->getNextNode(); |
| 2287 | CallSite FinallyCall(MaybeCall); |
| 2288 | if (!FinallyCall || FinallyCall.arg_size() != 2) |
| 2289 | return CallSite(); |
| 2290 | if (!match(FinallyCall.getArgument(0), m_SpecificInt(1))) |
| 2291 | return CallSite(); |
Reid Kleckner | d5afc62f | 2015-07-07 23:23:03 +0000 | [diff] [blame] | 2292 | if (!isLocalAddressCall(FinallyCall.getArgument(1))) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2293 | return CallSite(); |
| 2294 | return FinallyCall; |
| 2295 | } |
| 2296 | |
| 2297 | static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) { |
| 2298 | // Skip single ubr blocks. |
| 2299 | while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) { |
| 2300 | auto *Br = dyn_cast<BranchInst>(BB->getTerminator()); |
| 2301 | if (Br && Br->isUnconditional()) |
| 2302 | BB = Br->getSuccessor(0); |
| 2303 | else |
| 2304 | return BB; |
| 2305 | } |
| 2306 | return BB; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2307 | } |
| 2308 | |
| 2309 | // This function searches starting with the input block for the next block that |
| 2310 | // contains code that is not part of a catch handler and would not be eliminated |
| 2311 | // during handler outlining. |
| 2312 | // |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2313 | void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions, |
| 2314 | BasicBlock *StartBB, BasicBlock *EndBB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2315 | // Here we will skip over the following: |
| 2316 | // |
| 2317 | // landing pad prolog: |
| 2318 | // |
| 2319 | // Unconditional branches |
| 2320 | // |
| 2321 | // Selector dispatch |
| 2322 | // |
| 2323 | // Resume pattern |
| 2324 | // |
| 2325 | // Anything else marks the start of an interesting block |
| 2326 | |
| 2327 | BasicBlock *BB = StartBB; |
| 2328 | // Anything other than an unconditional branch will kick us out of this loop |
| 2329 | // one way or another. |
| 2330 | while (BB) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2331 | BB = followSingleUnconditionalBranches(BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2332 | // If we've already scanned this block, don't scan it again. If it is |
| 2333 | // a cleanup block, there will be an action in the CleanupHandlerMap. |
| 2334 | // If we've scanned it and it is not a cleanup block, there will be a |
| 2335 | // nullptr in the CleanupHandlerMap. If we have not scanned it, there will |
| 2336 | // be no entry in the CleanupHandlerMap. We must call count() first to |
| 2337 | // avoid creating a null entry for blocks we haven't scanned. |
| 2338 | if (CleanupHandlerMap.count(BB)) { |
| 2339 | if (auto *Action = CleanupHandlerMap[BB]) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2340 | Actions.insertCleanupHandler(Action); |
| 2341 | DEBUG(dbgs() << " Found cleanup code in block " |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 2342 | << Action->getStartBlock()->getName() << "\n"); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2343 | // FIXME: This cleanup might chain into another, and we need to discover |
| 2344 | // that. |
| 2345 | return; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2346 | } else { |
| 2347 | // Here we handle the case where the cleanup handler map contains a |
| 2348 | // value for this block but the value is a nullptr. This means that |
| 2349 | // we have previously analyzed the block and determined that it did |
| 2350 | // not contain any cleanup code. Based on the earlier analysis, we |
Eric Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 2351 | // know the block must end in either an unconditional branch, a |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2352 | // resume or a conditional branch that is predicated on a comparison |
| 2353 | // with a selector. Either the resume or the selector dispatch |
| 2354 | // would terminate the search for cleanup code, so the unconditional |
| 2355 | // branch is the only case for which we might need to continue |
| 2356 | // searching. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2357 | BasicBlock *SuccBB = followSingleUnconditionalBranches(BB); |
| 2358 | if (SuccBB == BB || SuccBB == EndBB) |
| 2359 | return; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2360 | BB = SuccBB; |
| 2361 | continue; |
| 2362 | } |
| 2363 | } |
| 2364 | |
| 2365 | // Create an entry in the cleanup handler map for this block. Initially |
| 2366 | // we create an entry that says this isn't a cleanup block. If we find |
| 2367 | // cleanup code, the caller will replace this entry. |
| 2368 | CleanupHandlerMap[BB] = nullptr; |
| 2369 | |
| 2370 | TerminatorInst *Terminator = BB->getTerminator(); |
| 2371 | |
| 2372 | // Landing pad blocks have extra instructions we need to accept. |
| 2373 | LandingPadMap *LPadMap = nullptr; |
| 2374 | if (BB->isLandingPad()) { |
| 2375 | LandingPadInst *LPad = BB->getLandingPadInst(); |
| 2376 | LPadMap = &LPadMaps[LPad]; |
| 2377 | if (!LPadMap->isInitialized()) |
| 2378 | LPadMap->mapLandingPad(LPad); |
| 2379 | } |
| 2380 | |
| 2381 | // Look for the bare resume pattern: |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2382 | // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0 |
| 2383 | // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1 |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2384 | // resume { i8*, i32 } %lpad.val2 |
| 2385 | if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) { |
| 2386 | InsertValueInst *Insert1 = nullptr; |
| 2387 | InsertValueInst *Insert2 = nullptr; |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2388 | Value *ResumeVal = Resume->getOperand(0); |
Reid Kleckner | 1c130bb | 2015-04-16 17:02:23 +0000 | [diff] [blame] | 2389 | // If the resume value isn't a phi or landingpad value, it should be a |
| 2390 | // series of insertions. Identify them so we can avoid them when scanning |
| 2391 | // for cleanups. |
| 2392 | if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) { |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2393 | Insert2 = dyn_cast<InsertValueInst>(ResumeVal); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2394 | if (!Insert2) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2395 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2396 | Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand()); |
| 2397 | if (!Insert1) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2398 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2399 | } |
| 2400 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 2401 | II != IE; ++II) { |
| 2402 | Instruction *Inst = II; |
| 2403 | if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) |
| 2404 | continue; |
| 2405 | if (Inst == Insert1 || Inst == Insert2 || Inst == Resume) |
| 2406 | continue; |
| 2407 | if (!Inst->hasOneUse() || |
| 2408 | (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2409 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2410 | } |
| 2411 | } |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2412 | return; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2413 | } |
| 2414 | |
| 2415 | BranchInst *Branch = dyn_cast<BranchInst>(Terminator); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2416 | if (Branch && Branch->isConditional()) { |
| 2417 | // Look for the selector dispatch. |
| 2418 | // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*)) |
| 2419 | // %matches = icmp eq i32 %sel, %2 |
| 2420 | // br i1 %matches, label %catch14, label %eh.resume |
| 2421 | CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition()); |
| 2422 | if (!Compare || !Compare->isEquality()) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2423 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 2424 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 2425 | II != IE; ++II) { |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2426 | Instruction *Inst = II; |
| 2427 | if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) |
| 2428 | continue; |
| 2429 | if (Inst == Compare || Inst == Branch) |
| 2430 | continue; |
| 2431 | if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) |
| 2432 | continue; |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2433 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2434 | } |
| 2435 | // The selector dispatch block should always terminate our search. |
| 2436 | assert(BB == EndBB); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2437 | return; |
| 2438 | } |
| 2439 | |
| 2440 | if (isAsynchronousEHPersonality(Personality)) { |
| 2441 | // If this is a landingpad block, split the block at the first non-landing |
| 2442 | // pad instruction. |
| 2443 | Instruction *MaybeCall = BB->getFirstNonPHIOrDbg(); |
| 2444 | if (LPadMap) { |
| 2445 | while (MaybeCall != BB->getTerminator() && |
| 2446 | LPadMap->isLandingPadSpecificInst(MaybeCall)) |
| 2447 | MaybeCall = MaybeCall->getNextNode(); |
| 2448 | } |
| 2449 | |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 2450 | // Look for outlined finally calls on x64, since those happen to match the |
| 2451 | // prototype provided by the runtime. |
| 2452 | if (TheTriple.getArch() == Triple::x86_64) { |
| 2453 | if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) { |
| 2454 | Function *Fin = FinallyCall.getCalledFunction(); |
| 2455 | assert(Fin && "outlined finally call should be direct"); |
| 2456 | auto *Action = new CleanupHandler(BB); |
| 2457 | Action->setHandlerBlockOrFunc(Fin); |
| 2458 | Actions.insertCleanupHandler(Action); |
| 2459 | CleanupHandlerMap[BB] = Action; |
| 2460 | DEBUG(dbgs() << " Found frontend-outlined finally call to " |
| 2461 | << Fin->getName() << " in block " |
| 2462 | << Action->getStartBlock()->getName() << "\n"); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2463 | |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 2464 | // Split the block if there were more interesting instructions and |
| 2465 | // look for finally calls in the normal successor block. |
| 2466 | BasicBlock *SuccBB = BB; |
| 2467 | if (FinallyCall.getInstruction() != BB->getTerminator() && |
| 2468 | FinallyCall.getInstruction()->getNextNode() != |
| 2469 | BB->getTerminator()) { |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 2470 | SuccBB = |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 2471 | SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2472 | } else { |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 2473 | if (FinallyCall.isInvoke()) { |
| 2474 | SuccBB = cast<InvokeInst>(FinallyCall.getInstruction()) |
| 2475 | ->getNormalDest(); |
| 2476 | } else { |
| 2477 | SuccBB = BB->getUniqueSuccessor(); |
| 2478 | assert(SuccBB && |
| 2479 | "splitOutlinedFinallyCalls didn't insert a branch"); |
| 2480 | } |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2481 | } |
Reid Kleckner | 6511c8b | 2015-07-01 20:59:25 +0000 | [diff] [blame] | 2482 | BB = SuccBB; |
| 2483 | if (BB == EndBB) |
| 2484 | return; |
| 2485 | continue; |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2486 | } |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2487 | } |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2488 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2489 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2490 | // Anything else is either a catch block or interesting cleanup code. |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 2491 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 2492 | II != IE; ++II) { |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2493 | Instruction *Inst = II; |
| 2494 | if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) |
| 2495 | continue; |
| 2496 | // Unconditional branches fall through to this loop. |
| 2497 | if (Inst == Branch) |
| 2498 | continue; |
| 2499 | // If this is a catch block, there is no cleanup code to be found. |
| 2500 | if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2501 | return; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2502 | // If this a nested landing pad, it may contain an endcatch call. |
| 2503 | if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2504 | return; |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2505 | // Anything else makes this interesting cleanup code. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2506 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2507 | } |
| 2508 | |
| 2509 | // Only unconditional branches in empty blocks should get this far. |
| 2510 | assert(Branch && Branch->isUnconditional()); |
| 2511 | if (BB == EndBB) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2512 | return; |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2513 | BB = Branch->getSuccessor(0); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2514 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2515 | } |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2516 | |
| 2517 | // This is a public function, declared in WinEHFuncInfo.h and is also |
| 2518 | // referenced by WinEHNumbering in FunctionLoweringInfo.cpp. |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2519 | void llvm::parseEHActions( |
| 2520 | const IntrinsicInst *II, |
| 2521 | SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) { |
Reid Kleckner | f12c030 | 2015-06-09 21:42:19 +0000 | [diff] [blame] | 2522 | assert(II->getIntrinsicID() == Intrinsic::eh_actions && |
| 2523 | "attempted to parse non eh.actions intrinsic"); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2524 | for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) { |
| 2525 | uint64_t ActionKind = |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 2526 | cast<ConstantInt>(II->getArgOperand(I))->getZExtValue(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2527 | if (ActionKind == /*catch=*/1) { |
| 2528 | auto *Selector = cast<Constant>(II->getArgOperand(I + 1)); |
| 2529 | ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2)); |
| 2530 | int64_t EHObjIndexVal = EHObjIndex->getSExtValue(); |
| 2531 | Constant *Handler = cast<Constant>(II->getArgOperand(I + 3)); |
| 2532 | I += 4; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2533 | auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector, |
| 2534 | /*NextBB=*/nullptr); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2535 | CH->setHandlerBlockOrFunc(Handler); |
| 2536 | CH->setExceptionVarIndex(EHObjIndexVal); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2537 | Actions.push_back(std::move(CH)); |
David Majnemer | 69132a7 | 2015-04-03 22:49:05 +0000 | [diff] [blame] | 2538 | } else if (ActionKind == 0) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2539 | Constant *Handler = cast<Constant>(II->getArgOperand(I + 1)); |
| 2540 | I += 2; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2541 | auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2542 | CH->setHandlerBlockOrFunc(Handler); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2543 | Actions.push_back(std::move(CH)); |
David Majnemer | 69132a7 | 2015-04-03 22:49:05 +0000 | [diff] [blame] | 2544 | } else { |
| 2545 | llvm_unreachable("Expected either a catch or cleanup handler!"); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2546 | } |
| 2547 | } |
| 2548 | std::reverse(Actions.begin(), Actions.end()); |
| 2549 | } |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2550 | |
| 2551 | namespace { |
| 2552 | struct WinEHNumbering { |
| 2553 | WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), |
| 2554 | CurrentBaseState(-1), NextState(0) {} |
| 2555 | |
| 2556 | WinEHFuncInfo &FuncInfo; |
| 2557 | int CurrentBaseState; |
| 2558 | int NextState; |
| 2559 | |
| 2560 | SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack; |
| 2561 | SmallPtrSet<const Function *, 4> VisitedHandlers; |
| 2562 | |
| 2563 | int currentEHNumber() const { |
| 2564 | return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState(); |
| 2565 | } |
| 2566 | |
| 2567 | void createUnwindMapEntry(int ToState, ActionHandler *AH); |
| 2568 | void createTryBlockMapEntry(int TryLow, int TryHigh, |
| 2569 | ArrayRef<CatchHandler *> Handlers); |
| 2570 | void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions, |
| 2571 | ImmutableCallSite CS); |
| 2572 | void popUnmatchedActions(int FirstMismatch); |
| 2573 | void calculateStateNumbers(const Function &F); |
| 2574 | void findActionRootLPads(const Function &F); |
| 2575 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 2576 | } |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2577 | |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2578 | static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState, |
| 2579 | const Value *V) { |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2580 | WinEHUnwindMapEntry UME; |
| 2581 | UME.ToState = ToState; |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2582 | UME.Cleanup = V; |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2583 | FuncInfo.UnwindMap.push_back(UME); |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2584 | return FuncInfo.getLastStateNumber(); |
| 2585 | } |
| 2586 | |
| 2587 | static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow, |
| 2588 | int TryHigh, int CatchHigh, |
| 2589 | ArrayRef<const CatchPadInst *> Handlers) { |
| 2590 | WinEHTryBlockMapEntry TBME; |
| 2591 | TBME.TryLow = TryLow; |
| 2592 | TBME.TryHigh = TryHigh; |
| 2593 | TBME.CatchHigh = CatchHigh; |
| 2594 | assert(TBME.TryLow <= TBME.TryHigh); |
| 2595 | for (const CatchPadInst *CPI : Handlers) { |
| 2596 | WinEHHandlerType HT; |
| 2597 | Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0)); |
| 2598 | if (TypeInfo->isNullValue()) { |
| 2599 | HT.Adjectives = 0x40; |
| 2600 | HT.TypeDescriptor = nullptr; |
| 2601 | } else { |
| 2602 | auto *GV = cast<GlobalVariable>(TypeInfo->stripPointerCasts()); |
| 2603 | // Selectors are always pointers to GlobalVariables with 'struct' type. |
| 2604 | // The struct has two fields, adjectives and a type descriptor. |
| 2605 | auto *CS = cast<ConstantStruct>(GV->getInitializer()); |
| 2606 | HT.Adjectives = |
| 2607 | cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue(); |
| 2608 | HT.TypeDescriptor = |
| 2609 | cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts()); |
| 2610 | } |
Reid Kleckner | 0e28823 | 2015-08-27 23:27:47 +0000 | [diff] [blame] | 2611 | HT.Handler = CPI->getNormalDest(); |
| 2612 | HT.HandlerMBB = nullptr; |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2613 | // FIXME: Pass CPI->getArgOperand(1). |
| 2614 | HT.CatchObjRecoverIdx = -1; |
| 2615 | TBME.HandlerArray.push_back(HT); |
| 2616 | } |
| 2617 | FuncInfo.TryBlockMap.push_back(TBME); |
| 2618 | } |
| 2619 | |
| 2620 | void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) { |
| 2621 | Value *V = nullptr; |
| 2622 | if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH)) |
| 2623 | V = cast<Function>(CH->getHandlerBlockOrFunc()); |
| 2624 | addUnwindMapEntry(FuncInfo, ToState, V); |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2625 | } |
| 2626 | |
| 2627 | void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh, |
| 2628 | ArrayRef<CatchHandler *> Handlers) { |
| 2629 | // See if we already have an entry for this set of handlers. |
| 2630 | // This is using iterators rather than a range-based for loop because |
| 2631 | // if we find the entry we're looking for we'll need the iterator to erase it. |
| 2632 | int NumHandlers = Handlers.size(); |
| 2633 | auto I = FuncInfo.TryBlockMap.begin(); |
| 2634 | auto E = FuncInfo.TryBlockMap.end(); |
| 2635 | for ( ; I != E; ++I) { |
| 2636 | auto &Entry = *I; |
| 2637 | if (Entry.HandlerArray.size() != (size_t)NumHandlers) |
| 2638 | continue; |
| 2639 | int N; |
| 2640 | for (N = 0; N < NumHandlers; ++N) { |
| 2641 | if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc()) |
| 2642 | break; // breaks out of inner loop |
| 2643 | } |
| 2644 | // If all the handlers match, this is what we were looking for. |
| 2645 | if (N == NumHandlers) { |
| 2646 | break; |
| 2647 | } |
| 2648 | } |
| 2649 | |
| 2650 | // If we found an existing entry for this set of handlers, extend the range |
| 2651 | // but move the entry to the end of the map vector. The order of entries |
| 2652 | // in the map is critical to the way that the runtime finds handlers. |
| 2653 | // FIXME: Depending on what has happened with block ordering, this may |
| 2654 | // incorrectly combine entries that should remain separate. |
| 2655 | if (I != E) { |
| 2656 | // Copy the existing entry. |
| 2657 | WinEHTryBlockMapEntry Entry = *I; |
| 2658 | Entry.TryLow = std::min(TryLow, Entry.TryLow); |
| 2659 | Entry.TryHigh = std::max(TryHigh, Entry.TryHigh); |
| 2660 | assert(Entry.TryLow <= Entry.TryHigh); |
| 2661 | // Erase the old entry and add this one to the back. |
| 2662 | FuncInfo.TryBlockMap.erase(I); |
| 2663 | FuncInfo.TryBlockMap.push_back(Entry); |
| 2664 | return; |
| 2665 | } |
| 2666 | |
| 2667 | // If we didn't find an entry, create a new one. |
| 2668 | WinEHTryBlockMapEntry TBME; |
| 2669 | TBME.TryLow = TryLow; |
| 2670 | TBME.TryHigh = TryHigh; |
| 2671 | assert(TBME.TryLow <= TBME.TryHigh); |
| 2672 | for (CatchHandler *CH : Handlers) { |
| 2673 | WinEHHandlerType HT; |
| 2674 | if (CH->getSelector()->isNullValue()) { |
| 2675 | HT.Adjectives = 0x40; |
| 2676 | HT.TypeDescriptor = nullptr; |
| 2677 | } else { |
| 2678 | auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts()); |
| 2679 | // Selectors are always pointers to GlobalVariables with 'struct' type. |
| 2680 | // The struct has two fields, adjectives and a type descriptor. |
| 2681 | auto *CS = cast<ConstantStruct>(GV->getInitializer()); |
| 2682 | HT.Adjectives = |
| 2683 | cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue(); |
| 2684 | HT.TypeDescriptor = |
| 2685 | cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts()); |
| 2686 | } |
| 2687 | HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc()); |
Reid Kleckner | 0e28823 | 2015-08-27 23:27:47 +0000 | [diff] [blame] | 2688 | HT.HandlerMBB = nullptr; |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2689 | HT.CatchObjRecoverIdx = CH->getExceptionVarIndex(); |
| 2690 | TBME.HandlerArray.push_back(HT); |
| 2691 | } |
| 2692 | FuncInfo.TryBlockMap.push_back(TBME); |
| 2693 | } |
| 2694 | |
| 2695 | static void print_name(const Value *V) { |
| 2696 | #ifndef NDEBUG |
| 2697 | if (!V) { |
| 2698 | DEBUG(dbgs() << "null"); |
| 2699 | return; |
| 2700 | } |
| 2701 | |
| 2702 | if (const auto *F = dyn_cast<Function>(V)) |
| 2703 | DEBUG(dbgs() << F->getName()); |
| 2704 | else |
| 2705 | DEBUG(V->dump()); |
| 2706 | #endif |
| 2707 | } |
| 2708 | |
| 2709 | void WinEHNumbering::processCallSite( |
| 2710 | MutableArrayRef<std::unique_ptr<ActionHandler>> Actions, |
| 2711 | ImmutableCallSite CS) { |
| 2712 | DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber() |
| 2713 | << ") for: "); |
| 2714 | print_name(CS ? CS.getCalledValue() : nullptr); |
| 2715 | DEBUG(dbgs() << '\n'); |
| 2716 | |
| 2717 | DEBUG(dbgs() << "HandlerStack: \n"); |
| 2718 | for (int I = 0, E = HandlerStack.size(); I < E; ++I) { |
| 2719 | DEBUG(dbgs() << " "); |
| 2720 | print_name(HandlerStack[I]->getHandlerBlockOrFunc()); |
| 2721 | DEBUG(dbgs() << '\n'); |
| 2722 | } |
| 2723 | DEBUG(dbgs() << "Actions: \n"); |
| 2724 | for (int I = 0, E = Actions.size(); I < E; ++I) { |
| 2725 | DEBUG(dbgs() << " "); |
| 2726 | print_name(Actions[I]->getHandlerBlockOrFunc()); |
| 2727 | DEBUG(dbgs() << '\n'); |
| 2728 | } |
| 2729 | int FirstMismatch = 0; |
| 2730 | for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E; |
| 2731 | ++FirstMismatch) { |
| 2732 | if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() != |
| 2733 | Actions[FirstMismatch]->getHandlerBlockOrFunc()) |
| 2734 | break; |
| 2735 | } |
| 2736 | |
| 2737 | // Remove unmatched actions from the stack and process their EH states. |
| 2738 | popUnmatchedActions(FirstMismatch); |
| 2739 | |
| 2740 | DEBUG(dbgs() << "Pushing actions for CallSite: "); |
| 2741 | print_name(CS ? CS.getCalledValue() : nullptr); |
| 2742 | DEBUG(dbgs() << '\n'); |
| 2743 | |
| 2744 | bool LastActionWasCatch = false; |
| 2745 | const LandingPadInst *LastRootLPad = nullptr; |
| 2746 | for (size_t I = FirstMismatch; I != Actions.size(); ++I) { |
| 2747 | // We can reuse eh states when pushing two catches for the same invoke. |
| 2748 | bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get()); |
| 2749 | auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc()); |
| 2750 | // Various conditions can lead to a handler being popped from the |
| 2751 | // stack and re-pushed later. That shouldn't create a new state. |
| 2752 | // FIXME: Can code optimization lead to re-used handlers? |
| 2753 | if (FuncInfo.HandlerEnclosedState.count(Handler)) { |
| 2754 | // If we already assigned the state enclosed by this handler re-use it. |
| 2755 | Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]); |
| 2756 | continue; |
| 2757 | } |
| 2758 | const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler]; |
| 2759 | if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) { |
| 2760 | DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n"); |
| 2761 | Actions[I]->setEHState(currentEHNumber()); |
| 2762 | } else { |
| 2763 | DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", "); |
| 2764 | print_name(Actions[I]->getHandlerBlockOrFunc()); |
| 2765 | DEBUG(dbgs() << ") with EH state " << NextState << "\n"); |
| 2766 | createUnwindMapEntry(currentEHNumber(), Actions[I].get()); |
| 2767 | DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n"); |
| 2768 | Actions[I]->setEHState(NextState); |
| 2769 | NextState++; |
| 2770 | } |
| 2771 | HandlerStack.push_back(std::move(Actions[I])); |
| 2772 | LastActionWasCatch = CurrActionIsCatch; |
| 2773 | LastRootLPad = RootLPad; |
| 2774 | } |
| 2775 | |
| 2776 | // This is used to defer numbering states for a handler until after the |
| 2777 | // last time it appears in an invoke action list. |
| 2778 | if (CS.isInvoke()) { |
| 2779 | for (int I = 0, E = HandlerStack.size(); I < E; ++I) { |
| 2780 | auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc()); |
| 2781 | if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction())) |
| 2782 | continue; |
| 2783 | FuncInfo.LastInvokeVisited[Handler] = true; |
| 2784 | DEBUG(dbgs() << "Last invoke of "); |
| 2785 | print_name(Handler); |
| 2786 | DEBUG(dbgs() << " has been visited.\n"); |
| 2787 | } |
| 2788 | } |
| 2789 | |
| 2790 | DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: "); |
| 2791 | print_name(CS ? CS.getCalledValue() : nullptr); |
| 2792 | DEBUG(dbgs() << '\n'); |
| 2793 | } |
| 2794 | |
| 2795 | void WinEHNumbering::popUnmatchedActions(int FirstMismatch) { |
| 2796 | // Don't recurse while we are looping over the handler stack. Instead, defer |
| 2797 | // the numbering of the catch handlers until we are done popping. |
| 2798 | SmallVector<CatchHandler *, 4> PoppedCatches; |
| 2799 | for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) { |
| 2800 | std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val(); |
| 2801 | if (isa<CatchHandler>(Handler.get())) |
| 2802 | PoppedCatches.push_back(cast<CatchHandler>(Handler.release())); |
| 2803 | } |
| 2804 | |
| 2805 | int TryHigh = NextState - 1; |
| 2806 | int LastTryLowIdx = 0; |
| 2807 | for (int I = 0, E = PoppedCatches.size(); I != E; ++I) { |
| 2808 | CatchHandler *CH = PoppedCatches[I]; |
| 2809 | DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n"); |
| 2810 | if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) { |
| 2811 | int TryLow = CH->getEHState(); |
| 2812 | auto Handlers = |
| 2813 | makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1); |
| 2814 | DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh); |
| 2815 | for (size_t J = 0; J < Handlers.size(); ++J) { |
| 2816 | DEBUG(dbgs() << ", "); |
| 2817 | print_name(Handlers[J]->getHandlerBlockOrFunc()); |
| 2818 | } |
| 2819 | DEBUG(dbgs() << ")\n"); |
| 2820 | createTryBlockMapEntry(TryLow, TryHigh, Handlers); |
| 2821 | LastTryLowIdx = I + 1; |
| 2822 | } |
| 2823 | } |
| 2824 | |
| 2825 | for (CatchHandler *CH : PoppedCatches) { |
| 2826 | if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) { |
| 2827 | if (FuncInfo.LastInvokeVisited[F]) { |
| 2828 | DEBUG(dbgs() << "Assigning base state " << NextState << " to "); |
| 2829 | print_name(F); |
| 2830 | DEBUG(dbgs() << '\n'); |
| 2831 | FuncInfo.HandlerBaseState[F] = NextState; |
| 2832 | DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() |
| 2833 | << ", null)\n"); |
| 2834 | createUnwindMapEntry(currentEHNumber(), nullptr); |
| 2835 | ++NextState; |
| 2836 | calculateStateNumbers(*F); |
| 2837 | } |
| 2838 | else { |
| 2839 | DEBUG(dbgs() << "Deferring handling of "); |
| 2840 | print_name(F); |
| 2841 | DEBUG(dbgs() << " until last invoke visited.\n"); |
| 2842 | } |
| 2843 | } |
| 2844 | delete CH; |
| 2845 | } |
| 2846 | } |
| 2847 | |
| 2848 | void WinEHNumbering::calculateStateNumbers(const Function &F) { |
| 2849 | auto I = VisitedHandlers.insert(&F); |
| 2850 | if (!I.second) |
| 2851 | return; // We've already visited this handler, don't renumber it. |
| 2852 | |
| 2853 | int OldBaseState = CurrentBaseState; |
| 2854 | if (FuncInfo.HandlerBaseState.count(&F)) { |
| 2855 | CurrentBaseState = FuncInfo.HandlerBaseState[&F]; |
| 2856 | } |
| 2857 | |
| 2858 | size_t SavedHandlerStackSize = HandlerStack.size(); |
| 2859 | |
| 2860 | DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n'); |
| 2861 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
| 2862 | for (const BasicBlock &BB : F) { |
| 2863 | for (const Instruction &I : BB) { |
| 2864 | const auto *CI = dyn_cast<CallInst>(&I); |
| 2865 | if (!CI || CI->doesNotThrow()) |
| 2866 | continue; |
| 2867 | processCallSite(None, CI); |
| 2868 | } |
| 2869 | const auto *II = dyn_cast<InvokeInst>(BB.getTerminator()); |
| 2870 | if (!II) |
| 2871 | continue; |
| 2872 | const LandingPadInst *LPI = II->getLandingPadInst(); |
| 2873 | auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode()); |
| 2874 | if (!ActionsCall) |
| 2875 | continue; |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2876 | parseEHActions(ActionsCall, ActionList); |
| 2877 | if (ActionList.empty()) |
| 2878 | continue; |
| 2879 | processCallSite(ActionList, II); |
| 2880 | ActionList.clear(); |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2881 | FuncInfo.EHPadStateMap[LPI] = currentEHNumber(); |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 2882 | DEBUG(dbgs() << "Assigning state " << currentEHNumber() |
| 2883 | << " to landing pad at " << LPI->getParent()->getName() |
| 2884 | << '\n'); |
| 2885 | } |
| 2886 | |
| 2887 | // Pop any actions that were pushed on the stack for this function. |
| 2888 | popUnmatchedActions(SavedHandlerStackSize); |
| 2889 | |
| 2890 | DEBUG(dbgs() << "Assigning max state " << NextState - 1 |
| 2891 | << " to " << F.getName() << '\n'); |
| 2892 | FuncInfo.CatchHandlerMaxState[&F] = NextState - 1; |
| 2893 | |
| 2894 | CurrentBaseState = OldBaseState; |
| 2895 | } |
| 2896 | |
| 2897 | // This function follows the same basic traversal as calculateStateNumbers |
| 2898 | // but it is necessary to identify the root landing pad associated |
| 2899 | // with each action before we start assigning state numbers. |
| 2900 | void WinEHNumbering::findActionRootLPads(const Function &F) { |
| 2901 | auto I = VisitedHandlers.insert(&F); |
| 2902 | if (!I.second) |
| 2903 | return; // We've already visited this handler, don't revisit it. |
| 2904 | |
| 2905 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
| 2906 | for (const BasicBlock &BB : F) { |
| 2907 | const auto *II = dyn_cast<InvokeInst>(BB.getTerminator()); |
| 2908 | if (!II) |
| 2909 | continue; |
| 2910 | const LandingPadInst *LPI = II->getLandingPadInst(); |
| 2911 | auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode()); |
| 2912 | if (!ActionsCall) |
| 2913 | continue; |
| 2914 | |
| 2915 | assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions); |
| 2916 | parseEHActions(ActionsCall, ActionList); |
| 2917 | if (ActionList.empty()) |
| 2918 | continue; |
| 2919 | for (int I = 0, E = ActionList.size(); I < E; ++I) { |
| 2920 | if (auto *Handler |
| 2921 | = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) { |
| 2922 | FuncInfo.LastInvoke[Handler] = II; |
| 2923 | // Don't replace the root landing pad if we previously saw this |
| 2924 | // handler in a different function. |
| 2925 | if (FuncInfo.RootLPad.count(Handler) && |
| 2926 | FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F) |
| 2927 | continue; |
| 2928 | DEBUG(dbgs() << "Setting root lpad for "); |
| 2929 | print_name(Handler); |
| 2930 | DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n'); |
| 2931 | FuncInfo.RootLPad[Handler] = LPI; |
| 2932 | } |
| 2933 | } |
| 2934 | // Walk the actions again and look for nested handlers. This has to |
| 2935 | // happen after all of the actions have been processed in the current |
| 2936 | // function. |
| 2937 | for (int I = 0, E = ActionList.size(); I < E; ++I) |
| 2938 | if (auto *Handler |
| 2939 | = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) |
| 2940 | findActionRootLPads(*Handler); |
| 2941 | ActionList.clear(); |
| 2942 | } |
| 2943 | } |
| 2944 | |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2945 | static const BasicBlock *getSingleCatchPadPredecessor(const BasicBlock &BB) { |
| 2946 | for (const BasicBlock *PredBlock : predecessors(&BB)) |
| 2947 | if (isa<CatchPadInst>(PredBlock->getFirstNonPHI())) |
| 2948 | return PredBlock; |
| 2949 | return nullptr; |
| 2950 | } |
| 2951 | |
| 2952 | // Given BB which ends in an unwind edge, return the EHPad that this BB belongs |
| 2953 | // to. If the unwind edge came from an invoke, return null. |
| 2954 | static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) { |
| 2955 | const TerminatorInst *TI = BB->getTerminator(); |
| 2956 | if (isa<InvokeInst>(TI)) |
| 2957 | return nullptr; |
| 2958 | if (isa<CatchPadInst>(TI) || isa<CatchEndPadInst>(TI) || |
| 2959 | isa<TerminatePadInst>(TI)) |
| 2960 | return BB; |
Joseph Tremoulet | 8220bcc | 2015-08-23 00:26:33 +0000 | [diff] [blame] | 2961 | return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent(); |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 2962 | } |
| 2963 | |
| 2964 | static void calculateExplicitStateNumbers(WinEHFuncInfo &FuncInfo, |
| 2965 | const BasicBlock &BB, |
| 2966 | int ParentState) { |
| 2967 | assert(BB.isEHPad()); |
| 2968 | const Instruction *FirstNonPHI = BB.getFirstNonPHI(); |
| 2969 | // All catchpad instructions will be handled when we process their |
| 2970 | // respective catchendpad instruction. |
| 2971 | if (isa<CatchPadInst>(FirstNonPHI)) |
| 2972 | return; |
| 2973 | |
| 2974 | if (isa<CatchEndPadInst>(FirstNonPHI)) { |
| 2975 | const BasicBlock *TryPad = &BB; |
| 2976 | const BasicBlock *LastTryPad = nullptr; |
| 2977 | SmallVector<const CatchPadInst *, 2> Handlers; |
| 2978 | do { |
| 2979 | LastTryPad = TryPad; |
| 2980 | TryPad = getSingleCatchPadPredecessor(*TryPad); |
| 2981 | if (TryPad) |
| 2982 | Handlers.push_back(cast<CatchPadInst>(TryPad->getFirstNonPHI())); |
| 2983 | } while (TryPad); |
| 2984 | // We've pushed these back into reverse source order. Reverse them to get |
| 2985 | // the list back into source order. |
| 2986 | std::reverse(Handlers.begin(), Handlers.end()); |
| 2987 | int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr); |
| 2988 | FuncInfo.EHPadStateMap[Handlers.front()] = TryLow; |
| 2989 | for (const BasicBlock *PredBlock : predecessors(LastTryPad)) |
| 2990 | if ((PredBlock = getEHPadFromPredecessor(PredBlock))) |
| 2991 | calculateExplicitStateNumbers(FuncInfo, *PredBlock, TryLow); |
| 2992 | int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr); |
| 2993 | FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow; |
| 2994 | int TryHigh = CatchLow - 1; |
| 2995 | for (const BasicBlock *PredBlock : predecessors(&BB)) |
| 2996 | if ((PredBlock = getEHPadFromPredecessor(PredBlock))) |
| 2997 | calculateExplicitStateNumbers(FuncInfo, *PredBlock, CatchLow); |
| 2998 | int CatchHigh = FuncInfo.getLastStateNumber(); |
| 2999 | addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers); |
| 3000 | DEBUG(dbgs() << "TryLow[" << LastTryPad->getName() << "]: " << TryLow |
| 3001 | << '\n'); |
| 3002 | DEBUG(dbgs() << "TryHigh[" << LastTryPad->getName() << "]: " << TryHigh |
| 3003 | << '\n'); |
| 3004 | DEBUG(dbgs() << "CatchHigh[" << LastTryPad->getName() << "]: " << CatchHigh |
| 3005 | << '\n'); |
| 3006 | } else if (isa<CleanupPadInst>(FirstNonPHI)) { |
| 3007 | int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB); |
| 3008 | FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState; |
| 3009 | DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB " |
| 3010 | << BB.getName() << '\n'); |
| 3011 | for (const BasicBlock *PredBlock : predecessors(&BB)) |
| 3012 | if ((PredBlock = getEHPadFromPredecessor(PredBlock))) |
| 3013 | calculateExplicitStateNumbers(FuncInfo, *PredBlock, CleanupState); |
| 3014 | } else if (isa<TerminatePadInst>(FirstNonPHI)) { |
| 3015 | report_fatal_error("Not yet implemented!"); |
| 3016 | } else { |
| 3017 | llvm_unreachable("unexpected EH Pad!"); |
| 3018 | } |
| 3019 | } |
| 3020 | |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 3021 | void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn, |
| 3022 | WinEHFuncInfo &FuncInfo) { |
| 3023 | // Return if it's already been done. |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 3024 | if (!FuncInfo.EHPadStateMap.empty()) |
| 3025 | return; |
| 3026 | |
| 3027 | bool IsExplicit = false; |
| 3028 | for (const BasicBlock &BB : *ParentFn) { |
| 3029 | if (!BB.isEHPad()) |
| 3030 | continue; |
| 3031 | // Check if the EH Pad has no exceptional successors (i.e. it unwinds to |
| 3032 | // caller). Cleanups are a little bit of a special case because their |
| 3033 | // control flow cannot be determined by looking at the pad but instead by |
| 3034 | // the pad's users. |
| 3035 | bool HasNoSuccessors = false; |
| 3036 | const Instruction *FirstNonPHI = BB.getFirstNonPHI(); |
| 3037 | if (FirstNonPHI->mayThrow()) { |
| 3038 | HasNoSuccessors = true; |
| 3039 | } else if (auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI)) { |
| 3040 | HasNoSuccessors = |
| 3041 | CPI->use_empty() || |
| 3042 | cast<CleanupReturnInst>(CPI->user_back())->unwindsToCaller(); |
| 3043 | } |
| 3044 | |
| 3045 | if (!HasNoSuccessors) |
| 3046 | continue; |
| 3047 | calculateExplicitStateNumbers(FuncInfo, BB, -1); |
| 3048 | IsExplicit = true; |
| 3049 | } |
| 3050 | |
| 3051 | if (IsExplicit) |
Reid Kleckner | fe4d491 | 2015-05-28 22:00:24 +0000 | [diff] [blame] | 3052 | return; |
| 3053 | |
| 3054 | WinEHNumbering Num(FuncInfo); |
| 3055 | Num.findActionRootLPads(*ParentFn); |
| 3056 | // The VisitedHandlers list is used by both findActionRootLPads and |
| 3057 | // calculateStateNumbers, but both functions need to visit all handlers. |
| 3058 | Num.VisitedHandlers.clear(); |
| 3059 | Num.calculateStateNumbers(*ParentFn); |
| 3060 | // Pop everything on the handler stack. |
| 3061 | // It may be necessary to call this more than once because a handler can |
| 3062 | // be pushed on the stack as a result of clearing the stack. |
| 3063 | while (!Num.HandlerStack.empty()) |
| 3064 | Num.processCallSite(None, ImmutableCallSite()); |
| 3065 | } |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3066 | |
| 3067 | void WinEHPrepare::numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB) { |
| 3068 | Instruction *FirstNonPHI = FuncletBB->getFirstNonPHI(); |
| 3069 | bool IsCatch = isa<CatchPadInst>(FirstNonPHI); |
| 3070 | bool IsCleanup = isa<CleanupPadInst>(FirstNonPHI); |
| 3071 | |
| 3072 | // Initialize the worklist with the funclet's entry point. |
| 3073 | std::vector<BasicBlock *> Worklist; |
| 3074 | Worklist.push_back(InitialBB); |
| 3075 | |
| 3076 | while (!Worklist.empty()) { |
| 3077 | BasicBlock *BB = Worklist.back(); |
| 3078 | Worklist.pop_back(); |
| 3079 | |
| 3080 | // There can be only one "pad" basic block in the funclet: the initial one. |
| 3081 | if (BB != FuncletBB && BB->isEHPad()) |
| 3082 | continue; |
| 3083 | |
| 3084 | // Add 'FuncletBB' as a possible color for 'BB'. |
| 3085 | if (BlockColors[BB].insert(FuncletBB).second == false) { |
| 3086 | // Skip basic blocks which we have already visited. |
| 3087 | continue; |
| 3088 | } |
| 3089 | |
| 3090 | FuncletBlocks[FuncletBB].insert(BB); |
| 3091 | |
| 3092 | Instruction *Terminator = BB->getTerminator(); |
| 3093 | // The catchret's successors cannot be part of the funclet. |
| 3094 | if (IsCatch && isa<CatchReturnInst>(Terminator)) |
| 3095 | continue; |
| 3096 | // The cleanupret's successors cannot be part of the funclet. |
| 3097 | if (IsCleanup && isa<CleanupReturnInst>(Terminator)) |
| 3098 | continue; |
| 3099 | |
| 3100 | Worklist.insert(Worklist.end(), succ_begin(BB), succ_end(BB)); |
| 3101 | } |
| 3102 | } |
| 3103 | |
| 3104 | bool WinEHPrepare::prepareExplicitEH(Function &F) { |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3105 | // Remove unreachable blocks. It is not valuable to assign them a color and |
| 3106 | // their existence can trick us into thinking values are alive when they are |
| 3107 | // not. |
| 3108 | removeUnreachableBlocks(F); |
| 3109 | |
| 3110 | BasicBlock *EntryBlock = &F.getEntryBlock(); |
| 3111 | |
| 3112 | // Number everything starting from the entry block. |
| 3113 | numberFunclet(EntryBlock, EntryBlock); |
| 3114 | |
| 3115 | for (BasicBlock &BB : F) { |
| 3116 | // Remove single entry PHIs to simplify preparation. |
| 3117 | if (auto *PN = dyn_cast<PHINode>(BB.begin())) |
| 3118 | if (PN->getNumIncomingValues() == 1) |
| 3119 | FoldSingleEntryPHINodes(&BB); |
| 3120 | |
| 3121 | // EH pad instructions are always the first non-PHI nodes in a block if they |
| 3122 | // are at all present. |
| 3123 | Instruction *I = BB.getFirstNonPHI(); |
| 3124 | if (I->isEHPad()) |
| 3125 | numberFunclet(&BB, &BB); |
| 3126 | |
| 3127 | // It is possible for a normal basic block to only be reachable via an |
| 3128 | // exceptional basic block. The successor of a catchret is the only case |
| 3129 | // where this is possible. |
| 3130 | if (auto *CRI = dyn_cast<CatchReturnInst>(BB.getTerminator())) |
| 3131 | numberFunclet(CRI->getSuccessor(), EntryBlock); |
| 3132 | } |
| 3133 | |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3134 | // Strip PHI nodes off of EH pads. |
| 3135 | SmallVector<PHINode *, 16> PHINodes; |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3136 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { |
| 3137 | BasicBlock *BB = FI++; |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3138 | if (!BB->isEHPad()) |
| 3139 | continue; |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3140 | for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { |
| 3141 | Instruction *I = BI++; |
| 3142 | auto *PN = dyn_cast<PHINode>(I); |
| 3143 | // Stop at the first non-PHI. |
| 3144 | if (!PN) |
| 3145 | break; |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3146 | |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3147 | AllocaInst *SpillSlot = insertPHILoads(PN, F); |
| 3148 | if (SpillSlot) |
| 3149 | insertPHIStores(PN, SpillSlot); |
| 3150 | |
| 3151 | PHINodes.push_back(PN); |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3152 | } |
| 3153 | } |
| 3154 | |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3155 | for (auto *PN : PHINodes) { |
| 3156 | // There may be lingering uses on other EH PHIs being removed |
| 3157 | PN->replaceAllUsesWith(UndefValue::get(PN->getType())); |
| 3158 | PN->eraseFromParent(); |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3159 | } |
| 3160 | |
| 3161 | // Turn all inter-funclet uses of a Value into loads and stores. |
| 3162 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { |
| 3163 | BasicBlock *BB = FI++; |
| 3164 | std::set<BasicBlock *> &ColorsForBB = BlockColors[BB]; |
| 3165 | for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { |
| 3166 | Instruction *I = BI++; |
| 3167 | // Funclets are permitted to use static allocas. |
| 3168 | if (auto *AI = dyn_cast<AllocaInst>(I)) |
| 3169 | if (AI->isStaticAlloca()) |
| 3170 | continue; |
| 3171 | |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3172 | demoteNonlocalUses(I, ColorsForBB, F); |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3173 | } |
| 3174 | } |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3175 | // Also demote function parameters used in funclets. |
| 3176 | std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()]; |
| 3177 | for (Argument &Arg : F.args()) |
| 3178 | demoteNonlocalUses(&Arg, ColorsForEntry, F); |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3179 | |
| 3180 | // We need to clone all blocks which belong to multiple funclets. Values are |
| 3181 | // remapped throughout the funclet to propogate both the new instructions |
| 3182 | // *and* the new basic blocks themselves. |
| 3183 | for (auto &Funclet : FuncletBlocks) { |
| 3184 | BasicBlock *FuncletPadBB = Funclet.first; |
| 3185 | std::set<BasicBlock *> &BlocksInFunclet = Funclet.second; |
| 3186 | |
| 3187 | std::map<BasicBlock *, BasicBlock *> Orig2Clone; |
| 3188 | ValueToValueMapTy VMap; |
| 3189 | for (BasicBlock *BB : BlocksInFunclet) { |
| 3190 | std::set<BasicBlock *> &ColorsForBB = BlockColors[BB]; |
| 3191 | // We don't need to do anything if the block is monochromatic. |
| 3192 | size_t NumColorsForBB = ColorsForBB.size(); |
| 3193 | if (NumColorsForBB == 1) |
| 3194 | continue; |
| 3195 | |
| 3196 | assert(!isa<PHINode>(BB->front()) && |
| 3197 | "Polychromatic PHI nodes should have been demoted!"); |
| 3198 | |
| 3199 | // Create a new basic block and copy instructions into it! |
| 3200 | BasicBlock *CBB = CloneBasicBlock( |
| 3201 | BB, VMap, Twine(".for.", FuncletPadBB->getName()), &F); |
| 3202 | |
| 3203 | // Add basic block mapping. |
| 3204 | VMap[BB] = CBB; |
| 3205 | |
| 3206 | // Record delta operations that we need to perform to our color mappings. |
| 3207 | Orig2Clone[BB] = CBB; |
| 3208 | } |
| 3209 | |
| 3210 | // Update our color mappings to reflect that one block has lost a color and |
| 3211 | // another has gained a color. |
| 3212 | for (auto &BBMapping : Orig2Clone) { |
| 3213 | BasicBlock *OldBlock = BBMapping.first; |
| 3214 | BasicBlock *NewBlock = BBMapping.second; |
| 3215 | |
| 3216 | BlocksInFunclet.insert(NewBlock); |
| 3217 | BlockColors[NewBlock].insert(FuncletPadBB); |
| 3218 | |
| 3219 | BlocksInFunclet.erase(OldBlock); |
| 3220 | BlockColors[OldBlock].erase(FuncletPadBB); |
| 3221 | } |
| 3222 | |
| 3223 | // Loop over all of the instructions in the function, fixing up operand |
| 3224 | // references as we go. This uses VMap to do all the hard work. |
| 3225 | for (BasicBlock *BB : BlocksInFunclet) |
| 3226 | // Loop over all instructions, fixing each one as we find it... |
| 3227 | for (Instruction &I : *BB) |
| 3228 | RemapInstruction(&I, VMap, RF_IgnoreMissingEntries); |
| 3229 | } |
| 3230 | |
David Majnemer | 83f4bb2 | 2015-08-17 20:56:39 +0000 | [diff] [blame] | 3231 | // Remove implausible terminators and replace them with UnreachableInst. |
| 3232 | for (auto &Funclet : FuncletBlocks) { |
| 3233 | BasicBlock *FuncletPadBB = Funclet.first; |
| 3234 | std::set<BasicBlock *> &BlocksInFunclet = Funclet.second; |
| 3235 | Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI(); |
| 3236 | auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI); |
| 3237 | auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI); |
| 3238 | |
| 3239 | for (BasicBlock *BB : BlocksInFunclet) { |
| 3240 | TerminatorInst *TI = BB->getTerminator(); |
| 3241 | // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst. |
| 3242 | bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad); |
| 3243 | // The token consumed by a CatchReturnInst must match the funclet token. |
| 3244 | bool IsUnreachableCatchret = false; |
| 3245 | if (auto *CRI = dyn_cast<CatchReturnInst>(TI)) |
Joseph Tremoulet | 8220bcc | 2015-08-23 00:26:33 +0000 | [diff] [blame] | 3246 | IsUnreachableCatchret = CRI->getCatchPad() != CatchPad; |
David Majnemer | 83f4bb2 | 2015-08-17 20:56:39 +0000 | [diff] [blame] | 3247 | // The token consumed by a CleanupPadInst must match the funclet token. |
| 3248 | bool IsUnreachableCleanupret = false; |
| 3249 | if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) |
Joseph Tremoulet | 8220bcc | 2015-08-23 00:26:33 +0000 | [diff] [blame] | 3250 | IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad; |
David Majnemer | 83f4bb2 | 2015-08-17 20:56:39 +0000 | [diff] [blame] | 3251 | if (IsUnreachableRet || IsUnreachableCatchret || IsUnreachableCleanupret) { |
| 3252 | new UnreachableInst(BB->getContext(), TI); |
| 3253 | TI->eraseFromParent(); |
| 3254 | } |
| 3255 | } |
| 3256 | } |
| 3257 | |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3258 | // Clean-up some of the mess we made by removing useles PHI nodes, trivial |
| 3259 | // branches, etc. |
| 3260 | for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { |
| 3261 | BasicBlock *BB = FI++; |
| 3262 | SimplifyInstructionsInBlock(BB); |
| 3263 | ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true); |
| 3264 | MergeBlockIntoPredecessor(BB); |
| 3265 | } |
| 3266 | |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3267 | // We might have some unreachable blocks after cleaning up some impossible |
| 3268 | // control flow. |
| 3269 | removeUnreachableBlocks(F); |
| 3270 | |
| 3271 | // Recolor the CFG to verify that all is well. |
| 3272 | for (BasicBlock &BB : F) { |
| 3273 | size_t NumColors = BlockColors[&BB].size(); |
| 3274 | assert(NumColors == 1 && "Expected monochromatic BB!"); |
| 3275 | if (NumColors == 0) |
| 3276 | report_fatal_error("Uncolored BB!"); |
| 3277 | if (NumColors > 1) |
| 3278 | report_fatal_error("Multicolor BB!"); |
| 3279 | bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin()); |
| 3280 | assert(!EHPadHasPHI && "EH Pad still has a PHI!"); |
| 3281 | if (EHPadHasPHI) |
| 3282 | report_fatal_error("EH Pad still has a PHI!"); |
| 3283 | } |
| 3284 | |
| 3285 | BlockColors.clear(); |
| 3286 | FuncletBlocks.clear(); |
David Majnemer | 0ad363e | 2015-08-18 19:07:12 +0000 | [diff] [blame] | 3287 | |
David Majnemer | fd9f477 | 2015-08-11 01:15:26 +0000 | [diff] [blame] | 3288 | return true; |
| 3289 | } |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3290 | |
| 3291 | // TODO: Share loads when one use dominates another, or when a catchpad exit |
| 3292 | // dominates uses (needs dominators). |
| 3293 | AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) { |
| 3294 | BasicBlock *PHIBlock = PN->getParent(); |
| 3295 | AllocaInst *SpillSlot = nullptr; |
| 3296 | |
| 3297 | if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) { |
| 3298 | // Insert a load in place of the PHI and replace all uses. |
| 3299 | SpillSlot = new AllocaInst(PN->getType(), nullptr, |
| 3300 | Twine(PN->getName(), ".wineh.spillslot"), |
| 3301 | F.getEntryBlock().begin()); |
| 3302 | Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"), |
| 3303 | PHIBlock->getFirstInsertionPt()); |
| 3304 | PN->replaceAllUsesWith(V); |
| 3305 | return SpillSlot; |
| 3306 | } |
| 3307 | |
| 3308 | DenseMap<BasicBlock *, Value *> Loads; |
| 3309 | for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end(); |
| 3310 | UI != UE;) { |
| 3311 | Use &U = *UI++; |
| 3312 | auto *UsingInst = cast<Instruction>(U.getUser()); |
| 3313 | BasicBlock *UsingBB = UsingInst->getParent(); |
| 3314 | if (UsingBB->isEHPad()) { |
| 3315 | // Use is on an EH pad phi. Leave it alone; we'll insert loads and |
| 3316 | // stores for it separately. |
| 3317 | assert(isa<PHINode>(UsingInst)); |
| 3318 | continue; |
| 3319 | } |
| 3320 | replaceUseWithLoad(PN, U, SpillSlot, Loads, F); |
| 3321 | } |
| 3322 | return SpillSlot; |
| 3323 | } |
| 3324 | |
| 3325 | // TODO: improve store placement. Inserting at def is probably good, but need |
| 3326 | // to be careful not to introduce interfering stores (needs liveness analysis). |
| 3327 | // TODO: identify related phi nodes that can share spill slots, and share them |
| 3328 | // (also needs liveness). |
| 3329 | void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI, |
| 3330 | AllocaInst *SpillSlot) { |
| 3331 | // Use a worklist of (Block, Value) pairs -- the given Value needs to be |
| 3332 | // stored to the spill slot by the end of the given Block. |
| 3333 | SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist; |
| 3334 | |
| 3335 | Worklist.push_back({OriginalPHI->getParent(), OriginalPHI}); |
| 3336 | |
| 3337 | while (!Worklist.empty()) { |
| 3338 | BasicBlock *EHBlock; |
| 3339 | Value *InVal; |
| 3340 | std::tie(EHBlock, InVal) = Worklist.pop_back_val(); |
| 3341 | |
| 3342 | PHINode *PN = dyn_cast<PHINode>(InVal); |
| 3343 | if (PN && PN->getParent() == EHBlock) { |
| 3344 | // The value is defined by another PHI we need to remove, with no room to |
| 3345 | // insert a store after the PHI, so each predecessor needs to store its |
| 3346 | // incoming value. |
| 3347 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) { |
| 3348 | Value *PredVal = PN->getIncomingValue(i); |
| 3349 | |
| 3350 | // Undef can safely be skipped. |
| 3351 | if (isa<UndefValue>(PredVal)) |
| 3352 | continue; |
| 3353 | |
| 3354 | insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist); |
| 3355 | } |
| 3356 | } else { |
| 3357 | // We need to store InVal, which dominates EHBlock, but can't put a store |
| 3358 | // in EHBlock, so need to put stores in each predecessor. |
| 3359 | for (BasicBlock *PredBlock : predecessors(EHBlock)) { |
| 3360 | insertPHIStore(PredBlock, InVal, SpillSlot, Worklist); |
| 3361 | } |
| 3362 | } |
| 3363 | } |
| 3364 | } |
| 3365 | |
| 3366 | void WinEHPrepare::insertPHIStore( |
| 3367 | BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot, |
| 3368 | SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) { |
| 3369 | |
| 3370 | if (PredBlock->isEHPad() && |
| 3371 | !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) { |
| 3372 | // Pred is unsplittable, so we need to queue it on the worklist. |
| 3373 | Worklist.push_back({PredBlock, PredVal}); |
| 3374 | return; |
| 3375 | } |
| 3376 | |
| 3377 | // Otherwise, insert the store at the end of the basic block. |
| 3378 | new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator()); |
| 3379 | } |
| 3380 | |
| 3381 | // TODO: Share loads for same-funclet uses (requires dominators if funclets |
| 3382 | // aren't properly nested). |
| 3383 | void WinEHPrepare::demoteNonlocalUses(Value *V, |
| 3384 | std::set<BasicBlock *> &ColorsForBB, |
| 3385 | Function &F) { |
David Majnemer | 83f4bb2 | 2015-08-17 20:56:39 +0000 | [diff] [blame] | 3386 | // Tokens can only be used non-locally due to control flow involving |
| 3387 | // unreachable edges. Don't try to demote the token usage, we'll simply |
| 3388 | // delete the cloned user later. |
| 3389 | if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V)) |
| 3390 | return; |
| 3391 | |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3392 | DenseMap<BasicBlock *, Value *> Loads; |
| 3393 | AllocaInst *SpillSlot = nullptr; |
| 3394 | for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) { |
| 3395 | Use &U = *UI++; |
| 3396 | auto *UsingInst = cast<Instruction>(U.getUser()); |
| 3397 | BasicBlock *UsingBB = UsingInst->getParent(); |
| 3398 | |
| 3399 | // Is the Use inside a block which is colored with a subset of the Def? |
| 3400 | // If so, we don't need to escape the Def because we will clone |
| 3401 | // ourselves our own private copy. |
| 3402 | std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB]; |
| 3403 | if (std::includes(ColorsForBB.begin(), ColorsForBB.end(), |
| 3404 | ColorsForUsingBB.begin(), ColorsForUsingBB.end())) |
| 3405 | continue; |
| 3406 | |
| 3407 | replaceUseWithLoad(V, U, SpillSlot, Loads, F); |
| 3408 | } |
| 3409 | if (SpillSlot) { |
| 3410 | // Insert stores of the computed value into the stack slot. |
| 3411 | // We have to be careful if I is an invoke instruction, |
| 3412 | // because we can't insert the store AFTER the terminator instruction. |
| 3413 | BasicBlock::iterator InsertPt; |
| 3414 | if (isa<Argument>(V)) { |
| 3415 | InsertPt = F.getEntryBlock().getTerminator(); |
| 3416 | } else if (isa<TerminatorInst>(V)) { |
| 3417 | auto *II = cast<InvokeInst>(V); |
| 3418 | // We cannot demote invoke instructions to the stack if their normal |
| 3419 | // edge is critical. Therefore, split the critical edge and create a |
| 3420 | // basic block into which the store can be inserted. |
| 3421 | if (!II->getNormalDest()->getSinglePredecessor()) { |
| 3422 | unsigned SuccNum = |
| 3423 | GetSuccessorNumber(II->getParent(), II->getNormalDest()); |
| 3424 | assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!"); |
| 3425 | BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum); |
| 3426 | assert(NewBlock && "Unable to split critical edge."); |
| 3427 | // Update the color mapping for the newly split edge. |
| 3428 | std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()]; |
| 3429 | BlockColors[NewBlock] = ColorsForUsingBB; |
| 3430 | for (BasicBlock *FuncletPad : ColorsForUsingBB) |
| 3431 | FuncletBlocks[FuncletPad].insert(NewBlock); |
| 3432 | } |
| 3433 | InsertPt = II->getNormalDest()->getFirstInsertionPt(); |
| 3434 | } else { |
| 3435 | InsertPt = cast<Instruction>(V); |
| 3436 | ++InsertPt; |
| 3437 | // Don't insert before PHI nodes or EH pad instrs. |
| 3438 | for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt) |
| 3439 | ; |
| 3440 | } |
| 3441 | new StoreInst(V, SpillSlot, InsertPt); |
| 3442 | } |
| 3443 | } |
| 3444 | |
| 3445 | void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot, |
| 3446 | DenseMap<BasicBlock *, Value *> &Loads, |
| 3447 | Function &F) { |
| 3448 | // Lazilly create the spill slot. |
| 3449 | if (!SpillSlot) |
| 3450 | SpillSlot = new AllocaInst(V->getType(), nullptr, |
| 3451 | Twine(V->getName(), ".wineh.spillslot"), |
| 3452 | F.getEntryBlock().begin()); |
| 3453 | |
| 3454 | auto *UsingInst = cast<Instruction>(U.getUser()); |
| 3455 | if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) { |
| 3456 | // If this is a PHI node, we can't insert a load of the value before |
| 3457 | // the use. Instead insert the load in the predecessor block |
| 3458 | // corresponding to the incoming value. |
| 3459 | // |
| 3460 | // Note that if there are multiple edges from a basic block to this |
| 3461 | // PHI node that we cannot have multiple loads. The problem is that |
| 3462 | // the resulting PHI node will have multiple values (from each load) |
| 3463 | // coming in from the same block, which is illegal SSA form. |
| 3464 | // For this reason, we keep track of and reuse loads we insert. |
| 3465 | BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U); |
Joseph Tremoulet | 7031c9f | 2015-08-17 13:51:37 +0000 | [diff] [blame] | 3466 | if (auto *CatchRet = |
| 3467 | dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) { |
| 3468 | // Putting a load above a catchret and use on the phi would still leave |
| 3469 | // a cross-funclet def/use. We need to split the edge, change the |
| 3470 | // catchret to target the new block, and put the load there. |
| 3471 | BasicBlock *PHIBlock = UsingInst->getParent(); |
| 3472 | BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock); |
| 3473 | // SplitEdge gives us: |
| 3474 | // IncomingBlock: |
| 3475 | // ... |
| 3476 | // br label %NewBlock |
| 3477 | // NewBlock: |
| 3478 | // catchret label %PHIBlock |
| 3479 | // But we need: |
| 3480 | // IncomingBlock: |
| 3481 | // ... |
| 3482 | // catchret label %NewBlock |
| 3483 | // NewBlock: |
| 3484 | // br label %PHIBlock |
| 3485 | // So move the terminators to each others' blocks and swap their |
| 3486 | // successors. |
| 3487 | BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator()); |
| 3488 | Goto->removeFromParent(); |
| 3489 | CatchRet->removeFromParent(); |
| 3490 | IncomingBlock->getInstList().push_back(CatchRet); |
| 3491 | NewBlock->getInstList().push_back(Goto); |
| 3492 | Goto->setSuccessor(0, PHIBlock); |
| 3493 | CatchRet->setSuccessor(NewBlock); |
| 3494 | // Update the color mapping for the newly split edge. |
| 3495 | std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock]; |
| 3496 | BlockColors[NewBlock] = ColorsForPHIBlock; |
| 3497 | for (BasicBlock *FuncletPad : ColorsForPHIBlock) |
| 3498 | FuncletBlocks[FuncletPad].insert(NewBlock); |
| 3499 | // Treat the new block as incoming for load insertion. |
| 3500 | IncomingBlock = NewBlock; |
| 3501 | } |
Joseph Tremoulet | c9ff914 | 2015-08-13 14:30:10 +0000 | [diff] [blame] | 3502 | Value *&Load = Loads[IncomingBlock]; |
| 3503 | // Insert the load into the predecessor block |
| 3504 | if (!Load) |
| 3505 | Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"), |
| 3506 | /*Volatile=*/false, IncomingBlock->getTerminator()); |
| 3507 | |
| 3508 | U.set(Load); |
| 3509 | } else { |
| 3510 | // Reload right before the old use. |
| 3511 | auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"), |
| 3512 | /*Volatile=*/false, UsingInst); |
| 3513 | U.set(Load); |
| 3514 | } |
| 3515 | } |