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