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