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