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