1 //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
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 file contains support for writing Win64 exception info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "WinException.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/WinEHFuncInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCWin64EH.h"
32 #include "llvm/Support/COFF.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 using namespace llvm;
43 
44 WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
45   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
46   // platforms use an imagerel32 relocation to refer to symbols.
47   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
48 }
49 
50 WinException::~WinException() {}
51 
52 /// endModule - Emit all exception information that should come after the
53 /// content.
54 void WinException::endModule() {
55   auto &OS = *Asm->OutStreamer;
56   const Module *M = MMI->getModule();
57   for (const Function &F : *M)
58     if (F.hasFnAttribute("safeseh"))
59       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
60 }
61 
62 void WinException::beginFunction(const MachineFunction *MF) {
63   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
64 
65   // If any landing pads survive, we need an EH table.
66   bool hasLandingPads = !MMI->getLandingPads().empty();
67   bool hasEHFunclets = MMI->hasEHFunclets();
68 
69   const Function *F = MF->getFunction();
70 
71   shouldEmitMoves = Asm->needsSEHMoves();
72 
73   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
74   unsigned PerEncoding = TLOF.getPersonalityEncoding();
75 
76   EHPersonality Per = EHPersonality::Unknown;
77   const Function *PerFn = nullptr;
78   if (F->hasPersonalityFn()) {
79     PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
80     Per = classifyEHPersonality(PerFn);
81   }
82 
83   bool forceEmitPersonality = F->hasPersonalityFn() &&
84                               !isNoOpWithoutInvoke(Per) &&
85                               F->needsUnwindTableEntry();
86 
87   shouldEmitPersonality =
88       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
89                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
90 
91   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
92   shouldEmitLSDA = shouldEmitPersonality &&
93     LSDAEncoding != dwarf::DW_EH_PE_omit;
94 
95   // If we're not using CFI, we don't want the CFI or the personality, but we
96   // might want EH tables if we had EH pads.
97   if (!Asm->MAI->usesWindowsCFI() || (!MF->hasWinCFI() && !PerFn)) {
98     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
99       // If this is 32-bit SEH and we don't have any funclets (really invokes),
100       // make sure we emit the parent offset label. Some unreferenced filter
101       // functions may still refer to it.
102       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
103       StringRef FLinkageName =
104           GlobalValue::getRealLinkageName(MF->getFunction()->getName());
105       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
106     }
107     shouldEmitLSDA = hasEHFunclets;
108     shouldEmitPersonality = false;
109     return;
110   }
111 
112   beginFunclet(MF->front(), Asm->CurrentFnSym);
113 }
114 
115 /// endFunction - Gather and emit post-function exception information.
116 ///
117 void WinException::endFunction(const MachineFunction *MF) {
118   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
119     return;
120 
121   const Function *F = MF->getFunction();
122   EHPersonality Per = EHPersonality::Unknown;
123   if (F->hasPersonalityFn())
124     Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
125 
126   // Get rid of any dead landing pads if we're not using funclets. In funclet
127   // schemes, the landing pad is not actually reachable. It only exists so
128   // that we can emit the right table data.
129   if (!isFuncletEHPersonality(Per))
130     MMI->TidyLandingPads();
131 
132   endFunclet();
133 
134   // endFunclet will emit the necessary .xdata tables for x64 SEH.
135   if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
136     return;
137 
138   if (shouldEmitPersonality || shouldEmitLSDA) {
139     Asm->OutStreamer->PushSection();
140 
141     // Just switch sections to the right xdata section.
142     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
143         Asm->OutStreamer->getCurrentSectionOnly());
144     Asm->OutStreamer->SwitchSection(XData);
145 
146     // Emit the tables appropriate to the personality function in use. If we
147     // don't recognize the personality, assume it uses an Itanium-style LSDA.
148     if (Per == EHPersonality::MSVC_Win64SEH)
149       emitCSpecificHandlerTable(MF);
150     else if (Per == EHPersonality::MSVC_X86SEH)
151       emitExceptHandlerTable(MF);
152     else if (Per == EHPersonality::MSVC_CXX)
153       emitCXXFrameHandler3Table(MF);
154     else if (Per == EHPersonality::CoreCLR)
155       emitCLRExceptionTable(MF);
156     else
157       emitExceptionTable();
158 
159     Asm->OutStreamer->PopSection();
160   }
161 }
162 
163 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
164 static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
165                                    const MachineBasicBlock *MBB) {
166   if (!MBB)
167     return nullptr;
168 
169   assert(MBB->isEHFuncletEntry());
170 
171   // Give catches and cleanups a name based off of their parent function and
172   // their funclet entry block's number.
173   const MachineFunction *MF = MBB->getParent();
174   const Function *F = MF->getFunction();
175   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
176   MCContext &Ctx = MF->getContext();
177   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
178   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
179                                Twine(MBB->getNumber()) + "@?0?" +
180                                FuncLinkageName + "@4HA");
181 }
182 
183 void WinException::beginFunclet(const MachineBasicBlock &MBB,
184                                 MCSymbol *Sym) {
185   CurrentFuncletEntry = &MBB;
186 
187   const Function *F = Asm->MF->getFunction();
188   // If a symbol was not provided for the funclet, invent one.
189   if (!Sym) {
190     Sym = getMCSymbolForMBB(Asm, &MBB);
191 
192     // Describe our funclet symbol as a function with internal linkage.
193     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
194     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
195     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
196                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
197     Asm->OutStreamer->EndCOFFSymbolDef();
198 
199     // We want our funclet's entry point to be aligned such that no nops will be
200     // present after the label.
201     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
202                        F);
203 
204     // Now that we've emitted the alignment directive, point at our funclet.
205     Asm->OutStreamer->EmitLabel(Sym);
206   }
207 
208   // Mark 'Sym' as starting our funclet.
209   if (shouldEmitMoves || shouldEmitPersonality)
210     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
211 
212   if (shouldEmitPersonality) {
213     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
214     const Function *PerFn = nullptr;
215 
216     // Determine which personality routine we are using for this funclet.
217     if (F->hasPersonalityFn())
218       PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
219     const MCSymbol *PersHandlerSym =
220         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
221 
222     // Classify the personality routine so that we may reason about it.
223     EHPersonality Per = classifyEHPersonality(PerFn);
224 
225     // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
226     if (Per != EHPersonality::MSVC_CXX ||
227         !CurrentFuncletEntry->isCleanupFuncletEntry())
228       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
229   }
230 }
231 
232 void WinException::endFunclet() {
233   // No funclet to process?  Great, we have nothing to do.
234   if (!CurrentFuncletEntry)
235     return;
236 
237   if (shouldEmitMoves || shouldEmitPersonality) {
238     const Function *F = Asm->MF->getFunction();
239     EHPersonality Per = EHPersonality::Unknown;
240     if (F->hasPersonalityFn())
241       Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
242 
243     // The .seh_handlerdata directive implicitly switches section, push the
244     // current section so that we may return to it.
245     Asm->OutStreamer->PushSection();
246 
247     // Emit an UNWIND_INFO struct describing the prologue.
248     Asm->OutStreamer->EmitWinEHHandlerData();
249 
250     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
251         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
252       // If this is a C++ catch funclet (or the parent function),
253       // emit a reference to the LSDA for the parent function.
254       StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
255       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
256           Twine("$cppxdata$", FuncLinkageName));
257       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
258     } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
259                !CurrentFuncletEntry->isEHFuncletEntry()) {
260       // If this is the parent function in Win64 SEH, emit the LSDA immediately
261       // following .seh_handlerdata.
262       emitCSpecificHandlerTable(Asm->MF);
263     }
264 
265     // Switch back to the previous section now that we are done writing to
266     // .xdata.
267     Asm->OutStreamer->PopSection();
268 
269     // Emit a .seh_endproc directive to mark the end of the function.
270     Asm->OutStreamer->EmitWinCFIEndProc();
271   }
272 
273   // Let's make sure we don't try to end the same funclet twice.
274   CurrentFuncletEntry = nullptr;
275 }
276 
277 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
278   if (!Value)
279     return MCConstantExpr::create(0, Asm->OutContext);
280   return MCSymbolRefExpr::create(Value, useImageRel32
281                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
282                                             : MCSymbolRefExpr::VK_None,
283                                  Asm->OutContext);
284 }
285 
286 const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
287   if (!GV)
288     return MCConstantExpr::create(0, Asm->OutContext);
289   return create32bitRef(Asm->getSymbol(GV));
290 }
291 
292 const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
293   return MCBinaryExpr::createAdd(create32bitRef(Label),
294                                  MCConstantExpr::create(1, Asm->OutContext),
295                                  Asm->OutContext);
296 }
297 
298 const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
299                                       const MCSymbol *OffsetFrom) {
300   return MCBinaryExpr::createSub(
301       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
302       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
303 }
304 
305 const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
306                                              const MCSymbol *OffsetFrom) {
307   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
308                                  MCConstantExpr::create(1, Asm->OutContext),
309                                  Asm->OutContext);
310 }
311 
312 int WinException::getFrameIndexOffset(int FrameIndex,
313                                       const WinEHFuncInfo &FuncInfo) {
314   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
315   unsigned UnusedReg;
316   if (Asm->MAI->usesWindowsCFI()) {
317     int Offset =
318         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
319                                            /*IgnoreSPUpdates*/ true);
320     assert(UnusedReg ==
321            Asm->MF->getSubtarget()
322                .getTargetLowering()
323                ->getStackPointerRegisterToSaveRestore());
324     return Offset;
325   }
326 
327   // For 32-bit, offsets should be relative to the end of the EH registration
328   // node. For 64-bit, it's relative to SP at the end of the prologue.
329   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
330   int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
331   Offset += FuncInfo.EHRegNodeEndOffset;
332   return Offset;
333 }
334 
335 namespace {
336 
337 /// Top-level state used to represent unwind to caller
338 const int NullState = -1;
339 
340 struct InvokeStateChange {
341   /// EH Label immediately after the last invoke in the previous state, or
342   /// nullptr if the previous state was the null state.
343   const MCSymbol *PreviousEndLabel;
344 
345   /// EH label immediately before the first invoke in the new state, or nullptr
346   /// if the new state is the null state.
347   const MCSymbol *NewStartLabel;
348 
349   /// State of the invoke following NewStartLabel, or NullState to indicate
350   /// the presence of calls which may unwind to caller.
351   int NewState;
352 };
353 
354 /// Iterator that reports all the invoke state changes in a range of machine
355 /// basic blocks.  Changes to the null state are reported whenever a call that
356 /// may unwind to caller is encountered.  The MBB range is expected to be an
357 /// entire function or funclet, and the start and end of the range are treated
358 /// as being in the NullState even if there's not an unwind-to-caller call
359 /// before the first invoke or after the last one (i.e., the first state change
360 /// reported is the first change to something other than NullState, and a
361 /// change back to NullState is always reported at the end of iteration).
362 class InvokeStateChangeIterator {
363   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
364                             MachineFunction::const_iterator MFI,
365                             MachineFunction::const_iterator MFE,
366                             MachineBasicBlock::const_iterator MBBI,
367                             int BaseState)
368       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
369     LastStateChange.PreviousEndLabel = nullptr;
370     LastStateChange.NewStartLabel = nullptr;
371     LastStateChange.NewState = BaseState;
372     scan();
373   }
374 
375 public:
376   static iterator_range<InvokeStateChangeIterator>
377   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
378         MachineFunction::const_iterator End, int BaseState = NullState) {
379     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
380     // the end of the last block.
381     assert(Begin != End);
382     auto BlockBegin = Begin->begin();
383     auto BlockEnd = std::prev(End)->end();
384     return make_range(
385         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
386         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
387   }
388 
389   // Iterator methods.
390   bool operator==(const InvokeStateChangeIterator &O) const {
391     assert(BaseState == O.BaseState);
392     // Must be visiting same block.
393     if (MFI != O.MFI)
394       return false;
395     // Must be visiting same isntr.
396     if (MBBI != O.MBBI)
397       return false;
398     // At end of block/instr iteration, we can still have two distinct states:
399     // one to report the final EndLabel, and another indicating the end of the
400     // state change iteration.  Check for CurrentEndLabel equality to
401     // distinguish these.
402     return CurrentEndLabel == O.CurrentEndLabel;
403   }
404 
405   bool operator!=(const InvokeStateChangeIterator &O) const {
406     return !operator==(O);
407   }
408   InvokeStateChange &operator*() { return LastStateChange; }
409   InvokeStateChange *operator->() { return &LastStateChange; }
410   InvokeStateChangeIterator &operator++() { return scan(); }
411 
412 private:
413   InvokeStateChangeIterator &scan();
414 
415   const WinEHFuncInfo &EHInfo;
416   const MCSymbol *CurrentEndLabel = nullptr;
417   MachineFunction::const_iterator MFI;
418   MachineFunction::const_iterator MFE;
419   MachineBasicBlock::const_iterator MBBI;
420   InvokeStateChange LastStateChange;
421   bool VisitingInvoke = false;
422   int BaseState;
423 };
424 
425 } // end anonymous namespace
426 
427 InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
428   bool IsNewBlock = false;
429   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
430     if (IsNewBlock)
431       MBBI = MFI->begin();
432     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
433       const MachineInstr &MI = *MBBI;
434       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
435           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
436         // Indicate a change of state to the null state.  We don't have
437         // start/end EH labels handy but the caller won't expect them for
438         // null state regions.
439         LastStateChange.PreviousEndLabel = CurrentEndLabel;
440         LastStateChange.NewStartLabel = nullptr;
441         LastStateChange.NewState = BaseState;
442         CurrentEndLabel = nullptr;
443         // Don't re-visit this instr on the next scan
444         ++MBBI;
445         return *this;
446       }
447 
448       // All other state changes are at EH labels before/after invokes.
449       if (!MI.isEHLabel())
450         continue;
451       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
452       if (Label == CurrentEndLabel) {
453         VisitingInvoke = false;
454         continue;
455       }
456       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
457       // Ignore EH labels that aren't the ones inserted before an invoke
458       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
459         continue;
460       auto &StateAndEnd = InvokeMapIter->second;
461       int NewState = StateAndEnd.first;
462       // Keep track of the fact that we're between EH start/end labels so
463       // we know not to treat the inoke we'll see as unwinding to caller.
464       VisitingInvoke = true;
465       if (NewState == LastStateChange.NewState) {
466         // The state isn't actually changing here.  Record the new end and
467         // keep going.
468         CurrentEndLabel = StateAndEnd.second;
469         continue;
470       }
471       // Found a state change to report
472       LastStateChange.PreviousEndLabel = CurrentEndLabel;
473       LastStateChange.NewStartLabel = Label;
474       LastStateChange.NewState = NewState;
475       // Start keeping track of the new current end
476       CurrentEndLabel = StateAndEnd.second;
477       // Don't re-visit this instr on the next scan
478       ++MBBI;
479       return *this;
480     }
481   }
482   // Iteration hit the end of the block range.
483   if (LastStateChange.NewState != BaseState) {
484     // Report the end of the last new state
485     LastStateChange.PreviousEndLabel = CurrentEndLabel;
486     LastStateChange.NewStartLabel = nullptr;
487     LastStateChange.NewState = BaseState;
488     // Leave CurrentEndLabel non-null to distinguish this state from end.
489     assert(CurrentEndLabel != nullptr);
490     return *this;
491   }
492   // We've reported all state changes and hit the end state.
493   CurrentEndLabel = nullptr;
494   return *this;
495 }
496 
497 /// Emit the language-specific data that __C_specific_handler expects.  This
498 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
499 /// up after faults with __try, __except, and __finally.  The typeinfo values
500 /// are not really RTTI data, but pointers to filter functions that return an
501 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
502 /// blocks and other cleanups, the landing pad label is zero, and the filter
503 /// function is actually a cleanup handler with the same prototype.  A catch-all
504 /// entry is modeled with a null filter function field and a non-zero landing
505 /// pad label.
506 ///
507 /// Possible filter function return values:
508 ///   EXCEPTION_EXECUTE_HANDLER (1):
509 ///     Jump to the landing pad label after cleanups.
510 ///   EXCEPTION_CONTINUE_SEARCH (0):
511 ///     Continue searching this table or continue unwinding.
512 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
513 ///     Resume execution at the trapping PC.
514 ///
515 /// Inferred table structure:
516 ///   struct Table {
517 ///     int NumEntries;
518 ///     struct Entry {
519 ///       imagerel32 LabelStart;
520 ///       imagerel32 LabelEnd;
521 ///       imagerel32 FilterOrFinally;  // One means catch-all.
522 ///       imagerel32 LabelLPad;        // Zero means __finally.
523 ///     } Entries[NumEntries];
524 ///   };
525 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
526   auto &OS = *Asm->OutStreamer;
527   MCContext &Ctx = Asm->OutContext;
528   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
529 
530   bool VerboseAsm = OS.isVerboseAsm();
531   auto AddComment = [&](const Twine &Comment) {
532     if (VerboseAsm)
533       OS.AddComment(Comment);
534   };
535 
536   // Emit a label assignment with the SEH frame offset so we can use it for
537   // llvm.x86.seh.recoverfp.
538   StringRef FLinkageName =
539       GlobalValue::getRealLinkageName(MF->getFunction()->getName());
540   MCSymbol *ParentFrameOffset =
541       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
542   const MCExpr *MCOffset =
543       MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
544   Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
545 
546   // Use the assembler to compute the number of table entries through label
547   // difference and division.
548   MCSymbol *TableBegin =
549       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
550   MCSymbol *TableEnd =
551       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
552   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
553   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
554   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
555   AddComment("Number of call sites");
556   OS.EmitValue(EntryCount, 4);
557 
558   OS.EmitLabel(TableBegin);
559 
560   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
561   // models exceptions from invokes. LLVM also allows arbitrary reordering of
562   // the code, so our tables end up looking a bit different. Rather than
563   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
564   // each range of invokes in the same state, we emit table entries for all
565   // the actions that would be taken in that state. This means our tables are
566   // slightly bigger, which is OK.
567   const MCSymbol *LastStartLabel = nullptr;
568   int LastEHState = -1;
569   // Break out before we enter into a finally funclet.
570   // FIXME: We need to emit separate EH tables for cleanups.
571   MachineFunction::const_iterator End = MF->end();
572   MachineFunction::const_iterator Stop = std::next(MF->begin());
573   while (Stop != End && !Stop->isEHFuncletEntry())
574     ++Stop;
575   for (const auto &StateChange :
576        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
577     // Emit all the actions for the state we just transitioned out of
578     // if it was not the null state
579     if (LastEHState != -1)
580       emitSEHActionsForRange(FuncInfo, LastStartLabel,
581                              StateChange.PreviousEndLabel, LastEHState);
582     LastStartLabel = StateChange.NewStartLabel;
583     LastEHState = StateChange.NewState;
584   }
585 
586   OS.EmitLabel(TableEnd);
587 }
588 
589 void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
590                                           const MCSymbol *BeginLabel,
591                                           const MCSymbol *EndLabel, int State) {
592   auto &OS = *Asm->OutStreamer;
593   MCContext &Ctx = Asm->OutContext;
594 
595   bool VerboseAsm = OS.isVerboseAsm();
596   auto AddComment = [&](const Twine &Comment) {
597     if (VerboseAsm)
598       OS.AddComment(Comment);
599   };
600 
601   assert(BeginLabel && EndLabel);
602   while (State != -1) {
603     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
604     const MCExpr *FilterOrFinally;
605     const MCExpr *ExceptOrNull;
606     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
607     if (UME.IsFinally) {
608       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
609       ExceptOrNull = MCConstantExpr::create(0, Ctx);
610     } else {
611       // For an except, the filter can be 1 (catch-all) or a function
612       // label.
613       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
614                                    : MCConstantExpr::create(1, Ctx);
615       ExceptOrNull = create32bitRef(Handler->getSymbol());
616     }
617 
618     AddComment("LabelStart");
619     OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
620     AddComment("LabelEnd");
621     OS.EmitValue(getLabelPlusOne(EndLabel), 4);
622     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
623                                                              : "CatchAll");
624     OS.EmitValue(FilterOrFinally, 4);
625     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
626     OS.EmitValue(ExceptOrNull, 4);
627 
628     assert(UME.ToState < State && "states should decrease");
629     State = UME.ToState;
630   }
631 }
632 
633 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
634   const Function *F = MF->getFunction();
635   auto &OS = *Asm->OutStreamer;
636   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
637 
638   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
639 
640   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
641   MCSymbol *FuncInfoXData = nullptr;
642   if (shouldEmitPersonality) {
643     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
644     // IPs to state numbers.
645     FuncInfoXData =
646         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
647     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
648   } else {
649     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
650   }
651 
652   int UnwindHelpOffset = 0;
653   if (Asm->MAI->usesWindowsCFI())
654     UnwindHelpOffset =
655         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
656 
657   MCSymbol *UnwindMapXData = nullptr;
658   MCSymbol *TryBlockMapXData = nullptr;
659   MCSymbol *IPToStateXData = nullptr;
660   if (!FuncInfo.CxxUnwindMap.empty())
661     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
662         Twine("$stateUnwindMap$", FuncLinkageName));
663   if (!FuncInfo.TryBlockMap.empty())
664     TryBlockMapXData =
665         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
666   if (!IPToStateTable.empty())
667     IPToStateXData =
668         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
669 
670   bool VerboseAsm = OS.isVerboseAsm();
671   auto AddComment = [&](const Twine &Comment) {
672     if (VerboseAsm)
673       OS.AddComment(Comment);
674   };
675 
676   // FuncInfo {
677   //   uint32_t           MagicNumber
678   //   int32_t            MaxState;
679   //   UnwindMapEntry    *UnwindMap;
680   //   uint32_t           NumTryBlocks;
681   //   TryBlockMapEntry  *TryBlockMap;
682   //   uint32_t           IPMapEntries; // always 0 for x86
683   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
684   //   uint32_t           UnwindHelp;   // non-x86 only
685   //   ESTypeList        *ESTypeList;
686   //   int32_t            EHFlags;
687   // }
688   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
689   // EHFlags & 2 -> ???
690   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
691   OS.EmitValueToAlignment(4);
692   OS.EmitLabel(FuncInfoXData);
693 
694   AddComment("MagicNumber");
695   OS.EmitIntValue(0x19930522, 4);
696 
697   AddComment("MaxState");
698   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
699 
700   AddComment("UnwindMap");
701   OS.EmitValue(create32bitRef(UnwindMapXData), 4);
702 
703   AddComment("NumTryBlocks");
704   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
705 
706   AddComment("TryBlockMap");
707   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
708 
709   AddComment("IPMapEntries");
710   OS.EmitIntValue(IPToStateTable.size(), 4);
711 
712   AddComment("IPToStateXData");
713   OS.EmitValue(create32bitRef(IPToStateXData), 4);
714 
715   if (Asm->MAI->usesWindowsCFI()) {
716     AddComment("UnwindHelp");
717     OS.EmitIntValue(UnwindHelpOffset, 4);
718   }
719 
720   AddComment("ESTypeList");
721   OS.EmitIntValue(0, 4);
722 
723   AddComment("EHFlags");
724   OS.EmitIntValue(1, 4);
725 
726   // UnwindMapEntry {
727   //   int32_t ToState;
728   //   void  (*Action)();
729   // };
730   if (UnwindMapXData) {
731     OS.EmitLabel(UnwindMapXData);
732     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
733       MCSymbol *CleanupSym =
734           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
735       AddComment("ToState");
736       OS.EmitIntValue(UME.ToState, 4);
737 
738       AddComment("Action");
739       OS.EmitValue(create32bitRef(CleanupSym), 4);
740     }
741   }
742 
743   // TryBlockMap {
744   //   int32_t      TryLow;
745   //   int32_t      TryHigh;
746   //   int32_t      CatchHigh;
747   //   int32_t      NumCatches;
748   //   HandlerType *HandlerArray;
749   // };
750   if (TryBlockMapXData) {
751     OS.EmitLabel(TryBlockMapXData);
752     SmallVector<MCSymbol *, 1> HandlerMaps;
753     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
754       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
755 
756       MCSymbol *HandlerMapXData = nullptr;
757       if (!TBME.HandlerArray.empty())
758         HandlerMapXData =
759             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
760                                                   .concat(Twine(I))
761                                                   .concat("$")
762                                                   .concat(FuncLinkageName));
763       HandlerMaps.push_back(HandlerMapXData);
764 
765       // TBMEs should form intervals.
766       assert(0 <= TBME.TryLow && "bad trymap interval");
767       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
768       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
769       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
770              "bad trymap interval");
771 
772       AddComment("TryLow");
773       OS.EmitIntValue(TBME.TryLow, 4);
774 
775       AddComment("TryHigh");
776       OS.EmitIntValue(TBME.TryHigh, 4);
777 
778       AddComment("CatchHigh");
779       OS.EmitIntValue(TBME.CatchHigh, 4);
780 
781       AddComment("NumCatches");
782       OS.EmitIntValue(TBME.HandlerArray.size(), 4);
783 
784       AddComment("HandlerArray");
785       OS.EmitValue(create32bitRef(HandlerMapXData), 4);
786     }
787 
788     // All funclets use the same parent frame offset currently.
789     unsigned ParentFrameOffset = 0;
790     if (shouldEmitPersonality) {
791       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
792       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
793     }
794 
795     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
796       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
797       MCSymbol *HandlerMapXData = HandlerMaps[I];
798       if (!HandlerMapXData)
799         continue;
800       // HandlerType {
801       //   int32_t         Adjectives;
802       //   TypeDescriptor *Type;
803       //   int32_t         CatchObjOffset;
804       //   void          (*Handler)();
805       //   int32_t         ParentFrameOffset; // x64 only
806       // };
807       OS.EmitLabel(HandlerMapXData);
808       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
809         // Get the frame escape label with the offset of the catch object. If
810         // the index is INT_MAX, then there is no catch object, and we should
811         // emit an offset of zero, indicating that no copy will occur.
812         const MCExpr *FrameAllocOffsetRef = nullptr;
813         if (HT.CatchObj.FrameIndex != INT_MAX) {
814           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
815           assert(Offset != 0 && "Illegal offset for catch object!");
816           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
817         } else {
818           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
819         }
820 
821         MCSymbol *HandlerSym =
822             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
823 
824         AddComment("Adjectives");
825         OS.EmitIntValue(HT.Adjectives, 4);
826 
827         AddComment("Type");
828         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
829 
830         AddComment("CatchObjOffset");
831         OS.EmitValue(FrameAllocOffsetRef, 4);
832 
833         AddComment("Handler");
834         OS.EmitValue(create32bitRef(HandlerSym), 4);
835 
836         if (shouldEmitPersonality) {
837           AddComment("ParentFrameOffset");
838           OS.EmitIntValue(ParentFrameOffset, 4);
839         }
840       }
841     }
842   }
843 
844   // IPToStateMapEntry {
845   //   void   *IP;
846   //   int32_t State;
847   // };
848   if (IPToStateXData) {
849     OS.EmitLabel(IPToStateXData);
850     for (auto &IPStatePair : IPToStateTable) {
851       AddComment("IP");
852       OS.EmitValue(IPStatePair.first, 4);
853       AddComment("ToState");
854       OS.EmitIntValue(IPStatePair.second, 4);
855     }
856   }
857 }
858 
859 void WinException::computeIP2StateTable(
860     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
861     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
862 
863   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
864                                        FuncletEnd = MF->begin(),
865                                        End = MF->end();
866        FuncletStart != End; FuncletStart = FuncletEnd) {
867     // Find the end of the funclet
868     while (++FuncletEnd != End) {
869       if (FuncletEnd->isEHFuncletEntry()) {
870         break;
871       }
872     }
873 
874     // Don't emit ip2state entries for cleanup funclets. Any interesting
875     // exceptional actions in cleanups must be handled in a separate IR
876     // function.
877     if (FuncletStart->isCleanupFuncletEntry())
878       continue;
879 
880     MCSymbol *StartLabel;
881     int BaseState;
882     if (FuncletStart == MF->begin()) {
883       BaseState = NullState;
884       StartLabel = Asm->getFunctionBegin();
885     } else {
886       auto *FuncletPad =
887           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
888       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
889       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
890       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
891     }
892     assert(StartLabel && "need local function start label");
893     IPToStateTable.push_back(
894         std::make_pair(create32bitRef(StartLabel), BaseState));
895 
896     for (const auto &StateChange : InvokeStateChangeIterator::range(
897              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
898       // Compute the label to report as the start of this entry; use the EH
899       // start label for the invoke if we have one, otherwise (this is a call
900       // which may unwind to our caller and does not have an EH start label, so)
901       // use the previous end label.
902       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
903       if (!ChangeLabel)
904         ChangeLabel = StateChange.PreviousEndLabel;
905       // Emit an entry indicating that PCs after 'Label' have this EH state.
906       IPToStateTable.push_back(
907           std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
908       // FIXME: assert that NewState is between CatchLow and CatchHigh.
909     }
910   }
911 }
912 
913 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
914                                                  StringRef FLinkageName) {
915   // Outlined helpers called by the EH runtime need to know the offset of the EH
916   // registration in order to recover the parent frame pointer. Now that we know
917   // we've code generated the parent, we can emit the label assignment that
918   // those helpers use to get the offset of the registration node.
919 
920   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
921   // after optimization all the invokes were eliminated. We still need to emit
922   // the parent frame offset label, but it should be garbage and should never be
923   // used.
924   int64_t Offset = 0;
925   int FI = FuncInfo.EHRegNodeFrameIndex;
926   if (FI != INT_MAX) {
927     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
928     unsigned UnusedReg;
929     Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
930   }
931 
932   MCContext &Ctx = Asm->OutContext;
933   MCSymbol *ParentFrameOffset =
934       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
935   Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
936                                    MCConstantExpr::create(Offset, Ctx));
937 }
938 
939 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
940 /// functionally equivalent to the __C_specific_handler table, except it is
941 /// indexed by state number instead of IP.
942 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
943   MCStreamer &OS = *Asm->OutStreamer;
944   const Function *F = MF->getFunction();
945   StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
946 
947   bool VerboseAsm = OS.isVerboseAsm();
948   auto AddComment = [&](const Twine &Comment) {
949     if (VerboseAsm)
950       OS.AddComment(Comment);
951   };
952 
953   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
954   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
955 
956   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
957   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
958   OS.EmitValueToAlignment(4);
959   OS.EmitLabel(LSDALabel);
960 
961   const Function *Per =
962       dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
963   StringRef PerName = Per->getName();
964   int BaseState = -1;
965   if (PerName == "_except_handler4") {
966     // The LSDA for _except_handler4 starts with this struct, followed by the
967     // scope table:
968     //
969     // struct EH4ScopeTable {
970     //   int32_t GSCookieOffset;
971     //   int32_t GSCookieXOROffset;
972     //   int32_t EHCookieOffset;
973     //   int32_t EHCookieXOROffset;
974     //   ScopeTableEntry ScopeRecord[];
975     // };
976     //
977     // Offsets are %ebp relative.
978     //
979     // The GS cookie is present only if the function needs stack protection.
980     // GSCookieOffset = -2 means that GS cookie is not used.
981     //
982     // The EH cookie is always present.
983     //
984     // Check is done the following way:
985     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
986 
987     // Retrieve the Guard Stack slot.
988     int GSCookieOffset = -2;
989     const MachineFrameInfo &MFI = MF->getFrameInfo();
990     if (MFI.hasStackProtectorIndex()) {
991       unsigned UnusedReg;
992       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
993       int SSPIdx = MFI.getStackProtectorIndex();
994       GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
995     }
996 
997     // Retrieve the EH Guard slot.
998     // TODO(etienneb): Get rid of this value and change it for and assertion.
999     int EHCookieOffset = 9999;
1000     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1001       unsigned UnusedReg;
1002       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1003       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1004       EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
1005     }
1006 
1007     AddComment("GSCookieOffset");
1008     OS.EmitIntValue(GSCookieOffset, 4);
1009     AddComment("GSCookieXOROffset");
1010     OS.EmitIntValue(0, 4);
1011     AddComment("EHCookieOffset");
1012     OS.EmitIntValue(EHCookieOffset, 4);
1013     AddComment("EHCookieXOROffset");
1014     OS.EmitIntValue(0, 4);
1015     BaseState = -2;
1016   }
1017 
1018   assert(!FuncInfo.SEHUnwindMap.empty());
1019   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
1020     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1021     const MCSymbol *ExceptOrFinally =
1022         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
1023     // -1 is usually the base state for "unwind to caller", but for
1024     // _except_handler4 it's -2. Do that replacement here if necessary.
1025     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
1026     AddComment("ToState");
1027     OS.EmitIntValue(ToState, 4);
1028     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1029     OS.EmitValue(create32bitRef(UME.Filter), 4);
1030     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1031     OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
1032   }
1033 }
1034 
1035 static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
1036   int Rank = 0;
1037   while (State != -1) {
1038     ++Rank;
1039     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
1040   }
1041   return Rank;
1042 }
1043 
1044 static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1045   int LeftRank = getTryRank(FuncInfo, Left);
1046   int RightRank = getTryRank(FuncInfo, Right);
1047 
1048   while (LeftRank < RightRank) {
1049     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1050     --RightRank;
1051   }
1052 
1053   while (RightRank < LeftRank) {
1054     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1055     --LeftRank;
1056   }
1057 
1058   while (Left != Right) {
1059     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1060     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1061   }
1062 
1063   return Left;
1064 }
1065 
1066 void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1067   // CLR EH "states" are really just IDs that identify handlers/funclets;
1068   // states, handlers, and funclets all have 1:1 mappings between them, and a
1069   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1070   MCStreamer &OS = *Asm->OutStreamer;
1071   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1072   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1073   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1074 
1075   // A ClrClause describes a protected region.
1076   struct ClrClause {
1077     const MCSymbol *StartLabel; // Start of protected region
1078     const MCSymbol *EndLabel;   // End of protected region
1079     int State;          // Index of handler protecting the protected region
1080     int EnclosingState; // Index of funclet enclosing the protected region
1081   };
1082   SmallVector<ClrClause, 8> Clauses;
1083 
1084   // Build a map from handler MBBs to their corresponding states (i.e. their
1085   // indices in the ClrEHUnwindMap).
1086   int NumStates = FuncInfo.ClrEHUnwindMap.size();
1087   assert(NumStates > 0 && "Don't need exception table!");
1088   DenseMap<const MachineBasicBlock *, int> HandlerStates;
1089   for (int State = 0; State < NumStates; ++State) {
1090     MachineBasicBlock *HandlerBlock =
1091         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1092     HandlerStates[HandlerBlock] = State;
1093     // Use this loop through all handlers to verify our assumption (used in
1094     // the MinEnclosingState computation) that enclosing funclets have lower
1095     // state numbers than their enclosed funclets.
1096     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
1097            "ill-formed state numbering");
1098   }
1099   // Map the main function to the NullState.
1100   HandlerStates[&MF->front()] = NullState;
1101 
1102   // Write out a sentinel indicating the end of the standard (Windows) xdata
1103   // and the start of the additional (CLR) info.
1104   OS.EmitIntValue(0xffffffff, 4);
1105   // Write out the number of funclets
1106   OS.EmitIntValue(NumStates, 4);
1107 
1108   // Walk the machine blocks/instrs, computing and emitting a few things:
1109   // 1. Emit a list of the offsets to each handler entry, in lexical order.
1110   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1111   // 3. Compute the list of ClrClauses, in the required order (inner before
1112   //    outer, earlier before later; the order by which a forward scan with
1113   //    early termination will find the innermost enclosing clause covering
1114   //    a given address).
1115   // 4. A map (MinClauseMap) from each handler index to the index of the
1116   //    outermost funclet/function which contains a try clause targeting the
1117   //    key handler.  This will be used to determine IsDuplicate-ness when
1118   //    emitting ClrClauses.  The NullState value is used to indicate that the
1119   //    top-level function contains a try clause targeting the key handler.
1120   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1121   // try regions we entered before entering the PendingState try but which
1122   // we haven't yet exited.
1123   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1124   // EndSymbolMap and MinClauseMap are maps described above.
1125   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1126   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1127 
1128   // Visit the root function and each funclet.
1129   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1130                                        FuncletEnd = MF->begin(),
1131                                        End = MF->end();
1132        FuncletStart != End; FuncletStart = FuncletEnd) {
1133     int FuncletState = HandlerStates[&*FuncletStart];
1134     // Find the end of the funclet
1135     MCSymbol *EndSymbol = FuncEndSym;
1136     while (++FuncletEnd != End) {
1137       if (FuncletEnd->isEHFuncletEntry()) {
1138         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
1139         break;
1140       }
1141     }
1142     // Emit the function/funclet end and, if this is a funclet (and not the
1143     // root function), record it in the EndSymbolMap.
1144     OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1145     if (FuncletState != NullState) {
1146       // Record the end of the handler.
1147       EndSymbolMap[FuncletState] = EndSymbol;
1148     }
1149 
1150     // Walk the state changes in this function/funclet and compute its clauses.
1151     // Funclets always start in the null state.
1152     const MCSymbol *CurrentStartLabel = nullptr;
1153     int CurrentState = NullState;
1154     assert(HandlerStack.empty());
1155     for (const auto &StateChange :
1156          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1157       // Close any try regions we're not still under
1158       int StillPendingState =
1159           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1160       while (CurrentState != StillPendingState) {
1161         assert(CurrentState != NullState &&
1162                "Failed to find still-pending state!");
1163         // Close the pending clause
1164         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1165                            CurrentState, FuncletState});
1166         // Now the next-outer try region is current
1167         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
1168         // Pop the new start label from the handler stack if we've exited all
1169         // inner try regions of the corresponding try region.
1170         if (HandlerStack.back().second == CurrentState)
1171           CurrentStartLabel = HandlerStack.pop_back_val().first;
1172       }
1173 
1174       if (StateChange.NewState != CurrentState) {
1175         // For each clause we're starting, update the MinClauseMap so we can
1176         // know which is the topmost funclet containing a clause targeting
1177         // it.
1178         for (int EnteredState = StateChange.NewState;
1179              EnteredState != CurrentState;
1180              EnteredState =
1181                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
1182           int &MinEnclosingState = MinClauseMap[EnteredState];
1183           if (FuncletState < MinEnclosingState)
1184             MinEnclosingState = FuncletState;
1185         }
1186         // Save the previous current start/label on the stack and update to
1187         // the newly-current start/state.
1188         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1189         CurrentStartLabel = StateChange.NewStartLabel;
1190         CurrentState = StateChange.NewState;
1191       }
1192     }
1193     assert(HandlerStack.empty());
1194   }
1195 
1196   // Now emit the clause info, starting with the number of clauses.
1197   OS.EmitIntValue(Clauses.size(), 4);
1198   for (ClrClause &Clause : Clauses) {
1199     // Emit a CORINFO_EH_CLAUSE :
1200     /*
1201       struct CORINFO_EH_CLAUSE
1202       {
1203           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
1204           DWORD                   TryOffset;
1205           DWORD                   TryLength;     // actually TryEndOffset
1206           DWORD                   HandlerOffset;
1207           DWORD                   HandlerLength; // actually HandlerEndOffset
1208           union
1209           {
1210               DWORD               ClassToken;   // use for catch clauses
1211               DWORD               FilterOffset; // use for filter clauses
1212           };
1213       };
1214 
1215       enum CORINFO_EH_CLAUSE_FLAGS
1216       {
1217           CORINFO_EH_CLAUSE_NONE    = 0,
1218           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
1219           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1220           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
1221       };
1222       typedef enum CorExceptionFlag
1223       {
1224           COR_ILEXCEPTION_CLAUSE_NONE,
1225           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
1226           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1227           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
1228           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1229                                                       // clause was duplicated
1230                                                       // to a funclet which was
1231                                                       // pulled out of line
1232       } CorExceptionFlag;
1233     */
1234     // Add 1 to the start/end of the EH clause; the IP associated with a
1235     // call when the runtime does its scan is the IP of the next instruction
1236     // (the one to which control will return after the call), so we need
1237     // to add 1 to the end of the clause to cover that offset.  We also add
1238     // 1 to the start of the clause to make sure that the ranges reported
1239     // for all clauses are disjoint.  Note that we'll need some additional
1240     // logic when machine traps are supported, since in that case the IP
1241     // that the runtime uses is the offset of the faulting instruction
1242     // itself; if such an instruction immediately follows a call but the
1243     // two belong to different clauses, we'll need to insert a nop between
1244     // them so the runtime can distinguish the point to which the call will
1245     // return from the point at which the fault occurs.
1246 
1247     const MCExpr *ClauseBegin =
1248         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1249     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1250 
1251     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
1252     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1253     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1254     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1255     MCSymbol *EndSym = EndSymbolMap[Clause.State];
1256     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1257 
1258     uint32_t Flags = 0;
1259     switch (Entry.HandlerType) {
1260     case ClrHandlerType::Catch:
1261       // Leaving bits 0-2 clear indicates catch.
1262       break;
1263     case ClrHandlerType::Filter:
1264       Flags |= 1;
1265       break;
1266     case ClrHandlerType::Finally:
1267       Flags |= 2;
1268       break;
1269     case ClrHandlerType::Fault:
1270       Flags |= 4;
1271       break;
1272     }
1273     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1274       // This is a "duplicate" clause; the handler needs to be entered from a
1275       // frame above the one holding the invoke.
1276       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1277       Flags |= 8;
1278     }
1279     OS.EmitIntValue(Flags, 4);
1280 
1281     // Write the clause start/end
1282     OS.EmitValue(ClauseBegin, 4);
1283     OS.EmitValue(ClauseEnd, 4);
1284 
1285     // Write out the handler start/end
1286     OS.EmitValue(HandlerBegin, 4);
1287     OS.EmitValue(HandlerEnd, 4);
1288 
1289     // Write out the type token or filter offset
1290     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1291     OS.EmitIntValue(Entry.TypeToken, 4);
1292   }
1293 }
1294