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