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