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