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