these two pieces of code are the same because we always
[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/Module.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineLocation.h"
19 #include "llvm/Support/Dwarf.h"
20 #include "llvm/Support/Timer.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetAsmInfo.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace llvm;
29
30 static TimerGroup &getDwarfTimerGroup() {
31   static TimerGroup DwarfTimerGroup("Dwarf Exception");
32   return DwarfTimerGroup;
33 }
34
35 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
36                                const TargetAsmInfo *T)
37   : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
38     shouldEmitTableModule(false), shouldEmitMovesModule(false),
39     ExceptionTimer(0) {
40   if (TimePassesIsEnabled) 
41     ExceptionTimer = new Timer("Dwarf Exception Writer",
42                                getDwarfTimerGroup());
43 }
44
45 DwarfException::~DwarfException() {
46   delete ExceptionTimer;
47 }
48
49 void DwarfException::EmitCommonEHFrame(const Function *Personality,
50                                        unsigned Index) {
51   // Size and sign of stack growth.
52   int stackGrowth =
53     Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
54     TargetFrameInfo::StackGrowsUp ?
55     TD->getPointerSize() : -TD->getPointerSize();
56
57   // Begin eh frame section.
58   Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
59
60   if (TAI->is_EHSymbolPrivate())
61     O << TAI->getPrivateGlobalPrefix();
62
63   O << "EH_frame" << Index << ":\n";
64   EmitLabel("section_eh_frame", Index);
65
66   // Define base labels.
67   EmitLabel("eh_frame_common", Index);
68
69   // Define the eh frame length.
70   EmitDifference("eh_frame_common_end", Index,
71                  "eh_frame_common_begin", Index, true);
72   Asm->EOL("Length of Common Information Entry");
73
74   // EH frame header.
75   EmitLabel("eh_frame_common_begin", Index);
76   Asm->EmitInt32((int)0);
77   Asm->EOL("CIE Identifier Tag");
78   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
79   Asm->EOL("CIE Version");
80
81   // The personality presence indicates that language specific information will
82   // show up in the eh frame.
83   Asm->EmitString(Personality ? "zPLR" : "zR");
84   Asm->EOL("CIE Augmentation");
85
86   // Round out reader.
87   Asm->EmitULEB128Bytes(1);
88   Asm->EOL("CIE Code Alignment Factor");
89   Asm->EmitSLEB128Bytes(stackGrowth);
90   Asm->EOL("CIE Data Alignment Factor");
91   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
92   Asm->EOL("CIE Return Address Column");
93
94   // If there is a personality, we need to indicate the functions location.
95   if (Personality) {
96     Asm->EmitULEB128Bytes(7);
97     Asm->EOL("Augmentation Size");
98
99     if (TAI->getNeedsIndirectEncoding()) {
100       Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
101                     dwarf::DW_EH_PE_indirect);
102       Asm->EOL("Personality (pcrel sdata4 indirect)");
103     } else {
104       Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
105       Asm->EOL("Personality (pcrel sdata4)");
106     }
107
108     PrintRelDirective(true);
109     O << TAI->getPersonalityPrefix();
110     Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
111     O << TAI->getPersonalitySuffix();
112     if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
113       O << "-" << TAI->getPCSymbol();
114     Asm->EOL("Personality");
115
116     Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
117     Asm->EOL("LSDA Encoding (pcrel sdata4)");
118
119     Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
120     Asm->EOL("FDE Encoding (pcrel sdata4)");
121   } else {
122     Asm->EmitULEB128Bytes(1);
123     Asm->EOL("Augmentation Size");
124
125     Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
126     Asm->EOL("FDE Encoding (pcrel sdata4)");
127   }
128
129   // Indicate locations of general callee saved registers in frame.
130   std::vector<MachineMove> Moves;
131   RI->getInitialFrameState(Moves);
132   EmitFrameMoves(NULL, 0, Moves, true);
133
134   // On Darwin the linker honors the alignment of eh_frame, which means it must
135   // be 8-byte on 64-bit targets to match what gcc does.  Otherwise you get
136   // holes which confuse readers of eh_frame.
137   Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
138                      0, 0, false);
139   EmitLabel("eh_frame_common_end", Index);
140
141   Asm->EOL();
142 }
143
144 /// EmitEHFrame - Emit function exception frame information.
145 ///
146 void DwarfException::EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
147   assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() && 
148          "Should not emit 'available externally' functions at all");
149
150   Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
151   Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
152
153   // Externally visible entry into the functions eh frame info. If the
154   // corresponding function is static, this should not be externally visible.
155   if (linkage != Function::InternalLinkage &&
156       linkage != Function::PrivateLinkage) {
157     if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
158       O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
159   }
160
161   // If corresponding function is weak definition, this should be too.
162   if ((linkage == Function::WeakAnyLinkage ||
163        linkage == Function::WeakODRLinkage ||
164        linkage == Function::LinkOnceAnyLinkage ||
165        linkage == Function::LinkOnceODRLinkage) &&
166       TAI->getWeakDefDirective())
167     O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
168
169   // If there are no calls then you can't unwind.  This may mean we can omit the
170   // EH Frame, but some environments do not handle weak absolute symbols. If
171   // UnwindTablesMandatory is set we cannot do this optimization; the unwind
172   // info is to be available for non-EH uses.
173   if (!EHFrameInfo.hasCalls &&
174       !UnwindTablesMandatory &&
175       ((linkage != Function::WeakAnyLinkage &&
176         linkage != Function::WeakODRLinkage &&
177         linkage != Function::LinkOnceAnyLinkage &&
178         linkage != Function::LinkOnceODRLinkage) ||
179        !TAI->getWeakDefDirective() ||
180        TAI->getSupportsWeakOmittedEHFrame())) {
181     O << EHFrameInfo.FnName << " = 0\n";
182     // This name has no connection to the function, so it might get
183     // dead-stripped when the function is not, erroneously.  Prohibit
184     // dead-stripping unconditionally.
185     if (const char *UsedDirective = TAI->getUsedDirective())
186       O << UsedDirective << EHFrameInfo.FnName << "\n\n";
187   } else {
188     O << EHFrameInfo.FnName << ":\n";
189
190     // EH frame header.
191     EmitDifference("eh_frame_end", EHFrameInfo.Number,
192                    "eh_frame_begin", EHFrameInfo.Number, true);
193     Asm->EOL("Length of Frame Information Entry");
194
195     EmitLabel("eh_frame_begin", EHFrameInfo.Number);
196
197     EmitSectionOffset("eh_frame_begin", "eh_frame_common",
198                       EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
199                       true, true, false);
200
201     Asm->EOL("FDE CIE offset");
202
203     EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
204     Asm->EOL("FDE initial location");
205     EmitDifference("eh_func_end", EHFrameInfo.Number,
206                    "eh_func_begin", EHFrameInfo.Number, true);
207     Asm->EOL("FDE address range");
208
209     // If there is a personality and landing pads then point to the language
210     // specific data area in the exception table.
211     if (EHFrameInfo.PersonalityIndex) {
212       Asm->EmitULEB128Bytes(4);
213       Asm->EOL("Augmentation size");
214
215       if (EHFrameInfo.hasLandingPads)
216         EmitReference("exception", EHFrameInfo.Number, true, true);
217       else
218         Asm->EmitInt32((int)0);
219       Asm->EOL("Language Specific Data Area");
220     } else {
221       Asm->EmitULEB128Bytes(0);
222       Asm->EOL("Augmentation size");
223     }
224
225     // Indicate locations of function specific callee saved registers in frame.
226     EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, 
227                    true);
228
229     // On Darwin the linker honors the alignment of eh_frame, which means it
230     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise you
231     // get holes which confuse readers of eh_frame.
232     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
233                        0, 0, false);
234     EmitLabel("eh_frame_end", EHFrameInfo.Number);
235
236     // If the function is marked used, this table should be also.  We cannot
237     // make the mark unconditional in this case, since retaining the table also
238     // retains the function in this case, and there is code around that depends
239     // on unused functions (calling undefined externals) being dead-stripped to
240     // link correctly.  Yes, there really is.
241     if (MMI->getUsedFunctions().count(EHFrameInfo.function))
242       if (const char *UsedDirective = TAI->getUsedDirective())
243         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
244   }
245 }
246
247 /// EmitExceptionTable - Emit landing pads and actions.
248 ///
249 /// The general organization of the table is complex, but the basic concepts are
250 /// easy.  First there is a header which describes the location and organization
251 /// of the three components that follow.
252 /// 
253 ///  1. The landing pad site information describes the range of code covered by
254 ///     the try.  In our case it's an accumulation of the ranges covered by the
255 ///     invokes in the try.  There is also a reference to the landing pad that
256 ///     handles the exception once processed.  Finally an index into the actions
257 ///     table.
258 ///  2. The action table, in our case, is composed of pairs of type ids and next
259 ///     action offset.  Starting with the action index from the landing pad
260 ///     site, each type Id is checked for a match to the current exception.  If
261 ///     it matches then the exception and type id are passed on to the landing
262 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
263 ///     with a next action of zero.  If no type id is found the the frame is
264 ///     unwound and handling continues.
265 ///  3. Type id table contains references to all the C++ typeinfo for all
266 ///     catches in the function.  This tables is reversed indexed base 1.
267
268 /// SharedTypeIds - How many leading type ids two landing pads have in common.
269 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
270                                        const LandingPadInfo *R) {
271   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
272   unsigned LSize = LIds.size(), RSize = RIds.size();
273   unsigned MinSize = LSize < RSize ? LSize : RSize;
274   unsigned Count = 0;
275
276   for (; Count != MinSize; ++Count)
277     if (LIds[Count] != RIds[Count])
278       return Count;
279
280   return Count;
281 }
282
283 /// PadLT - Order landing pads lexicographically by type id.
284 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
285   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
286   unsigned LSize = LIds.size(), RSize = RIds.size();
287   unsigned MinSize = LSize < RSize ? LSize : RSize;
288
289   for (unsigned i = 0; i != MinSize; ++i)
290     if (LIds[i] != RIds[i])
291       return LIds[i] < RIds[i];
292
293   return LSize < RSize;
294 }
295
296 void DwarfException::EmitExceptionTable() {
297   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
298   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
299   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
300   if (PadInfos.empty()) return;
301
302   // Sort the landing pads in order of their type ids.  This is used to fold
303   // duplicate actions.
304   SmallVector<const LandingPadInfo *, 64> LandingPads;
305   LandingPads.reserve(PadInfos.size());
306   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
307     LandingPads.push_back(&PadInfos[i]);
308   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
309
310   // Negative type ids index into FilterIds, positive type ids index into
311   // TypeInfos.  The value written for a positive type id is just the type id
312   // itself.  For a negative type id, however, the value written is the
313   // (negative) byte offset of the corresponding FilterIds entry.  The byte
314   // offset is usually equal to the type id, because the FilterIds entries are
315   // written using a variable width encoding which outputs one byte per entry as
316   // long as the value written is not too large, but can differ.  This kind of
317   // complication does not occur for positive type ids because type infos are
318   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
319   // offset corresponding to FilterIds[i].
320   SmallVector<int, 16> FilterOffsets;
321   FilterOffsets.reserve(FilterIds.size());
322   int Offset = -1;
323   for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
324         E = FilterIds.end(); I != E; ++I) {
325     FilterOffsets.push_back(Offset);
326     Offset -= TargetAsmInfo::getULEB128Size(*I);
327   }
328
329   // Compute the actions table and gather the first action index for each
330   // landing pad site.
331   SmallVector<ActionEntry, 32> Actions;
332   SmallVector<unsigned, 64> FirstActions;
333   FirstActions.reserve(LandingPads.size());
334
335   int FirstAction = 0;
336   unsigned SizeActions = 0;
337   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
338     const LandingPadInfo *LP = LandingPads[i];
339     const std::vector<int> &TypeIds = LP->TypeIds;
340     const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
341     unsigned SizeSiteActions = 0;
342
343     if (NumShared < TypeIds.size()) {
344       unsigned SizeAction = 0;
345       ActionEntry *PrevAction = 0;
346
347       if (NumShared) {
348         const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
349         assert(Actions.size());
350         PrevAction = &Actions.back();
351         SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
352           TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
353
354         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
355           SizeAction -=
356             TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
357           SizeAction += -PrevAction->NextAction;
358           PrevAction = PrevAction->Previous;
359         }
360       }
361
362       // Compute the actions.
363       for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
364         int TypeID = TypeIds[I];
365         assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
366         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
367         unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
368
369         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
370         SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
371         SizeSiteActions += SizeAction;
372
373         ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
374         Actions.push_back(Action);
375
376         PrevAction = &Actions.back();
377       }
378
379       // Record the first action of the landing pad site.
380       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
381     } // else identical - re-use previous FirstAction
382
383     FirstActions.push_back(FirstAction);
384
385     // Compute this sites contribution to size.
386     SizeActions += SizeSiteActions;
387   }
388
389   // Compute the call-site table.  The entry for an invoke has a try-range
390   // containing the call, a non-zero landing pad and an appropriate action.  The
391   // entry for an ordinary call has a try-range containing the call and zero for
392   // the landing pad and the action.  Calls marked 'nounwind' have no entry and
393   // must not be contained in the try-range of any entry - they form gaps in the
394   // table.  Entries must be ordered by try-range address.
395   SmallVector<CallSiteEntry, 64> CallSites;
396
397   RangeMapType PadMap;
398
399   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
400   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
401   // try-ranges for them need be deduced.
402   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
403     const LandingPadInfo *LandingPad = LandingPads[i];
404     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
405       unsigned BeginLabel = LandingPad->BeginLabels[j];
406       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
407       PadRange P = { i, j };
408       PadMap[BeginLabel] = P;
409     }
410   }
411
412   // The end label of the previous invoke or nounwind try-range.
413   unsigned LastLabel = 0;
414
415   // Whether there is a potentially throwing instruction (currently this means
416   // an ordinary call) between the end of the previous try-range and now.
417   bool SawPotentiallyThrowing = false;
418
419   // Whether the last callsite entry was for an invoke.
420   bool PreviousIsInvoke = false;
421
422   // Visit all instructions in order of address.
423   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
424        I != E; ++I) {
425     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
426          MI != E; ++MI) {
427       if (!MI->isLabel()) {
428         SawPotentiallyThrowing |= MI->getDesc().isCall();
429         continue;
430       }
431
432       unsigned BeginLabel = MI->getOperand(0).getImm();
433       assert(BeginLabel && "Invalid label!");
434
435       // End of the previous try-range?
436       if (BeginLabel == LastLabel)
437         SawPotentiallyThrowing = false;
438
439       // Beginning of a new try-range?
440       RangeMapType::iterator L = PadMap.find(BeginLabel);
441       if (L == PadMap.end())
442         // Nope, it was just some random label.
443         continue;
444
445       PadRange P = L->second;
446       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
447
448       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
449              "Inconsistent landing pad map!");
450
451       // If some instruction between the previous try-range and this one may
452       // throw, create a call-site entry with no landing pad for the region
453       // between the try-ranges.
454       if (SawPotentiallyThrowing) {
455         CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
456         CallSites.push_back(Site);
457         PreviousIsInvoke = false;
458       }
459
460       LastLabel = LandingPad->EndLabels[P.RangeIndex];
461       assert(BeginLabel && LastLabel && "Invalid landing pad!");
462
463       if (LandingPad->LandingPadLabel) {
464         // This try-range is for an invoke.
465         CallSiteEntry Site = {BeginLabel, LastLabel,
466                               LandingPad->LandingPadLabel,
467                               FirstActions[P.PadIndex]};
468
469         // Try to merge with the previous call-site.
470         if (PreviousIsInvoke) {
471           CallSiteEntry &Prev = CallSites.back();
472           if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
473             // Extend the range of the previous entry.
474             Prev.EndLabel = Site.EndLabel;
475             continue;
476           }
477         }
478
479         // Otherwise, create a new call-site.
480         CallSites.push_back(Site);
481         PreviousIsInvoke = true;
482       } else {
483         // Create a gap.
484         PreviousIsInvoke = false;
485       }
486     }
487   }
488
489   // If some instruction between the previous try-range and the end of the
490   // function may throw, create a call-site entry with no landing pad for the
491   // region following the try-range.
492   if (SawPotentiallyThrowing) {
493     CallSiteEntry Site = {LastLabel, 0, 0, 0};
494     CallSites.push_back(Site);
495   }
496
497   // Final tallies.
498
499   // Call sites.
500   const unsigned SiteStartSize  = sizeof(int32_t); // DW_EH_PE_udata4
501   const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
502   const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
503   unsigned SizeSites = CallSites.size() * (SiteStartSize +
504                                            SiteLengthSize +
505                                            LandingPadSize);
506   for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
507     SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
508
509   // Type infos.
510   const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
511   unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
512
513   unsigned TypeOffset = sizeof(int8_t) + // Call site format
514     TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
515     SizeSites + SizeActions + SizeTypes;
516
517   unsigned TotalSize = sizeof(int8_t) + // LPStart format
518                        sizeof(int8_t) + // TType format
519            TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
520                        TypeOffset;
521
522   unsigned SizeAlign = (4 - TotalSize) & 3;
523
524   // Begin the exception table.
525   Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
526   Asm->EmitAlignment(2, 0, 0, false);
527   O << "GCC_except_table" << SubprogramCount << ":\n";
528
529   for (unsigned i = 0; i != SizeAlign; ++i) {
530     Asm->EmitInt8(0);
531     Asm->EOL("Padding");
532     }
533
534   EmitLabel("exception", SubprogramCount);
535
536   // Emit the header.
537   Asm->EmitInt8(dwarf::DW_EH_PE_omit);
538   Asm->EOL("LPStart format (DW_EH_PE_omit)");
539   Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
540   Asm->EOL("TType format (DW_EH_PE_absptr)");
541   Asm->EmitULEB128Bytes(TypeOffset);
542   Asm->EOL("TType base offset");
543   Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
544   Asm->EOL("Call site format (DW_EH_PE_udata4)");
545   Asm->EmitULEB128Bytes(SizeSites);
546   Asm->EOL("Call-site table length");
547
548   // Emit the landing pad site information.
549   for (unsigned i = 0; i < CallSites.size(); ++i) {
550     CallSiteEntry &S = CallSites[i];
551     const char *BeginTag;
552     unsigned BeginNumber;
553
554     if (!S.BeginLabel) {
555       BeginTag = "eh_func_begin";
556       BeginNumber = SubprogramCount;
557     } else {
558       BeginTag = "label";
559       BeginNumber = S.BeginLabel;
560     }
561
562     EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
563                       true, true);
564     Asm->EOL("Region start");
565
566     if (!S.EndLabel)
567       EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
568                      true);
569     else
570       EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
571
572     Asm->EOL("Region length");
573
574     if (!S.PadLabel)
575       Asm->EmitInt32(0);
576     else
577       EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
578                         true, true);
579
580     Asm->EOL("Landing pad");
581
582     Asm->EmitULEB128Bytes(S.Action);
583     Asm->EOL("Action");
584   }
585
586   // Emit the actions.
587   for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
588     ActionEntry &Action = Actions[I];
589
590     Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
591     Asm->EOL("TypeInfo index");
592     Asm->EmitSLEB128Bytes(Action.NextAction);
593     Asm->EOL("Next action");
594   }
595
596   // Emit the type ids.
597   for (unsigned M = TypeInfos.size(); M; --M) {
598     GlobalVariable *GV = TypeInfos[M - 1];
599     PrintRelDirective();
600
601     if (GV) {
602       std::string GLN;
603       O << Asm->getGlobalLinkName(GV, GLN);
604     } else {
605       O << "0";
606     }
607
608     Asm->EOL("TypeInfo");
609   }
610
611   // Emit the filter typeids.
612   for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
613     unsigned TypeID = FilterIds[j];
614     Asm->EmitULEB128Bytes(TypeID);
615     Asm->EOL("Filter TypeInfo index");
616   }
617
618   Asm->EmitAlignment(2, 0, 0, false);
619 }
620
621 /// EndModule - Emit all exception information that should come after the
622 /// content.
623 void DwarfException::EndModule() {
624   if (TimePassesIsEnabled)
625     ExceptionTimer->startTimer();
626
627   if (shouldEmitMovesModule || shouldEmitTableModule) {
628     const std::vector<Function *> Personalities = MMI->getPersonalities();
629     for (unsigned i = 0; i < Personalities.size(); ++i)
630       EmitCommonEHFrame(Personalities[i], i);
631
632     for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
633            E = EHFrames.end(); I != E; ++I)
634       EmitEHFrame(*I);
635   }
636
637   if (TimePassesIsEnabled)
638     ExceptionTimer->stopTimer();
639 }
640
641 /// BeginFunction - Gather pre-function exception information.  Assumes being
642 /// emitted immediately after the function entry point.
643 void DwarfException::BeginFunction(MachineFunction *MF) {
644   if (TimePassesIsEnabled)
645     ExceptionTimer->startTimer();
646
647   this->MF = MF;
648   shouldEmitTable = shouldEmitMoves = false;
649
650   if (MMI && TAI->doesSupportExceptionHandling()) {
651     // Map all labels and get rid of any dead landing pads.
652     MMI->TidyLandingPads();
653
654     // If any landing pads survive, we need an EH table.
655     if (MMI->getLandingPads().size())
656       shouldEmitTable = true;
657
658     // See if we need frame move info.
659     if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
660       shouldEmitMoves = true;
661
662     if (shouldEmitMoves || shouldEmitTable)
663       // Assumes in correct section after the entry point.
664       EmitLabel("eh_func_begin", ++SubprogramCount);
665   }
666
667   shouldEmitTableModule |= shouldEmitTable;
668   shouldEmitMovesModule |= shouldEmitMoves;
669
670   if (TimePassesIsEnabled)
671     ExceptionTimer->stopTimer();
672 }
673
674 /// EndFunction - Gather and emit post-function exception information.
675 ///
676 void DwarfException::EndFunction() {
677   if (TimePassesIsEnabled) 
678     ExceptionTimer->startTimer();
679
680   if (shouldEmitMoves || shouldEmitTable) {
681     EmitLabel("eh_func_end", SubprogramCount);
682     EmitExceptionTable();
683
684     // Save EH frame information
685     EHFrames.push_back(
686         FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
687                             SubprogramCount,
688                             MMI->getPersonalityIndex(),
689                             MF->getFrameInfo()->hasCalls(),
690                             !MMI->getLandingPads().empty(),
691                             MMI->getFrameMoves(),
692                             MF->getFunction()));
693   }
694
695   if (TimePassesIsEnabled) 
696     ExceptionTimer->stopTimer();
697 }