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