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