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