1 //===- CodeGen/AsmPrinter/EHStreamer.cpp - Exception Directive Streamer ---===//
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 exception info into assembly files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "EHStreamer.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineOperand.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCTargetOptions.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdint>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 EHStreamer::EHStreamer(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
40 
41 EHStreamer::~EHStreamer() = default;
42 
43 /// How many leading type ids two landing pads have in common.
44 unsigned EHStreamer::sharedTypeIDs(const LandingPadInfo *L,
45                                    const LandingPadInfo *R) {
46   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
47   unsigned LSize = LIds.size(), RSize = RIds.size();
48   unsigned MinSize = LSize < RSize ? LSize : RSize;
49   unsigned Count = 0;
50 
51   for (; Count != MinSize; ++Count)
52     if (LIds[Count] != RIds[Count])
53       return Count;
54 
55   return Count;
56 }
57 
58 /// Compute the actions table and gather the first action index for each landing
59 /// pad site.
60 void EHStreamer::computeActionsTable(
61     const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
62     SmallVectorImpl<ActionEntry> &Actions,
63     SmallVectorImpl<unsigned> &FirstActions) {
64   // The action table follows the call-site table in the LSDA. The individual
65   // records are of two types:
66   //
67   //   * Catch clause
68   //   * Exception specification
69   //
70   // The two record kinds have the same format, with only small differences.
71   // They are distinguished by the "switch value" field: Catch clauses
72   // (TypeInfos) have strictly positive switch values, and exception
73   // specifications (FilterIds) have strictly negative switch values. Value 0
74   // indicates a catch-all clause.
75   //
76   // Negative type IDs index into FilterIds. Positive type IDs index into
77   // TypeInfos.  The value written for a positive type ID is just the type ID
78   // itself.  For a negative type ID, however, the value written is the
79   // (negative) byte offset of the corresponding FilterIds entry.  The byte
80   // offset is usually equal to the type ID (because the FilterIds entries are
81   // written using a variable width encoding, which outputs one byte per entry
82   // as long as the value written is not too large) but can differ.  This kind
83   // of complication does not occur for positive type IDs because type infos are
84   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
85   // offset corresponding to FilterIds[i].
86 
87   const std::vector<unsigned> &FilterIds = Asm->MF->getFilterIds();
88   SmallVector<int, 16> FilterOffsets;
89   FilterOffsets.reserve(FilterIds.size());
90   int Offset = -1;
91 
92   for (std::vector<unsigned>::const_iterator
93          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
94     FilterOffsets.push_back(Offset);
95     Offset -= getULEB128Size(*I);
96   }
97 
98   FirstActions.reserve(LandingPads.size());
99 
100   int FirstAction = 0;
101   unsigned SizeActions = 0; // Total size of all action entries for a function
102   const LandingPadInfo *PrevLPI = nullptr;
103 
104   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
105          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
106     const LandingPadInfo *LPI = *I;
107     const std::vector<int> &TypeIds = LPI->TypeIds;
108     unsigned NumShared = PrevLPI ? sharedTypeIDs(LPI, PrevLPI) : 0;
109     unsigned SizeSiteActions = 0; // Total size of all entries for a landingpad
110 
111     if (NumShared < TypeIds.size()) {
112       // Size of one action entry (typeid + next action)
113       unsigned SizeActionEntry = 0;
114       unsigned PrevAction = (unsigned)-1;
115 
116       if (NumShared) {
117         unsigned SizePrevIds = PrevLPI->TypeIds.size();
118         assert(Actions.size());
119         PrevAction = Actions.size() - 1;
120         SizeActionEntry = getSLEB128Size(Actions[PrevAction].NextAction) +
121                           getSLEB128Size(Actions[PrevAction].ValueForTypeID);
122 
123         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
124           assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
125           SizeActionEntry -= getSLEB128Size(Actions[PrevAction].ValueForTypeID);
126           SizeActionEntry += -Actions[PrevAction].NextAction;
127           PrevAction = Actions[PrevAction].Previous;
128         }
129       }
130 
131       // Compute the actions.
132       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
133         int TypeID = TypeIds[J];
134         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
135         int ValueForTypeID =
136             isFilterEHSelector(TypeID) ? FilterOffsets[-1 - TypeID] : TypeID;
137         unsigned SizeTypeID = getSLEB128Size(ValueForTypeID);
138 
139         int NextAction = SizeActionEntry ? -(SizeActionEntry + SizeTypeID) : 0;
140         SizeActionEntry = SizeTypeID + getSLEB128Size(NextAction);
141         SizeSiteActions += SizeActionEntry;
142 
143         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
144         Actions.push_back(Action);
145         PrevAction = Actions.size() - 1;
146       }
147 
148       // Record the first action of the landing pad site.
149       FirstAction = SizeActions + SizeSiteActions - SizeActionEntry + 1;
150     } // else identical - re-use previous FirstAction
151 
152     // Information used when creating the call-site table. The action record
153     // field of the call site record is the offset of the first associated
154     // action record, relative to the start of the actions table. This value is
155     // biased by 1 (1 indicating the start of the actions table), and 0
156     // indicates that there are no actions.
157     FirstActions.push_back(FirstAction);
158 
159     // Compute this sites contribution to size.
160     SizeActions += SizeSiteActions;
161 
162     PrevLPI = LPI;
163   }
164 }
165 
166 /// Return `true' if this is a call to a function marked `nounwind'. Return
167 /// `false' otherwise.
168 bool EHStreamer::callToNoUnwindFunction(const MachineInstr *MI) {
169   assert(MI->isCall() && "This should be a call instruction!");
170 
171   bool MarkedNoUnwind = false;
172   bool SawFunc = false;
173 
174   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
175     const MachineOperand &MO = MI->getOperand(I);
176 
177     if (!MO.isGlobal()) continue;
178 
179     const Function *F = dyn_cast<Function>(MO.getGlobal());
180     if (!F) continue;
181 
182     if (SawFunc) {
183       // Be conservative. If we have more than one function operand for this
184       // call, then we can't make the assumption that it's the callee and
185       // not a parameter to the call.
186       //
187       // FIXME: Determine if there's a way to say that `F' is the callee or
188       // parameter.
189       MarkedNoUnwind = false;
190       break;
191     }
192 
193     MarkedNoUnwind = F->doesNotThrow();
194     SawFunc = true;
195   }
196 
197   return MarkedNoUnwind;
198 }
199 
200 void EHStreamer::computePadMap(
201     const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
202     RangeMapType &PadMap) {
203   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
204   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
205   // try-ranges for them need be deduced so we can put them in the LSDA.
206   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
207     const LandingPadInfo *LandingPad = LandingPads[i];
208     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
209       MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
210       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
211       PadRange P = { i, j };
212       PadMap[BeginLabel] = P;
213     }
214   }
215 }
216 
217 /// Compute the call-site table.  The entry for an invoke has a try-range
218 /// containing the call, a non-zero landing pad, and an appropriate action.  The
219 /// entry for an ordinary call has a try-range containing the call and zero for
220 /// the landing pad and the action.  Calls marked 'nounwind' have no entry and
221 /// must not be contained in the try-range of any entry - they form gaps in the
222 /// table.  Entries must be ordered by try-range address.
223 void EHStreamer::
224 computeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
225                      const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
226                      const SmallVectorImpl<unsigned> &FirstActions) {
227   RangeMapType PadMap;
228   computePadMap(LandingPads, PadMap);
229 
230   // The end label of the previous invoke or nounwind try-range.
231   MCSymbol *LastLabel = Asm->getFunctionBegin();
232 
233   // Whether there is a potentially throwing instruction (currently this means
234   // an ordinary call) between the end of the previous try-range and now.
235   bool SawPotentiallyThrowing = false;
236 
237   // Whether the last CallSite entry was for an invoke.
238   bool PreviousIsInvoke = false;
239 
240   bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
241 
242   // Visit all instructions in order of address.
243   for (const auto &MBB : *Asm->MF) {
244     for (const auto &MI : MBB) {
245       if (!MI.isEHLabel()) {
246         if (MI.isCall())
247           SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
248         continue;
249       }
250 
251       // End of the previous try-range?
252       MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
253       if (BeginLabel == LastLabel)
254         SawPotentiallyThrowing = false;
255 
256       // Beginning of a new try-range?
257       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
258       if (L == PadMap.end())
259         // Nope, it was just some random label.
260         continue;
261 
262       const PadRange &P = L->second;
263       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
264       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
265              "Inconsistent landing pad map!");
266 
267       // For Dwarf exception handling (SjLj handling doesn't use this). If some
268       // instruction between the previous try-range and this one may throw,
269       // create a call-site entry with no landing pad for the region between the
270       // try-ranges.
271       if (SawPotentiallyThrowing && Asm->MAI->usesCFIForEH()) {
272         CallSites.push_back({LastLabel, BeginLabel, nullptr, 0});
273         PreviousIsInvoke = false;
274       }
275 
276       LastLabel = LandingPad->EndLabels[P.RangeIndex];
277       assert(BeginLabel && LastLabel && "Invalid landing pad!");
278 
279       if (!LandingPad->LandingPadLabel) {
280         // Create a gap.
281         PreviousIsInvoke = false;
282       } else {
283         // This try-range is for an invoke.
284         CallSiteEntry Site = {
285           BeginLabel,
286           LastLabel,
287           LandingPad,
288           FirstActions[P.PadIndex]
289         };
290 
291         // Try to merge with the previous call-site. SJLJ doesn't do this
292         if (PreviousIsInvoke && !IsSJLJ) {
293           CallSiteEntry &Prev = CallSites.back();
294           if (Site.LPad == Prev.LPad && Site.Action == Prev.Action) {
295             // Extend the range of the previous entry.
296             Prev.EndLabel = Site.EndLabel;
297             continue;
298           }
299         }
300 
301         // Otherwise, create a new call-site.
302         if (!IsSJLJ)
303           CallSites.push_back(Site);
304         else {
305           // SjLj EH must maintain the call sites in the order assigned
306           // to them by the SjLjPrepare pass.
307           unsigned SiteNo = Asm->MF->getCallSiteBeginLabel(BeginLabel);
308           if (CallSites.size() < SiteNo)
309             CallSites.resize(SiteNo);
310           CallSites[SiteNo - 1] = Site;
311         }
312         PreviousIsInvoke = true;
313       }
314     }
315   }
316 
317   // If some instruction between the previous try-range and the end of the
318   // function may throw, create a call-site entry with no landing pad for the
319   // region following the try-range.
320   if (SawPotentiallyThrowing && !IsSJLJ)
321     CallSites.push_back({LastLabel, Asm->getFunctionEnd(), nullptr, 0});
322 }
323 
324 /// Emit landing pads and actions.
325 ///
326 /// The general organization of the table is complex, but the basic concepts are
327 /// easy.  First there is a header which describes the location and organization
328 /// of the three components that follow.
329 ///
330 ///  1. The landing pad site information describes the range of code covered by
331 ///     the try.  In our case it's an accumulation of the ranges covered by the
332 ///     invokes in the try.  There is also a reference to the landing pad that
333 ///     handles the exception once processed.  Finally an index into the actions
334 ///     table.
335 ///  2. The action table, in our case, is composed of pairs of type IDs and next
336 ///     action offset.  Starting with the action index from the landing pad
337 ///     site, each type ID is checked for a match to the current exception.  If
338 ///     it matches then the exception and type id are passed on to the landing
339 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
340 ///     with a next action of zero.  If no type id is found then the frame is
341 ///     unwound and handling continues.
342 ///  3. Type ID table contains references to all the C++ typeinfo for all
343 ///     catches in the function.  This tables is reverse indexed base 1.
344 ///
345 /// Returns the starting symbol of an exception table.
346 MCSymbol *EHStreamer::emitExceptionTable() {
347   const MachineFunction *MF = Asm->MF;
348   const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
349   const std::vector<unsigned> &FilterIds = MF->getFilterIds();
350   const std::vector<LandingPadInfo> &PadInfos = MF->getLandingPads();
351 
352   // Sort the landing pads in order of their type ids.  This is used to fold
353   // duplicate actions.
354   SmallVector<const LandingPadInfo *, 64> LandingPads;
355   LandingPads.reserve(PadInfos.size());
356 
357   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
358     LandingPads.push_back(&PadInfos[i]);
359 
360   // Order landing pads lexicographically by type id.
361   llvm::sort(LandingPads, [](const LandingPadInfo *L, const LandingPadInfo *R) {
362     return L->TypeIds < R->TypeIds;
363   });
364 
365   // Compute the actions table and gather the first action index for each
366   // landing pad site.
367   SmallVector<ActionEntry, 32> Actions;
368   SmallVector<unsigned, 64> FirstActions;
369   computeActionsTable(LandingPads, Actions, FirstActions);
370 
371   // Compute the call-site table.
372   SmallVector<CallSiteEntry, 64> CallSites;
373   computeCallSiteTable(CallSites, LandingPads, FirstActions);
374 
375   bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
376   bool IsWasm = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Wasm;
377   unsigned CallSiteEncoding =
378       IsSJLJ ? static_cast<unsigned>(dwarf::DW_EH_PE_udata4) :
379                Asm->getObjFileLowering().getCallSiteEncoding();
380   bool HaveTTData = !TypeInfos.empty() || !FilterIds.empty();
381 
382   // Type infos.
383   MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
384   unsigned TTypeEncoding;
385 
386   if (!HaveTTData) {
387     // If there is no TypeInfo, then we just explicitly say that we're omitting
388     // that bit.
389     TTypeEncoding = dwarf::DW_EH_PE_omit;
390   } else {
391     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
392     // pick a type encoding for them.  We're about to emit a list of pointers to
393     // typeinfo objects at the end of the LSDA.  However, unless we're in static
394     // mode, this reference will require a relocation by the dynamic linker.
395     //
396     // Because of this, we have a couple of options:
397     //
398     //   1) If we are in -static mode, we can always use an absolute reference
399     //      from the LSDA, because the static linker will resolve it.
400     //
401     //   2) Otherwise, if the LSDA section is writable, we can output the direct
402     //      reference to the typeinfo and allow the dynamic linker to relocate
403     //      it.  Since it is in a writable section, the dynamic linker won't
404     //      have a problem.
405     //
406     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
407     //      we need to use some form of indirection.  For example, on Darwin,
408     //      we can output a statically-relocatable reference to a dyld stub. The
409     //      offset to the stub is constant, but the contents are in a section
410     //      that is updated by the dynamic linker.  This is easy enough, but we
411     //      need to tell the personality function of the unwinder to indirect
412     //      through the dyld stub.
413     //
414     // FIXME: When (3) is actually implemented, we'll have to emit the stubs
415     // somewhere.  This predicate should be moved to a shared location that is
416     // in target-independent code.
417     //
418     TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
419   }
420 
421   // Begin the exception table.
422   // Sometimes we want not to emit the data into separate section (e.g. ARM
423   // EHABI). In this case LSDASection will be NULL.
424   if (LSDASection)
425     Asm->OutStreamer->SwitchSection(LSDASection);
426   Asm->emitAlignment(Align(4));
427 
428   // Emit the LSDA.
429   MCSymbol *GCCETSym =
430     Asm->OutContext.getOrCreateSymbol(Twine("GCC_except_table")+
431                                       Twine(Asm->getFunctionNumber()));
432   Asm->OutStreamer->emitLabel(GCCETSym);
433   Asm->OutStreamer->emitLabel(Asm->getCurExceptionSym());
434 
435   // Emit the LSDA header.
436   Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
437   Asm->emitEncodingByte(TTypeEncoding, "@TType");
438 
439   MCSymbol *TTBaseLabel = nullptr;
440   if (HaveTTData) {
441     // N.B.: There is a dependency loop between the size of the TTBase uleb128
442     // here and the amount of padding before the aligned type table. The
443     // assembler must sometimes pad this uleb128 or insert extra padding before
444     // the type table. See PR35809 or GNU as bug 4029.
445     MCSymbol *TTBaseRefLabel = Asm->createTempSymbol("ttbaseref");
446     TTBaseLabel = Asm->createTempSymbol("ttbase");
447     Asm->emitLabelDifferenceAsULEB128(TTBaseLabel, TTBaseRefLabel);
448     Asm->OutStreamer->emitLabel(TTBaseRefLabel);
449   }
450 
451   bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
452 
453   // Emit the landing pad call site table.
454   MCSymbol *CstBeginLabel = Asm->createTempSymbol("cst_begin");
455   MCSymbol *CstEndLabel = Asm->createTempSymbol("cst_end");
456   Asm->emitEncodingByte(CallSiteEncoding, "Call site");
457   Asm->emitLabelDifferenceAsULEB128(CstEndLabel, CstBeginLabel);
458   Asm->OutStreamer->emitLabel(CstBeginLabel);
459 
460   // SjLj / Wasm Exception handling
461   if (IsSJLJ || IsWasm) {
462     unsigned idx = 0;
463     for (SmallVectorImpl<CallSiteEntry>::const_iterator
464          I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
465       const CallSiteEntry &S = *I;
466 
467       // Index of the call site entry.
468       if (VerboseAsm) {
469         Asm->OutStreamer->AddComment(">> Call Site " + Twine(idx) + " <<");
470         Asm->OutStreamer->AddComment("  On exception at call site "+Twine(idx));
471       }
472       Asm->emitULEB128(idx);
473 
474       // Offset of the first associated action record, relative to the start of
475       // the action table. This value is biased by 1 (1 indicates the start of
476       // the action table), and 0 indicates that there are no actions.
477       if (VerboseAsm) {
478         if (S.Action == 0)
479           Asm->OutStreamer->AddComment("  Action: cleanup");
480         else
481           Asm->OutStreamer->AddComment("  Action: " +
482                                        Twine((S.Action - 1) / 2 + 1));
483       }
484       Asm->emitULEB128(S.Action);
485     }
486   } else {
487     // Itanium LSDA exception handling
488 
489     // The call-site table is a list of all call sites that may throw an
490     // exception (including C++ 'throw' statements) in the procedure
491     // fragment. It immediately follows the LSDA header. Each entry indicates,
492     // for a given call, the first corresponding action record and corresponding
493     // landing pad.
494     //
495     // The table begins with the number of bytes, stored as an LEB128
496     // compressed, unsigned integer. The records immediately follow the record
497     // count. They are sorted in increasing call-site address. Each record
498     // indicates:
499     //
500     //   * The position of the call-site.
501     //   * The position of the landing pad.
502     //   * The first action record for that call site.
503     //
504     // A missing entry in the call-site table indicates that a call is not
505     // supposed to throw.
506 
507     unsigned Entry = 0;
508     for (SmallVectorImpl<CallSiteEntry>::const_iterator
509          I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
510       const CallSiteEntry &S = *I;
511 
512       MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
513 
514       // Offset of the call site relative to the start of the procedure.
515       if (VerboseAsm)
516         Asm->OutStreamer->AddComment(">> Call Site " + Twine(++Entry) + " <<");
517       Asm->emitCallSiteOffset(S.BeginLabel, EHFuncBeginSym, CallSiteEncoding);
518       if (VerboseAsm)
519         Asm->OutStreamer->AddComment(Twine("  Call between ") +
520                                      S.BeginLabel->getName() + " and " +
521                                      S.EndLabel->getName());
522       Asm->emitCallSiteOffset(S.EndLabel, S.BeginLabel, CallSiteEncoding);
523 
524       // Offset of the landing pad relative to the start of the procedure.
525       if (!S.LPad) {
526         if (VerboseAsm)
527           Asm->OutStreamer->AddComment("    has no landing pad");
528         Asm->emitCallSiteValue(0, CallSiteEncoding);
529       } else {
530         if (VerboseAsm)
531           Asm->OutStreamer->AddComment(Twine("    jumps to ") +
532                                        S.LPad->LandingPadLabel->getName());
533         Asm->emitCallSiteOffset(S.LPad->LandingPadLabel, EHFuncBeginSym,
534                                 CallSiteEncoding);
535       }
536 
537       // Offset of the first associated action record, relative to the start of
538       // the action table. This value is biased by 1 (1 indicates the start of
539       // the action table), and 0 indicates that there are no actions.
540       if (VerboseAsm) {
541         if (S.Action == 0)
542           Asm->OutStreamer->AddComment("  On action: cleanup");
543         else
544           Asm->OutStreamer->AddComment("  On action: " +
545                                        Twine((S.Action - 1) / 2 + 1));
546       }
547       Asm->emitULEB128(S.Action);
548     }
549   }
550   Asm->OutStreamer->emitLabel(CstEndLabel);
551 
552   // Emit the Action Table.
553   int Entry = 0;
554   for (SmallVectorImpl<ActionEntry>::const_iterator
555          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
556     const ActionEntry &Action = *I;
557 
558     if (VerboseAsm) {
559       // Emit comments that decode the action table.
560       Asm->OutStreamer->AddComment(">> Action Record " + Twine(++Entry) + " <<");
561     }
562 
563     // Type Filter
564     //
565     //   Used by the runtime to match the type of the thrown exception to the
566     //   type of the catch clauses or the types in the exception specification.
567     if (VerboseAsm) {
568       if (Action.ValueForTypeID > 0)
569         Asm->OutStreamer->AddComment("  Catch TypeInfo " +
570                                      Twine(Action.ValueForTypeID));
571       else if (Action.ValueForTypeID < 0)
572         Asm->OutStreamer->AddComment("  Filter TypeInfo " +
573                                      Twine(Action.ValueForTypeID));
574       else
575         Asm->OutStreamer->AddComment("  Cleanup");
576     }
577     Asm->emitSLEB128(Action.ValueForTypeID);
578 
579     // Action Record
580     if (VerboseAsm) {
581       if (Action.Previous == unsigned(-1)) {
582         Asm->OutStreamer->AddComment("  No further actions");
583       } else {
584         Asm->OutStreamer->AddComment("  Continue to action " +
585                                      Twine(Action.Previous + 1));
586       }
587     }
588     Asm->emitSLEB128(Action.NextAction);
589   }
590 
591   if (HaveTTData) {
592     Asm->emitAlignment(Align(4));
593     emitTypeInfos(TTypeEncoding, TTBaseLabel);
594   }
595 
596   Asm->emitAlignment(Align(4));
597   return GCCETSym;
598 }
599 
600 void EHStreamer::emitTypeInfos(unsigned TTypeEncoding, MCSymbol *TTBaseLabel) {
601   const MachineFunction *MF = Asm->MF;
602   const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
603   const std::vector<unsigned> &FilterIds = MF->getFilterIds();
604 
605   bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
606 
607   int Entry = 0;
608   // Emit the Catch TypeInfos.
609   if (VerboseAsm && !TypeInfos.empty()) {
610     Asm->OutStreamer->AddComment(">> Catch TypeInfos <<");
611     Asm->OutStreamer->AddBlankLine();
612     Entry = TypeInfos.size();
613   }
614 
615   for (const GlobalValue *GV : make_range(TypeInfos.rbegin(),
616                                           TypeInfos.rend())) {
617     if (VerboseAsm)
618       Asm->OutStreamer->AddComment("TypeInfo " + Twine(Entry--));
619     Asm->emitTTypeReference(GV, TTypeEncoding);
620   }
621 
622   Asm->OutStreamer->emitLabel(TTBaseLabel);
623 
624   // Emit the Exception Specifications.
625   if (VerboseAsm && !FilterIds.empty()) {
626     Asm->OutStreamer->AddComment(">> Filter TypeInfos <<");
627     Asm->OutStreamer->AddBlankLine();
628     Entry = 0;
629   }
630   for (std::vector<unsigned>::const_iterator
631          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
632     unsigned TypeID = *I;
633     if (VerboseAsm) {
634       --Entry;
635       if (isFilterEHSelector(TypeID))
636         Asm->OutStreamer->AddComment("FilterInfo " + Twine(Entry));
637     }
638 
639     Asm->emitULEB128(TypeID);
640   }
641 }
642