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