1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
\r
3 // The LLVM Compiler Infrastructure
\r
5 // This file is distributed under the University of Illinois Open Source
\r
6 // License. See LICENSE.TXT for details.
\r
8 //===----------------------------------------------------------------------===//
\r
10 // This pass lowers LLVM IR exception handling into something closer to what the
\r
11 // backend wants. It snifs the personality function to see which kind of
\r
12 // preparation is necessary. If the personality function uses the Itanium LSDA,
\r
13 // this pass delegates to the DWARF EH preparation pass.
\r
15 //===----------------------------------------------------------------------===//
\r
17 #include "llvm/CodeGen/Passes.h"
\r
18 #include "llvm/ADT/MapVector.h"
\r
19 #include "llvm/ADT/TinyPtrVector.h"
\r
20 #include "llvm/Analysis/LibCallSemantics.h"
\r
21 #include "llvm/IR/Function.h"
\r
22 #include "llvm/IR/IRBuilder.h"
\r
23 #include "llvm/IR/Instructions.h"
\r
24 #include "llvm/IR/IntrinsicInst.h"
\r
25 #include "llvm/IR/Module.h"
\r
26 #include "llvm/IR/PatternMatch.h"
\r
27 #include "llvm/Pass.h"
\r
28 #include "llvm/Transforms/Utils/Cloning.h"
\r
29 #include "llvm/Transforms/Utils/Local.h"
\r
32 using namespace llvm;
\r
33 using namespace llvm::PatternMatch;
\r
35 #define DEBUG_TYPE "winehprepare"
\r
39 struct HandlerAllocas {
\r
40 TinyPtrVector<AllocaInst *> Allocas;
\r
41 int ParentFrameAllocationIndex;
\r
44 // This map is used to model frame variable usage during outlining, to
\r
45 // construct a structure type to hold the frame variables in a frame
\r
46 // allocation block, and to remap the frame variable allocas (including
\r
47 // spill locations as needed) to GEPs that get the variable from the
\r
48 // frame allocation structure.
\r
49 typedef MapVector<AllocaInst *, HandlerAllocas> FrameVarInfoMap;
\r
51 class WinEHPrepare : public FunctionPass {
\r
52 std::unique_ptr<FunctionPass> DwarfPrepare;
\r
55 static char ID; // Pass identification, replacement for typeid.
\r
56 WinEHPrepare(const TargetMachine *TM = nullptr)
\r
57 : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
\r
59 bool runOnFunction(Function &Fn) override;
\r
61 bool doFinalization(Module &M) override;
\r
63 void getAnalysisUsage(AnalysisUsage &AU) const override;
\r
65 const char *getPassName() const override {
\r
66 return "Windows exception handling preparation";
\r
70 bool prepareCPPEHHandlers(Function &F,
\r
71 SmallVectorImpl<LandingPadInst *> &LPads);
\r
72 bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
\r
73 LandingPadInst *LPad, CallInst *&EHAlloc,
\r
74 AllocaInst *&EHObjPtr, FrameVarInfoMap &VarInfo);
\r
77 class WinEHFrameVariableMaterializer : public ValueMaterializer {
\r
79 WinEHFrameVariableMaterializer(Function *OutlinedFn,
\r
80 FrameVarInfoMap &FrameVarInfo);
\r
81 ~WinEHFrameVariableMaterializer() {}
\r
83 virtual Value *materializeValueFor(Value *V) override;
\r
86 FrameVarInfoMap &FrameVarInfo;
\r
87 IRBuilder<> Builder;
\r
90 class WinEHCatchDirector : public CloningDirector {
\r
92 WinEHCatchDirector(LandingPadInst *LPI, Function *CatchFn, Value *Selector,
\r
93 Value *EHObj, FrameVarInfoMap &VarInfo)
\r
94 : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),
\r
95 Materializer(CatchFn, VarInfo),
\r
96 SelectorIDType(Type::getInt32Ty(LPI->getContext())),
\r
97 Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}
\r
99 CloningAction handleInstruction(ValueToValueMapTy &VMap,
\r
100 const Instruction *Inst,
\r
101 BasicBlock *NewBB) override;
\r
103 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
\r
106 LandingPadInst *LPI;
\r
107 Value *CurrentSelector;
\r
109 WinEHFrameVariableMaterializer Materializer;
\r
110 Type *SelectorIDType;
\r
113 const Value *ExtractedEHPtr;
\r
114 const Value *ExtractedSelector;
\r
115 const Value *EHPtrStoreAddr;
\r
116 const Value *SelectorStoreAddr;
\r
118 } // end anonymous namespace
\r
120 char WinEHPrepare::ID = 0;
\r
121 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
\r
124 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
\r
125 return new WinEHPrepare(TM);
\r
128 static bool isMSVCPersonality(EHPersonality Pers) {
\r
129 return Pers == EHPersonality::MSVC_Win64SEH ||
\r
130 Pers == EHPersonality::MSVC_CXX;
\r
133 bool WinEHPrepare::runOnFunction(Function &Fn) {
\r
134 SmallVector<LandingPadInst *, 4> LPads;
\r
135 SmallVector<ResumeInst *, 4> Resumes;
\r
136 for (BasicBlock &BB : Fn) {
\r
137 if (auto *LP = BB.getLandingPadInst())
\r
138 LPads.push_back(LP);
\r
139 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
\r
140 Resumes.push_back(Resume);
\r
143 // No need to prepare functions that lack landing pads.
\r
147 // Classify the personality to see what kind of preparation we need.
\r
148 EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
\r
150 // Delegate through to the DWARF pass if this is unrecognized.
\r
151 if (!isMSVCPersonality(Pers))
\r
152 return DwarfPrepare->runOnFunction(Fn);
\r
154 // FIXME: This only returns true if the C++ EH handlers were outlined.
\r
155 // When that code is complete, it should always return whatever
\r
156 // prepareCPPEHHandlers returns.
\r
157 if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))
\r
160 // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.
\r
161 if (Resumes.empty())
\r
164 for (ResumeInst *Resume : Resumes) {
\r
165 IRBuilder<>(Resume).CreateUnreachable();
\r
166 Resume->eraseFromParent();
\r
172 bool WinEHPrepare::doFinalization(Module &M) {
\r
173 return DwarfPrepare->doFinalization(M);
\r
176 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
\r
177 DwarfPrepare->getAnalysisUsage(AU);
\r
180 bool WinEHPrepare::prepareCPPEHHandlers(
\r
181 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
\r
182 // These containers are used to re-map frame variables that are used in
\r
183 // outlined catch and cleanup handlers. They will be populated as the
\r
184 // handlers are outlined.
\r
185 FrameVarInfoMap FrameVarInfo;
\r
186 SmallVector<CallInst *, 4> HandlerAllocs;
\r
187 SmallVector<AllocaInst *, 4> HandlerEHObjPtrs;
\r
189 bool HandlersOutlined = false;
\r
191 for (LandingPadInst *LPad : LPads) {
\r
192 // Look for evidence that this landingpad has already been processed.
\r
193 bool LPadHasActionList = false;
\r
194 BasicBlock *LPadBB = LPad->getParent();
\r
195 for (Instruction &Inst : LPadBB->getInstList()) {
\r
196 // FIXME: Make this an intrinsic.
\r
197 if (auto *Call = dyn_cast<CallInst>(&Inst))
\r
198 if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {
\r
199 LPadHasActionList = true;
\r
204 // If we've already outlined the handlers for this landingpad,
\r
205 // there's nothing more to do here.
\r
206 if (LPadHasActionList)
\r
209 for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;
\r
211 if (LPad->isCatch(Idx)) {
\r
212 // Create a new instance of the handler data structure in the
\r
213 // HandlerData vector.
\r
214 CallInst *EHAlloc = nullptr;
\r
215 AllocaInst *EHObjPtr = nullptr;
\r
216 bool Outlined = outlineCatchHandler(&F, LPad->getClause(Idx), LPad,
\r
217 EHAlloc, EHObjPtr, FrameVarInfo);
\r
219 HandlersOutlined = true;
\r
220 // These values must be resolved after all handlers have been
\r
223 HandlerAllocs.push_back(EHAlloc);
\r
225 HandlerEHObjPtrs.push_back(EHObjPtr);
\r
227 } // End if (isCatch)
\r
228 } // End for each clause
\r
229 } // End for each landingpad
\r
231 // If nothing got outlined, there is no more processing to be done.
\r
232 if (!HandlersOutlined)
\r
235 // FIXME: We will replace the landingpad bodies with llvm.eh.actions
\r
236 // calls and indirect branches here and then delete blocks
\r
237 // which are no longer reachable. That will get rid of the
\r
238 // handlers that we have outlined. There is code below
\r
239 // that looks for allocas with no uses in the parent function.
\r
240 // That will only happen after the pruning is implemented.
\r
242 // Remap the frame variables.
\r
243 SmallVector<Type *, 2> StructTys;
\r
244 StructTys.push_back(Type::getInt32Ty(F.getContext())); // EH state
\r
245 StructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object
\r
247 // Start the index at two since we always have the above fields at 0 and 1.
\r
250 // FIXME: Sort the FrameVarInfo vector by the ParentAlloca size and alignment
\r
251 // and add padding as necessary to provide the proper alignment.
\r
253 // Map the alloca instructions to the corresponding index in the
\r
254 // frame allocation structure. If any alloca is used only in a single
\r
255 // handler and is not used in the parent frame after outlining, it will
\r
256 // be assigned an index of -1, meaning the handler can keep its
\r
257 // "temporary" alloca and the original alloca can be erased from the
\r
258 // parent function. If we later encounter this alloca in a second
\r
259 // handler, we will assign it a place in the frame allocation structure
\r
260 // at that time. Since the instruction replacement doesn't happen until
\r
261 // all the entries in the HandlerData have been processed this isn't a
\r
263 for (auto &VarInfoEntry : FrameVarInfo) {
\r
264 AllocaInst *ParentAlloca = VarInfoEntry.first;
\r
265 HandlerAllocas &AllocaInfo = VarInfoEntry.second;
\r
267 // If the instruction still has uses in the parent function or if it is
\r
268 // referenced by more than one handler, add it to the frame allocation
\r
270 if (ParentAlloca->getNumUses() != 0 || AllocaInfo.Allocas.size() > 1) {
\r
271 Type *VarTy = ParentAlloca->getAllocatedType();
\r
272 StructTys.push_back(VarTy);
\r
273 AllocaInfo.ParentFrameAllocationIndex = Idx++;
\r
275 // If the variable is not used in the parent frame and it is only used
\r
276 // in one handler, the alloca can be removed from the parent frame
\r
277 // and the handler will keep its "temporary" alloca to define the value.
\r
278 // An element index of -1 is used to indicate this condition.
\r
279 AllocaInfo.ParentFrameAllocationIndex = -1;
\r
283 // Having filled the StructTys vector and assigned an index to each element,
\r
284 // we can now create the structure.
\r
285 StructType *EHDataStructTy = StructType::create(
\r
286 F.getContext(), StructTys, "struct." + F.getName().str() + ".ehdata");
\r
287 IRBuilder<> Builder(F.getParent()->getContext());
\r
289 // Create a frame allocation.
\r
290 Module *M = F.getParent();
\r
291 LLVMContext &Context = M->getContext();
\r
292 BasicBlock *Entry = &F.getEntryBlock();
\r
293 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
\r
294 Function *FrameAllocFn =
\r
295 Intrinsic::getDeclaration(M, Intrinsic::frameallocate);
\r
296 uint64_t EHAllocSize = M->getDataLayout()->getTypeAllocSize(EHDataStructTy);
\r
297 Value *FrameAllocArgs[] = {
\r
298 ConstantInt::get(Type::getInt32Ty(Context), EHAllocSize)};
\r
299 CallInst *FrameAlloc =
\r
300 Builder.CreateCall(FrameAllocFn, FrameAllocArgs, "frame.alloc");
\r
302 Value *FrameEHData = Builder.CreateBitCast(
\r
303 FrameAlloc, EHDataStructTy->getPointerTo(), "eh.data");
\r
305 // Now visit each handler that is using the structure and bitcast its EHAlloc
\r
306 // value to be a pointer to the frame alloc structure.
\r
307 DenseMap<Function *, Value *> EHDataMap;
\r
308 for (CallInst *EHAlloc : HandlerAllocs) {
\r
309 // The EHAlloc has no uses at this time, so we need to just insert the
\r
310 // cast before the next instruction. There is always a next instruction.
\r
311 BasicBlock::iterator II = EHAlloc;
\r
313 Builder.SetInsertPoint(cast<Instruction>(II));
\r
314 Value *EHData = Builder.CreateBitCast(
\r
315 EHAlloc, EHDataStructTy->getPointerTo(), "eh.data");
\r
316 EHDataMap[EHAlloc->getParent()->getParent()] = EHData;
\r
319 // Next, replace the place-holder EHObjPtr allocas with GEP instructions
\r
320 // that pull the EHObjPtr from the frame alloc structure
\r
321 for (AllocaInst *EHObjPtr : HandlerEHObjPtrs) {
\r
322 Value *EHData = EHDataMap[EHObjPtr->getParent()->getParent()];
\r
323 Value *ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1);
\r
324 EHObjPtr->replaceAllUsesWith(ElementPtr);
\r
325 EHObjPtr->removeFromParent();
\r
326 ElementPtr->takeName(EHObjPtr);
\r
330 // Finally, replace all of the temporary allocas for frame variables used in
\r
331 // the outlined handlers and the original frame allocas with GEP instructions
\r
332 // that get the equivalent pointer from the frame allocation struct.
\r
333 for (auto &VarInfoEntry : FrameVarInfo) {
\r
334 AllocaInst *ParentAlloca = VarInfoEntry.first;
\r
335 HandlerAllocas &AllocaInfo = VarInfoEntry.second;
\r
336 int Idx = AllocaInfo.ParentFrameAllocationIndex;
\r
338 // If we have an index of -1 for this instruction, it means it isn't used
\r
339 // outside of this handler. In that case, we just keep the "temporary"
\r
340 // alloca in the handler and erase the original alloca from the parent.
\r
342 ParentAlloca->eraseFromParent();
\r
344 // Otherwise, we replace the parent alloca and all outlined allocas
\r
345 // which map to it with GEP instructions.
\r
347 // First replace the original alloca.
\r
348 Builder.SetInsertPoint(ParentAlloca);
\r
349 Builder.SetCurrentDebugLocation(ParentAlloca->getDebugLoc());
\r
350 Value *ElementPtr =
\r
351 Builder.CreateConstInBoundsGEP2_32(FrameEHData, 0, Idx);
\r
352 ParentAlloca->replaceAllUsesWith(ElementPtr);
\r
353 ParentAlloca->removeFromParent();
\r
354 ElementPtr->takeName(ParentAlloca);
\r
355 delete ParentAlloca;
\r
357 // Next replace all outlined allocas that are mapped to it.
\r
358 for (AllocaInst *TempAlloca : AllocaInfo.Allocas) {
\r
359 Value *EHData = EHDataMap[TempAlloca->getParent()->getParent()];
\r
360 // FIXME: Sink this GEP into the blocks where it is used.
\r
361 Builder.SetInsertPoint(TempAlloca);
\r
362 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
\r
363 ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, Idx);
\r
364 TempAlloca->replaceAllUsesWith(ElementPtr);
\r
365 TempAlloca->removeFromParent();
\r
366 ElementPtr->takeName(TempAlloca);
\r
369 } // end else of if (Idx == -1)
\r
370 } // End for each FrameVarInfo entry.
\r
372 return HandlersOutlined;
\r
375 bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
\r
376 LandingPadInst *LPad, CallInst *&EHAlloc,
\r
377 AllocaInst *&EHObjPtr,
\r
378 FrameVarInfoMap &VarInfo) {
\r
379 Module *M = SrcFn->getParent();
\r
380 LLVMContext &Context = M->getContext();
\r
382 // Create a new function to receive the handler contents.
\r
383 Type *Int8PtrType = Type::getInt8PtrTy(Context);
\r
384 std::vector<Type *> ArgTys;
\r
385 ArgTys.push_back(Int8PtrType);
\r
386 ArgTys.push_back(Int8PtrType);
\r
387 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
\r
388 Function *CatchHandler = Function::Create(
\r
389 FnType, GlobalVariable::ExternalLinkage, SrcFn->getName() + ".catch", M);
\r
391 // Generate a standard prolog to setup the frame recovery structure.
\r
392 IRBuilder<> Builder(Context);
\r
393 BasicBlock *Entry = BasicBlock::Create(Context, "catch.entry");
\r
394 CatchHandler->getBasicBlockList().push_front(Entry);
\r
395 Builder.SetInsertPoint(Entry);
\r
396 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
\r
398 // The outlined handler will be called with the parent's frame pointer as
\r
399 // its second argument. To enable the handler to access variables from
\r
400 // the parent frame, we use that pointer to get locate a special block
\r
401 // of memory that was allocated using llvm.eh.allocateframe for this
\r
402 // purpose. During the outlining process we will determine which frame
\r
403 // variables are used in handlers and create a structure that maps these
\r
404 // variables into the frame allocation block.
\r
406 // The frame allocation block also contains an exception state variable
\r
407 // used by the runtime and a pointer to the exception object pointer
\r
408 // which will be filled in by the runtime for use in the handler.
\r
409 Function *RecoverFrameFn =
\r
410 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
\r
411 Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),
\r
412 &(CatchHandler->getArgumentList().back())};
\r
413 EHAlloc = Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
\r
415 // This alloca is only temporary. We'll be replacing it once we know all the
\r
416 // frame variables that need to go in the frame allocation structure.
\r
417 EHObjPtr = Builder.CreateAlloca(Int8PtrType, 0, "eh.obj.ptr");
\r
419 // This will give us a raw pointer to the exception object, which
\r
420 // corresponds to the formal parameter of the catch statement. If the
\r
421 // handler uses this object, we will generate code during the outlining
\r
422 // process to cast the pointer to the appropriate type and deference it
\r
423 // as necessary. The un-outlined landing pad code represents the
\r
424 // exception object as the result of the llvm.eh.begincatch call.
\r
425 Value *EHObj = Builder.CreateLoad(EHObjPtr, false, "eh.obj");
\r
427 ValueToValueMapTy VMap;
\r
429 // FIXME: Map other values referenced in the filter handler.
\r
431 WinEHCatchDirector Director(LPad, CatchHandler, SelectorType, EHObj, VarInfo);
\r
433 SmallVector<ReturnInst *, 8> Returns;
\r
434 ClonedCodeInfo InlinedFunctionInfo;
\r
436 BasicBlock::iterator II = LPad;
\r
438 CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
\r
439 /*ModuleLevelChanges=*/false, Returns, "",
\r
440 &InlinedFunctionInfo,
\r
441 SrcFn->getParent()->getDataLayout(), &Director);
\r
443 // Move all the instructions in the first cloned block into our entry block.
\r
444 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
\r
445 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
\r
446 FirstClonedBB->eraseFromParent();
\r
451 CloningDirector::CloningAction WinEHCatchDirector::handleInstruction(
\r
452 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
\r
453 // Intercept instructions which extract values from the landing pad aggregate.
\r
454 if (auto *Extract = dyn_cast<ExtractValueInst>(Inst)) {
\r
455 if (Extract->getAggregateOperand() == LPI) {
\r
456 assert(Extract->getNumIndices() == 1 &&
\r
457 "Unexpected operation: extracting both landing pad values");
\r
458 assert((*(Extract->idx_begin()) == 0 || *(Extract->idx_begin()) == 1) &&
\r
459 "Unexpected operation: extracting an unknown landing pad element");
\r
461 if (*(Extract->idx_begin()) == 0) {
\r
462 // Element 0 doesn't directly corresponds to anything in the WinEH
\r
464 // It will be stored to a memory location, then later loaded and finally
\r
465 // the loaded value will be used as the argument to an
\r
466 // llvm.eh.begincatch
\r
467 // call. We're tracking it here so that we can skip the store and load.
\r
468 ExtractedEHPtr = Inst;
\r
470 // Element 1 corresponds to the filter selector. We'll map it to 1 for
\r
471 // matching purposes, but it will also probably be stored to memory and
\r
472 // reloaded, so we need to track the instuction so that we can map the
\r
473 // loaded value too.
\r
474 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
\r
475 ExtractedSelector = Inst;
\r
478 // Tell the caller not to clone this instruction.
\r
479 return CloningDirector::SkipInstruction;
\r
481 // Other extract value instructions just get cloned.
\r
482 return CloningDirector::CloneInstruction;
\r
485 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
\r
486 // Look for and suppress stores of the extracted landingpad values.
\r
487 const Value *StoredValue = Store->getValueOperand();
\r
488 if (StoredValue == ExtractedEHPtr) {
\r
489 EHPtrStoreAddr = Store->getPointerOperand();
\r
490 return CloningDirector::SkipInstruction;
\r
492 if (StoredValue == ExtractedSelector) {
\r
493 SelectorStoreAddr = Store->getPointerOperand();
\r
494 return CloningDirector::SkipInstruction;
\r
497 // Any other store just gets cloned.
\r
498 return CloningDirector::CloneInstruction;
\r
501 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
\r
502 // Look for loads of (previously suppressed) landingpad values.
\r
503 // The EHPtr load can be ignored (it should only be used as
\r
504 // an argument to llvm.eh.begincatch), but the selector value
\r
505 // needs to be mapped to a constant value of 1 to be used to
\r
506 // simplify the branching to always flow to the current handler.
\r
507 const Value *LoadAddr = Load->getPointerOperand();
\r
508 if (LoadAddr == EHPtrStoreAddr) {
\r
509 VMap[Inst] = UndefValue::get(Int8PtrType);
\r
510 return CloningDirector::SkipInstruction;
\r
512 if (LoadAddr == SelectorStoreAddr) {
\r
513 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
\r
514 return CloningDirector::SkipInstruction;
\r
517 // Any other loads just get cloned.
\r
518 return CloningDirector::CloneInstruction;
\r
521 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) {
\r
522 // The argument to the call is some form of the first element of the
\r
523 // landingpad aggregate value, but that doesn't matter. It isn't used
\r
525 // The return value of this instruction, however, is used to access the
\r
526 // EH object pointer. We have generated an instruction to get that value
\r
527 // from the EH alloc block, so we can just map to that here.
\r
528 VMap[Inst] = EHObj;
\r
529 return CloningDirector::SkipInstruction;
\r
531 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) {
\r
532 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
\r
533 // It might be interesting to track whether or not we are inside a catch
\r
534 // function, but that might make the algorithm more brittle than it needs
\r
537 // The end catch call can occur in one of two places: either in a
\r
539 // block that is part of the catch handlers exception mechanism, or at the
\r
540 // end of the catch block. If it occurs in a landing pad, we must skip it
\r
541 // and continue so that the landing pad gets cloned.
\r
542 // FIXME: This case isn't fully supported yet and shouldn't turn up in any
\r
543 // of the test cases until it is.
\r
544 if (IntrinCall->getParent()->isLandingPad())
\r
545 return CloningDirector::SkipInstruction;
\r
547 // If an end catch occurs anywhere else the next instruction should be an
\r
548 // unconditional branch instruction that we want to replace with a return
\r
549 // to the the address of the branch target.
\r
550 const BasicBlock *EndCatchBB = IntrinCall->getParent();
\r
551 const TerminatorInst *Terminator = EndCatchBB->getTerminator();
\r
552 const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
\r
553 assert(Branch && Branch->isUnconditional());
\r
554 assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
\r
555 BasicBlock::const_iterator(Branch));
\r
557 ReturnInst::Create(NewBB->getContext(),
\r
558 BlockAddress::get(Branch->getSuccessor(0)), NewBB);
\r
560 // We just added a terminator to the cloned block.
\r
561 // Tell the caller to stop processing the current basic block so that
\r
562 // the branch instruction will be skipped.
\r
563 return CloningDirector::StopCloningBB;
\r
565 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) {
\r
566 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
\r
567 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
\r
568 // This causes a replacement that will collapse the landing pad CFG based
\r
569 // on the filter function we intend to match.
\r
570 if (Selector == CurrentSelector)
\r
571 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
\r
573 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
\r
574 // Tell the caller not to clone this instruction.
\r
575 return CloningDirector::SkipInstruction;
\r
578 // Continue with the default cloning behavior.
\r
579 return CloningDirector::CloneInstruction;
\r
582 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
\r
583 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
\r
584 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
\r
585 Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());
\r
586 // FIXME: Do something with the FrameVarMapped so that it is shared across the
\r
590 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
\r
591 // If we're asked to materialize an alloca variable, we temporarily
\r
592 // create a matching alloca in the outlined function. When all the
\r
593 // outlining is complete, we'll collect these into a structure and
\r
594 // replace these temporary allocas with GEPs referencing the frame
\r
595 // allocation block.
\r
596 if (auto *AV = dyn_cast<AllocaInst>(V)) {
\r
597 AllocaInst *NewAlloca = Builder.CreateAlloca(
\r
598 AV->getAllocatedType(), AV->getArraySize(), AV->getName());
\r
599 FrameVarInfo[AV].Allocas.push_back(NewAlloca);
\r
603 // FIXME: Do PHI nodes need special handling?
\r
605 // FIXME: Are there other cases we can handle better? GEP, ExtractValue, etc.
\r
607 // FIXME: This doesn't work during cloning because it finds an instruction
\r
608 // in the use list that isn't yet part of a basic block.
\r
610 // If we're asked to remap some other instruction, we'll need to
\r
611 // spill it to an alloca variable in the parent function and add a
\r
612 // temporary alloca in the outlined function to be processed as
\r
613 // described above.
\r
614 Instruction *Inst = dyn_cast<Instruction>(V);
\r
616 AllocaInst *Spill = DemoteRegToStack(*Inst, true);
\r
617 AllocaInst *NewAlloca = Builder.CreateAlloca(Spill->getAllocatedType(),
\r
618 Spill->getArraySize());
\r
619 FrameVarMap[AV] = NewAlloca;
\r