• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Module.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Target/Mangler.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/Twine.h"
38 using namespace llvm;
39 
DwarfException(AsmPrinter * A)40 DwarfException::DwarfException(AsmPrinter *A)
41   : Asm(A), MMI(Asm->MMI) {}
42 
~DwarfException()43 DwarfException::~DwarfException() {}
44 
45 /// SharedTypeIds - How many leading type ids two landing pads have in common.
SharedTypeIds(const LandingPadInfo * L,const LandingPadInfo * R)46 unsigned 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.
PadLT(const LandingPadInfo * L,const LandingPadInfo * R)61 bool 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.
75 unsigned DwarfException::
ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo * > & LandingPads,SmallVectorImpl<ActionEntry> & Actions,SmallVectorImpl<unsigned> & FirstActions)76 ComputeActionsTable(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.
CallToNoUnwindFunction(const MachineInstr * MI)186 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
187   assert(MI->getDesc().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.
225 void DwarfException::
ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> & CallSites,const RangeMapType & PadMap,const SmallVectorImpl<const LandingPadInfo * > & LandingPads,const SmallVectorImpl<unsigned> & FirstActions)226 ComputeCallSiteTable(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->getDesc().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.
EmitExceptionTable()347 void 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->getTargetData().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(Twine(">> Call Site ") +
533                                     llvm::utostr(idx) + " <<");
534         Asm->OutStreamer.AddComment(Twine("  On exception at call site ") +
535                                     llvm::utostr(idx));
536       }
537       Asm->EmitULEB128(idx);
538 
539       // Offset of the first associated action record, relative to the start of
540       // the action table. This value is biased by 1 (1 indicates the start of
541       // the action table), and 0 indicates that there are no actions.
542       if (VerboseAsm) {
543         if (S.Action == 0)
544           Asm->OutStreamer.AddComment("  Action: cleanup");
545         else
546           Asm->OutStreamer.AddComment(Twine("  Action: ") +
547                                       llvm::utostr((S.Action - 1) / 2 + 1));
548       }
549       Asm->EmitULEB128(S.Action);
550     }
551   } else {
552     // DWARF Exception handling
553     assert(Asm->MAI->isExceptionHandlingDwarf());
554 
555     // The call-site table is a list of all call sites that may throw an
556     // exception (including C++ 'throw' statements) in the procedure
557     // fragment. It immediately follows the LSDA header. Each entry indicates,
558     // for a given call, the first corresponding action record and corresponding
559     // landing pad.
560     //
561     // The table begins with the number of bytes, stored as an LEB128
562     // compressed, unsigned integer. The records immediately follow the record
563     // count. They are sorted in increasing call-site address. Each record
564     // indicates:
565     //
566     //   * The position of the call-site.
567     //   * The position of the landing pad.
568     //   * The first action record for that call site.
569     //
570     // A missing entry in the call-site table indicates that a call is not
571     // supposed to throw.
572 
573     // Emit the landing pad call site table.
574     Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
575 
576     // Add extra padding if it wasn't added to the TType base offset.
577     Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
578 
579     unsigned Entry = 0;
580     for (SmallVectorImpl<CallSiteEntry>::const_iterator
581          I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
582       const CallSiteEntry &S = *I;
583 
584       MCSymbol *EHFuncBeginSym =
585         Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber());
586 
587       MCSymbol *BeginLabel = S.BeginLabel;
588       if (BeginLabel == 0)
589         BeginLabel = EHFuncBeginSym;
590       MCSymbol *EndLabel = S.EndLabel;
591       if (EndLabel == 0)
592         EndLabel = Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber());
593 
594 
595       // Offset of the call site relative to the previous call site, counted in
596       // number of 16-byte bundles. The first call site is counted relative to
597       // the start of the procedure fragment.
598       if (VerboseAsm)
599         Asm->OutStreamer.AddComment(Twine(">> Call Site ") +
600                                     llvm::utostr(++Entry) + " <<");
601       Asm->EmitLabelDifference(BeginLabel, EHFuncBeginSym, 4);
602       if (VerboseAsm)
603         Asm->OutStreamer.AddComment(Twine("  Call between ") +
604                                     BeginLabel->getName() + " and " +
605                                     EndLabel->getName());
606       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
607 
608       // Offset of the landing pad, counted in 16-byte bundles relative to the
609       // @LPStart address.
610       if (!S.PadLabel) {
611         if (VerboseAsm)
612           Asm->OutStreamer.AddComment("    has no landing pad");
613         Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
614       } else {
615         if (VerboseAsm)
616           Asm->OutStreamer.AddComment(Twine("    jumps to ") +
617                                       S.PadLabel->getName());
618         Asm->EmitLabelDifference(S.PadLabel, EHFuncBeginSym, 4);
619       }
620 
621       // Offset of the first associated action record, relative to the start of
622       // the action table. This value is biased by 1 (1 indicates the start of
623       // the action table), and 0 indicates that there are no actions.
624       if (VerboseAsm) {
625         if (S.Action == 0)
626           Asm->OutStreamer.AddComment("  On action: cleanup");
627         else
628           Asm->OutStreamer.AddComment(Twine("  On action: ") +
629                                       llvm::utostr((S.Action - 1) / 2 + 1));
630       }
631       Asm->EmitULEB128(S.Action);
632     }
633   }
634 
635   // Emit the Action Table.
636   int Entry = 0;
637   for (SmallVectorImpl<ActionEntry>::const_iterator
638          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
639     const ActionEntry &Action = *I;
640 
641     if (VerboseAsm) {
642       // Emit comments that decode the action table.
643       Asm->OutStreamer.AddComment(Twine(">> Action Record ") +
644                                   llvm::utostr(++Entry) + " <<");
645     }
646 
647     // Type Filter
648     //
649     //   Used by the runtime to match the type of the thrown exception to the
650     //   type of the catch clauses or the types in the exception specification.
651     if (VerboseAsm) {
652       if (Action.ValueForTypeID > 0)
653         Asm->OutStreamer.AddComment(Twine("  Catch TypeInfo ") +
654                                     llvm::itostr(Action.ValueForTypeID));
655       else if (Action.ValueForTypeID < 0)
656         Asm->OutStreamer.AddComment(Twine("  Filter TypeInfo ") +
657                                     llvm::itostr(Action.ValueForTypeID));
658       else
659         Asm->OutStreamer.AddComment("  Cleanup");
660     }
661     Asm->EmitSLEB128(Action.ValueForTypeID);
662 
663     // Action Record
664     //
665     //   Self-relative signed displacement in bytes of the next action record,
666     //   or 0 if there is no next action record.
667     if (VerboseAsm) {
668       if (Action.NextAction == 0) {
669         Asm->OutStreamer.AddComment("  No further actions");
670       } else {
671         unsigned NextAction = Entry + (Action.NextAction + 1) / 2;
672         Asm->OutStreamer.AddComment(Twine("  Continue to action ") +
673                                     llvm::utostr(NextAction));
674       }
675     }
676     Asm->EmitSLEB128(Action.NextAction);
677   }
678 
679   // Emit the Catch TypeInfos.
680   if (VerboseAsm && !TypeInfos.empty()) {
681     Asm->OutStreamer.AddComment(">> Catch TypeInfos <<");
682     Asm->OutStreamer.AddBlankLine();
683     Entry = TypeInfos.size();
684   }
685 
686   for (std::vector<const GlobalVariable *>::const_reverse_iterator
687          I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
688     const GlobalVariable *GV = *I;
689     if (VerboseAsm)
690       Asm->OutStreamer.AddComment(Twine("TypeInfo ") + llvm::utostr(Entry--));
691     if (GV)
692       Asm->EmitReference(GV, TTypeEncoding);
693     else
694       Asm->OutStreamer.EmitIntValue(0,Asm->GetSizeOfEncodedValue(TTypeEncoding),
695                                     0);
696   }
697 
698   // Emit the Exception Specifications.
699   if (VerboseAsm && !FilterIds.empty()) {
700     Asm->OutStreamer.AddComment(">> Filter TypeInfos <<");
701     Asm->OutStreamer.AddBlankLine();
702     Entry = 0;
703   }
704   for (std::vector<unsigned>::const_iterator
705          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
706     unsigned TypeID = *I;
707     if (VerboseAsm) {
708       --Entry;
709       if (TypeID != 0)
710         Asm->OutStreamer.AddComment(Twine("FilterInfo ") + llvm::itostr(Entry));
711     }
712 
713     Asm->EmitULEB128(TypeID);
714   }
715 
716   Asm->EmitAlignment(2);
717 }
718 
719 /// EndModule - Emit all exception information that should come after the
720 /// content.
EndModule()721 void DwarfException::EndModule() {
722   assert(0 && "Should be implemented");
723 }
724 
725 /// BeginFunction - Gather pre-function exception information. Assumes it's
726 /// being emitted immediately after the function entry point.
BeginFunction(const MachineFunction * MF)727 void DwarfException::BeginFunction(const MachineFunction *MF) {
728   assert(0 && "Should be implemented");
729 }
730 
731 /// EndFunction - Gather and emit post-function exception information.
732 ///
EndFunction()733 void DwarfException::EndFunction() {
734   assert(0 && "Should be implemented");
735 }
736