Rename functions to something more descriptive. At the very least mention the
[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/MachineFunction.h"
19 #include "llvm/CodeGen/MachineLocation.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetFrameInfo.h"
24 #include "llvm/Target/TargetLoweringObjectFile.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/StringExtras.h"
31 using namespace llvm;
32
33 static TimerGroup &getDwarfTimerGroup() {
34   static TimerGroup DwarfTimerGroup("Dwarf Exception");
35   return DwarfTimerGroup;
36 }
37
38 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
39                                const MCAsmInfo *T)
40   : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
41     shouldEmitTableModule(false), shouldEmitMovesModule(false),
42     ExceptionTimer(0) {
43   if (TimePassesIsEnabled) 
44     ExceptionTimer = new Timer("Dwarf Exception Writer",
45                                getDwarfTimerGroup());
46 }
47
48 DwarfException::~DwarfException() {
49   delete ExceptionTimer;
50 }
51
52 /// EmitCommonInformationEntry - Emit a Common Information Entry (CIE). This
53 /// holds information that is shared among many Frame Description Entries.
54 /// There is at least one CIE in every non-empty .debug_frame section.
55 void DwarfException::EmitCommonInformationEntry(const Function *Personality,
56                                                 unsigned Index) {
57   // Size and sign of stack growth.
58   int stackGrowth =
59     Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
60     TargetFrameInfo::StackGrowsUp ?
61     TD->getPointerSize() : -TD->getPointerSize();
62
63   // Begin eh frame section.
64   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
65
66   if (MAI->is_EHSymbolPrivate())
67     O << MAI->getPrivateGlobalPrefix();
68
69   O << "EH_frame" << Index << ":\n";
70   EmitLabel("section_eh_frame", Index);
71
72   // Define base labels.
73   EmitLabel("eh_frame_common", Index);
74
75   // Define the eh frame length.
76   EmitDifference("eh_frame_common_end", Index,
77                  "eh_frame_common_begin", Index, true);
78   Asm->EOL("Length of Common Information Entry");
79
80   // EH frame header.
81   EmitLabel("eh_frame_common_begin", Index);
82   Asm->EmitInt32((int)0);
83   Asm->EOL("CIE Identifier Tag");
84   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
85   Asm->EOL("CIE Version");
86
87   // The personality presence indicates that language specific information will
88   // show up in the eh frame.
89   Asm->EmitString(Personality ? "zPLR" : "zR");
90   Asm->EOL("CIE Augmentation");
91
92   // Round out reader.
93   Asm->EmitULEB128Bytes(1);
94   Asm->EOL("CIE Code Alignment Factor");
95   Asm->EmitSLEB128Bytes(stackGrowth);
96   Asm->EOL("CIE Data Alignment Factor");
97   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
98   Asm->EOL("CIE Return Address Column");
99
100   // If there is a personality, we need to indicate the functions location.
101   if (Personality) {
102     Asm->EmitULEB128Bytes(7);
103     Asm->EOL("Augmentation Size");
104
105     if (MAI->getNeedsIndirectEncoding()) {
106       Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
107                     dwarf::DW_EH_PE_indirect);
108       Asm->EOL("Personality (pcrel sdata4 indirect)");
109     } else {
110       Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
111       Asm->EOL("Personality (pcrel sdata4)");
112     }
113
114     PrintRelDirective(true);
115     O << MAI->getPersonalityPrefix();
116     Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
117     O << MAI->getPersonalitySuffix();
118     if (strcmp(MAI->getPersonalitySuffix(), "+4@GOTPCREL"))
119       O << "-" << MAI->getPCSymbol();
120     Asm->EOL("Personality");
121
122     Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
123     Asm->EOL("LSDA Encoding (pcrel sdata4)");
124
125     Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
126     Asm->EOL("FDE Encoding (pcrel sdata4)");
127   } else {
128     Asm->EmitULEB128Bytes(1);
129     Asm->EOL("Augmentation Size");
130
131     Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
132     Asm->EOL("FDE Encoding (pcrel sdata4)");
133   }
134
135   // Indicate locations of general callee saved registers in frame.
136   std::vector<MachineMove> Moves;
137   RI->getInitialFrameState(Moves);
138   EmitFrameMoves(NULL, 0, Moves, true);
139
140   // On Darwin the linker honors the alignment of eh_frame, which means it must
141   // be 8-byte on 64-bit targets to match what gcc does.  Otherwise you get
142   // holes which confuse readers of eh_frame.
143   Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
144                      0, 0, false);
145   EmitLabel("eh_frame_common_end", Index);
146
147   Asm->EOL();
148 }
149
150 /// EmitFrameDescriptionEntry - Emit the Frame Description Entry (FDE) for the
151 /// function.
152 void DwarfException::
153 EmitFrameDescriptionEntry(const FunctionEHFrameInfo &EHFrameInfo) {
154   assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() && 
155          "Should not emit 'available externally' functions at all");
156
157   const Function *TheFunc = EHFrameInfo.function;
158   
159   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
160   
161   // Externally visible entry into the functions eh frame info. If the
162   // corresponding function is static, this should not be externally visible.
163   if (!TheFunc->hasLocalLinkage())
164     if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
165       O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
166
167   // If corresponding function is weak definition, this should be too.
168   if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
169     O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
170
171   // If there are no calls then you can't unwind.  This may mean we can omit the
172   // EH Frame, but some environments do not handle weak absolute symbols. If
173   // UnwindTablesMandatory is set we cannot do this optimization; the unwind
174   // info is to be available for non-EH uses.
175   if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
176       (!TheFunc->isWeakForLinker() ||
177        !MAI->getWeakDefDirective() ||
178        MAI->getSupportsWeakOmittedEHFrame())) {
179     O << EHFrameInfo.FnName << " = 0\n";
180     // This name has no connection to the function, so it might get
181     // dead-stripped when the function is not, erroneously.  Prohibit
182     // dead-stripping unconditionally.
183     if (const char *UsedDirective = MAI->getUsedDirective())
184       O << UsedDirective << EHFrameInfo.FnName << "\n\n";
185   } else {
186     O << EHFrameInfo.FnName << ":\n";
187
188     // EH frame header.
189     EmitDifference("eh_frame_end", EHFrameInfo.Number,
190                    "eh_frame_begin", EHFrameInfo.Number, true);
191     Asm->EOL("Length of Frame Information Entry");
192
193     EmitLabel("eh_frame_begin", EHFrameInfo.Number);
194
195     EmitSectionOffset("eh_frame_begin", "eh_frame_common",
196                       EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
197                       true, true, false);
198
199     Asm->EOL("FDE CIE offset");
200
201     EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
202     Asm->EOL("FDE initial location");
203     EmitDifference("eh_func_end", EHFrameInfo.Number,
204                    "eh_func_begin", EHFrameInfo.Number, true);
205     Asm->EOL("FDE address range");
206
207     // If there is a personality and landing pads then point to the language
208     // specific data area in the exception table.
209     if (EHFrameInfo.PersonalityIndex) {
210       Asm->EmitULEB128Bytes(4);
211       Asm->EOL("Augmentation size");
212
213       if (EHFrameInfo.hasLandingPads)
214         EmitReference("exception", EHFrameInfo.Number, true, true);
215       else
216         Asm->EmitInt32((int)0);
217       Asm->EOL("Language Specific Data Area");
218     } else {
219       Asm->EmitULEB128Bytes(0);
220       Asm->EOL("Augmentation size");
221     }
222
223     // Indicate locations of function specific callee saved registers in frame.
224     EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, 
225                    true);
226
227     // On Darwin the linker honors the alignment of eh_frame, which means it
228     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise you
229     // get holes which confuse readers of eh_frame.
230     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
231                        0, 0, false);
232     EmitLabel("eh_frame_end", EHFrameInfo.Number);
233
234     // If the function is marked used, this table should be also.  We cannot
235     // make the mark unconditional in this case, since retaining the table also
236     // retains the function in this case, and there is code around that depends
237     // on unused functions (calling undefined externals) being dead-stripped to
238     // link correctly.  Yes, there really is.
239     if (MMI->isUsedFunction(EHFrameInfo.function))
240       if (const char *UsedDirective = MAI->getUsedDirective())
241         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
242   }
243 }
244
245 /// SharedTypeIds - How many leading type ids two landing pads have in common.
246 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
247                                        const LandingPadInfo *R) {
248   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
249   unsigned LSize = LIds.size(), RSize = RIds.size();
250   unsigned MinSize = LSize < RSize ? LSize : RSize;
251   unsigned Count = 0;
252
253   for (; Count != MinSize; ++Count)
254     if (LIds[Count] != RIds[Count])
255       return Count;
256
257   return Count;
258 }
259
260 /// PadLT - Order landing pads lexicographically by type id.
261 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
262   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
263   unsigned LSize = LIds.size(), RSize = RIds.size();
264   unsigned MinSize = LSize < RSize ? LSize : RSize;
265
266   for (unsigned i = 0; i != MinSize; ++i)
267     if (LIds[i] != RIds[i])
268       return LIds[i] < RIds[i];
269
270   return LSize < RSize;
271 }
272
273 /// ComputeActionsTable - Compute the actions table and gather the first action
274 /// index for each landing pad site.
275 unsigned DwarfException::
276 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
277                     SmallVectorImpl<ActionEntry> &Actions,
278                     SmallVectorImpl<unsigned> &FirstActions) {
279
280   // The action table follows the call-site table in the LSDA. The individual
281   // records are of two types:
282   //
283   //   * Catch clause
284   //   * Exception specification
285   //
286   // The two record kinds have the same format, with only small differences.
287   // They are distinguished by the "switch value" field: Catch clauses
288   // (TypeInfos) have strictly positive switch values, and exception
289   // specifications (FilterIds) have strictly negative switch values. Value 0
290   // indicates a catch-all clause.
291   //
292   // Negative type IDs index into FilterIds. Positive type IDs index into
293   // TypeInfos.  The value written for a positive type ID is just the type ID
294   // itself.  For a negative type ID, however, the value written is the
295   // (negative) byte offset of the corresponding FilterIds entry.  The byte
296   // offset is usually equal to the type ID (because the FilterIds entries are
297   // written using a variable width encoding, which outputs one byte per entry
298   // as long as the value written is not too large) but can differ.  This kind
299   // of complication does not occur for positive type IDs because type infos are
300   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
301   // offset corresponding to FilterIds[i].
302
303   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
304   SmallVector<int, 16> FilterOffsets;
305   FilterOffsets.reserve(FilterIds.size());
306   int Offset = -1;
307
308   for (std::vector<unsigned>::const_iterator
309          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
310     FilterOffsets.push_back(Offset);
311     Offset -= MCAsmInfo::getULEB128Size(*I);
312   }
313
314   FirstActions.reserve(LandingPads.size());
315
316   int FirstAction = 0;
317   unsigned SizeActions = 0;
318   const LandingPadInfo *PrevLPI = 0;
319
320   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
321          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
322     const LandingPadInfo *LPI = *I;
323     const std::vector<int> &TypeIds = LPI->TypeIds;
324     const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
325     unsigned SizeSiteActions = 0;
326
327     if (NumShared < TypeIds.size()) {
328       unsigned SizeAction = 0;
329       ActionEntry *PrevAction = 0;
330
331       if (NumShared) {
332         const unsigned SizePrevIds = PrevLPI->TypeIds.size();
333         assert(Actions.size());
334         PrevAction = &Actions.back();
335         SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
336           MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
337
338         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
339           SizeAction -=
340             MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
341           SizeAction += -PrevAction->NextAction;
342           PrevAction = PrevAction->Previous;
343         }
344       }
345
346       // Compute the actions.
347       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
348         int TypeID = TypeIds[J];
349         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
350         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
351         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
352
353         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
354         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
355         SizeSiteActions += SizeAction;
356
357         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
358         Actions.push_back(Action);
359         PrevAction = &Actions.back();
360       }
361
362       // Record the first action of the landing pad site.
363       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
364     } // else identical - re-use previous FirstAction
365
366     // Information used when created the call-site table. The action record
367     // field of the call site record is the offset of the first associated
368     // action record, relative to the start of the actions table. This value is
369     // biased by 1 (1 in dicating the start of the actions table), and 0
370     // indicates that there are no actions.
371     FirstActions.push_back(FirstAction);
372
373     // Compute this sites contribution to size.
374     SizeActions += SizeSiteActions;
375
376     PrevLPI = LPI;
377   }
378
379   return SizeActions;
380 }
381
382 /// ComputeCallSiteTable - Compute the call-site table.  The entry for an invoke
383 /// has a try-range containing the call, a non-zero landing pad, and an
384 /// appropriate action.  The entry for an ordinary call has a try-range
385 /// containing the call and zero for the landing pad and the action.  Calls
386 /// marked 'nounwind' have no entry and must not be contained in the try-range
387 /// of any entry - they form gaps in the table.  Entries must be ordered by
388 /// try-range address.
389 void DwarfException::
390 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
391                      const RangeMapType &PadMap,
392                      const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
393                      const SmallVectorImpl<unsigned> &FirstActions) {
394   // The end label of the previous invoke or nounwind try-range.
395   unsigned LastLabel = 0;
396
397   // Whether there is a potentially throwing instruction (currently this means
398   // an ordinary call) between the end of the previous try-range and now.
399   bool SawPotentiallyThrowing = false;
400
401   // Whether the last CallSite entry was for an invoke.
402   bool PreviousIsInvoke = false;
403
404   // Visit all instructions in order of address.
405   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
406        I != E; ++I) {
407     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
408          MI != E; ++MI) {
409       if (!MI->isLabel()) {
410         SawPotentiallyThrowing |= MI->getDesc().isCall();
411         continue;
412       }
413
414       unsigned BeginLabel = MI->getOperand(0).getImm();
415       assert(BeginLabel && "Invalid label!");
416
417       // End of the previous try-range?
418       if (BeginLabel == LastLabel)
419         SawPotentiallyThrowing = false;
420
421       // Beginning of a new try-range?
422       RangeMapType::iterator L = PadMap.find(BeginLabel);
423       if (L == PadMap.end())
424         // Nope, it was just some random label.
425         continue;
426
427       const PadRange &P = L->second;
428       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
429       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
430              "Inconsistent landing pad map!");
431
432       // For Dwarf exception handling (SjLj handling doesn't use this). If some
433       // instruction between the previous try-range and this one may throw,
434       // create a call-site entry with no landing pad for the region between the
435       // try-ranges.
436       if (SawPotentiallyThrowing &&
437           MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
438         CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
439         CallSites.push_back(Site);
440         PreviousIsInvoke = false;
441       }
442
443       LastLabel = LandingPad->EndLabels[P.RangeIndex];
444       assert(BeginLabel && LastLabel && "Invalid landing pad!");
445
446       if (LandingPad->LandingPadLabel) {
447         // This try-range is for an invoke.
448         CallSiteEntry Site = {
449           BeginLabel,
450           LastLabel,
451           LandingPad->LandingPadLabel,
452           FirstActions[P.PadIndex]
453         };
454
455         // Try to merge with the previous call-site.
456         if (PreviousIsInvoke) {
457           CallSiteEntry &Prev = CallSites.back();
458           if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
459             // Extend the range of the previous entry.
460             Prev.EndLabel = Site.EndLabel;
461             continue;
462           }
463         }
464
465         // Otherwise, create a new call-site.
466         CallSites.push_back(Site);
467         PreviousIsInvoke = true;
468       } else {
469         // Create a gap.
470         PreviousIsInvoke = false;
471       }
472     }
473   }
474
475   // If some instruction between the previous try-range and the end of the
476   // function may throw, create a call-site entry with no landing pad for the
477   // region following the try-range.
478   if (SawPotentiallyThrowing &&
479       MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
480     CallSiteEntry Site = { LastLabel, 0, 0, 0 };
481     CallSites.push_back(Site);
482   }
483 }
484
485 /// EmitExceptionTable - Emit landing pads and actions.
486 ///
487 /// The general organization of the table is complex, but the basic concepts are
488 /// easy.  First there is a header which describes the location and organization
489 /// of the three components that follow.
490 /// 
491 ///  1. The landing pad site information describes the range of code covered by
492 ///     the try.  In our case it's an accumulation of the ranges covered by the
493 ///     invokes in the try.  There is also a reference to the landing pad that
494 ///     handles the exception once processed.  Finally an index into the actions
495 ///     table.
496 ///  2. The action table, in our case, is composed of pairs of type IDs and next
497 ///     action offset.  Starting with the action index from the landing pad
498 ///     site, each type ID is checked for a match to the current exception.  If
499 ///     it matches then the exception and type id are passed on to the landing
500 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
501 ///     with a next action of zero.  If no type id is found the the frame is
502 ///     unwound and handling continues.
503 ///  3. Type ID table contains references to all the C++ typeinfo for all
504 ///     catches in the function.  This tables is reversed indexed base 1.
505 void DwarfException::EmitExceptionTable() {
506   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
507   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
508   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
509   if (PadInfos.empty()) return;
510
511   // Sort the landing pads in order of their type ids.  This is used to fold
512   // duplicate actions.
513   SmallVector<const LandingPadInfo *, 64> LandingPads;
514   LandingPads.reserve(PadInfos.size());
515
516   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
517     LandingPads.push_back(&PadInfos[i]);
518
519   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
520
521   // Compute the actions table and gather the first action index for each
522   // landing pad site.
523   SmallVector<ActionEntry, 32> Actions;
524   SmallVector<unsigned, 64> FirstActions;
525   unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
526
527   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
528   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
529   // try-ranges for them need be deduced when using Dwarf exception handling.
530   RangeMapType PadMap;
531   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
532     const LandingPadInfo *LandingPad = LandingPads[i];
533     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
534       unsigned BeginLabel = LandingPad->BeginLabels[j];
535       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
536       PadRange P = { i, j };
537       PadMap[BeginLabel] = P;
538     }
539   }
540
541   // Compute the call-site table.
542   SmallVector<CallSiteEntry, 64> CallSites;
543   ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
544
545   // Final tallies.
546
547   // Call sites.
548   const unsigned SiteStartSize  = sizeof(int32_t); // DW_EH_PE_udata4
549   const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
550   const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
551   unsigned SizeSites;
552
553   bool HaveTTData = (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
554     ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
555
556
557   if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
558     SizeSites = 0;
559   } else
560     SizeSites = CallSites.size() *
561       (SiteStartSize + SiteLengthSize + LandingPadSize);
562   for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
563     SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
564     if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
565       SizeSites += MCAsmInfo::getULEB128Size(i);
566   }
567   // Type infos.
568   const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
569   unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
570
571   unsigned TypeOffset = sizeof(int8_t) + // Call site format
572     MCAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
573     SizeSites + SizeActions + SizeTypes;
574
575   unsigned TotalSize = sizeof(int8_t) + // LPStart format
576                        sizeof(int8_t) + // TType format
577        (HaveTTData ?
578           MCAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
579                        TypeOffset;
580
581   unsigned SizeAlign = (4 - TotalSize) & 3;
582
583   // Begin the exception table.
584   const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
585   Asm->OutStreamer.SwitchSection(LSDASection);
586   Asm->EmitAlignment(2, 0, 0, false);
587   O << "GCC_except_table" << SubprogramCount << ":\n";
588
589   for (unsigned i = 0; i != SizeAlign; ++i) {
590     Asm->EmitInt8(0);
591     Asm->EOL("Padding");
592   }
593
594   EmitLabel("exception", SubprogramCount);
595   if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
596     std::string SjLjName = "_lsda_";
597     SjLjName += MF->getFunction()->getName().str();
598     EmitLabel(SjLjName.c_str(), 0);
599   }
600
601   // Emit the header.
602   Asm->EmitInt8(dwarf::DW_EH_PE_omit);
603   Asm->EOL("@LPStart format (DW_EH_PE_omit)");
604
605 #if 0
606   if (TypeInfos.empty() && FilterIds.empty()) {
607     // If there are no typeinfos or filters, there is nothing to emit, optimize
608     // by specifying the "omit" encoding.
609     Asm->EmitInt8(dwarf::DW_EH_PE_omit);
610     Asm->EOL("@TType format (DW_EH_PE_omit)");
611   } else {
612     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
613     // pick a type encoding for them.  We're about to emit a list of pointers to
614     // typeinfo objects at the end of the LSDA.  However, unless we're in static
615     // mode, this reference will require a relocation by the dynamic linker.
616     //
617     // Because of this, we have a couple of options:
618     //   1) If we are in -static mode, we can always use an absolute reference
619     //      from the LSDA, because the static linker will resolve it.
620     //   2) Otherwise, if the LSDA section is writable, we can output the direct
621     //      reference to the typeinfo and allow the dynamic linker to relocate
622     //      it.  Since it is in a writable section, the dynamic linker won't
623     //      have a problem.
624     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
625     //      we need to use some form of indirection.  For example, on Darwin,
626     //      we can output a statically-relocatable reference to a dyld stub. The
627     //      offset to the stub is constant, but the contents are in a section
628     //      that is updated by the dynamic linker.  This is easy enough, but we
629     //      need to tell the personality function of the unwinder to indirect
630     //      through the dyld stub.
631     //
632     // FIXME: When this is actually implemented, we'll have to emit the stubs
633     // somewhere.  This predicate should be moved to a shared location that is
634     // in target-independent code.
635     //
636     if (LSDASection->isWritable() ||
637         Asm->TM.getRelocationModel() == Reloc::Static) {
638       Asm->EmitInt8(DW_EH_PE_absptr);
639       Asm->EOL("TType format (DW_EH_PE_absptr)");
640     } else {
641       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
642       Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
643                " | DW_EH_PE_sdata4)");
644     }
645     Asm->EmitULEB128Bytes(TypeOffset);
646     Asm->EOL("TType base offset");
647   }
648 #else
649   // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
650   // say that we're omitting that bit.
651   // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
652   if (!HaveTTData) {
653     Asm->EmitInt8(dwarf::DW_EH_PE_omit);
654     Asm->EOL("@TType format (DW_EH_PE_omit)");
655   } else {
656     Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
657     Asm->EOL("@TType format (DW_EH_PE_absptr)");
658     Asm->EmitULEB128Bytes(TypeOffset);
659     Asm->EOL("@TType base offset");
660   }
661 #endif
662
663   // SjLj Exception handilng
664   if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
665     Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
666     Asm->EOL("Call site format (DW_EH_PE_udata4)");
667     Asm->EmitULEB128Bytes(SizeSites);
668     Asm->EOL("Call site table length");
669
670     // Emit the landing pad site information.
671     unsigned idx = 0;
672     for (SmallVectorImpl<CallSiteEntry>::const_iterator
673          I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
674       const CallSiteEntry &S = *I;
675
676       // Offset of the landing pad, counted in 16-byte bundles relative to the
677       // @LPStart address.
678       Asm->EmitULEB128Bytes(idx);
679       Asm->EOL("Landing pad");
680
681       // Offset of the first associated action record, relative to the start of
682       // the action table. This value is biased by 1 (1 indicates the start of
683       // the action table), and 0 indicates that there are no actions.
684       Asm->EmitULEB128Bytes(S.Action);
685       Asm->EOL("Action");
686     }
687   } else {
688     // DWARF Exception handling
689     assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
690
691     // The call-site table is a list of all call sites that may throw an
692     // exception (including C++ 'throw' statements) in the procedure
693     // fragment. It immediately follows the LSDA header. Each entry indicates,
694     // for a given call, the first corresponding action record and corresponding
695     // landing pad.
696     //
697     // The table begins with the number of bytes, stored as an LEB128
698     // compressed, unsigned integer. The records immediately follow the record
699     // count. They are sorted in increasing call-site address. Each record
700     // indicates:
701     //
702     //   * The position of the call-site.
703     //   * The position of the landing pad.
704     //   * The first action record for that call site.
705     //
706     // A missing entry in the call-site table indicates that a call is not
707     // supposed to throw. Such calls include:
708     //
709     //   * Calls to destructors within cleanup code. C++ semantics forbids these
710     //     calls to throw.
711     //   * Calls to intrinsic routines in the standard library which are known
712     //     not to throw (sin, memcpy, et al).
713     //
714     // If the runtime does not find the call-site entry for a given call, it
715     // will call `terminate()'.
716
717     // Emit the landing pad call site table.
718     Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
719     Asm->EOL("Call site format (DW_EH_PE_udata4)");
720     Asm->EmitULEB128Bytes(SizeSites);
721     Asm->EOL("Call site table size");
722
723     for (SmallVectorImpl<CallSiteEntry>::const_iterator
724          I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
725       const CallSiteEntry &S = *I;
726       const char *BeginTag;
727       unsigned BeginNumber;
728
729       if (!S.BeginLabel) {
730         BeginTag = "eh_func_begin";
731         BeginNumber = SubprogramCount;
732       } else {
733         BeginTag = "label";
734         BeginNumber = S.BeginLabel;
735       }
736
737       // Offset of the call site relative to the previous call site, counted in
738       // number of 16-byte bundles. The first call site is counted relative to
739       // the start of the procedure fragment.
740       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
741                         true, true);
742       Asm->EOL("Region start");
743
744       if (!S.EndLabel)
745         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
746                        true);
747       else
748         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
749
750       Asm->EOL("Region length");
751
752       // Offset of the landing pad, counted in 16-byte bundles relative to the
753       // @LPStart address.
754       if (!S.PadLabel)
755         Asm->EmitInt32(0);
756       else
757         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
758                           true, true);
759
760       Asm->EOL("Landing pad");
761
762       // Offset of the first associated action record, relative to the start of
763       // the action table. This value is biased by 1 (1 indicates the start of
764       // the action table), and 0 indicates that there are no actions.
765       Asm->EmitULEB128Bytes(S.Action);
766       Asm->EOL("Action");
767     }
768   }
769
770   // Emit the Action Table.
771   for (SmallVectorImpl<ActionEntry>::const_iterator
772          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
773     const ActionEntry &Action = *I;
774
775     // Type Filter
776     //
777     //   Used by the runtime to match the type of the thrown exception to the
778     //   type of the catch clauses or the types in the exception specification.
779
780     Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
781     Asm->EOL("TypeInfo index");
782
783     // Action Record
784     //
785     //   Self-relative signed displacement in bytes of the next action record,
786     //   or 0 if there is no next action record.
787
788     Asm->EmitSLEB128Bytes(Action.NextAction);
789     Asm->EOL("Next action");
790   }
791
792   // Emit the Catch Clauses. The code for the catch clauses following the same
793   // try is similar to a switch statement. The catch clause action record
794   // informs the runtime about the type of a catch clause and about the
795   // associated switch value.
796   //
797   //  Action Record Fields:
798   //  
799   //   * Filter Value
800   //     Positive value, starting at 1. Index in the types table of the
801   //     __typeinfo for the catch-clause type. 1 is the first word preceding
802   //     TTBase, 2 is the second word, and so on. Used by the runtime to check
803   //     if the thrown exception type matches the catch-clause type. Back-end
804   //     generated switch statements check against this value.
805   //
806   //   * Next
807   //     Signed offset, in bytes from the start of this field, to the next
808   //     chained action record, or zero if none.
809   //
810   // The order of the action records determined by the next field is the order
811   // of the catch clauses as they appear in the source code, and must be kept in
812   // the same order. As a result, changing the order of the catch clause would
813   // change the semantics of the program.
814   for (std::vector<GlobalVariable *>::const_reverse_iterator
815          I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
816     const GlobalVariable *GV = *I;
817     PrintRelDirective();
818
819     if (GV) {
820       std::string GLN;
821       O << Asm->getGlobalLinkName(GV, GLN);
822     } else {
823       O << "0";
824     }
825
826     Asm->EOL("TypeInfo");
827   }
828
829   // Emit the Type Table.
830   for (std::vector<unsigned>::const_iterator
831          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
832     unsigned TypeID = *I;
833     Asm->EmitULEB128Bytes(TypeID);
834     Asm->EOL("Filter TypeInfo index");
835   }
836
837   Asm->EmitAlignment(2, 0, 0, false);
838 }
839
840 /// EndModule - Emit all exception information that should come after the
841 /// content.
842 void DwarfException::EndModule() {
843   if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
844     return;
845   if (TimePassesIsEnabled)
846     ExceptionTimer->startTimer();
847
848   if (shouldEmitMovesModule || shouldEmitTableModule) {
849     const std::vector<Function *> Personalities = MMI->getPersonalities();
850     for (unsigned i = 0; i < Personalities.size(); ++i)
851       EmitCommonInformationEntry(Personalities[i], i);
852
853     for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
854            E = EHFrames.end(); I != E; ++I)
855       EmitFrameDescriptionEntry(*I);
856   }
857
858   if (TimePassesIsEnabled)
859     ExceptionTimer->stopTimer();
860 }
861
862 /// BeginFunction - Gather pre-function exception information.  Assumes being
863 /// emitted immediately after the function entry point.
864 void DwarfException::BeginFunction(MachineFunction *MF) {
865   if (TimePassesIsEnabled)
866     ExceptionTimer->startTimer();
867
868   this->MF = MF;
869   shouldEmitTable = shouldEmitMoves = false;
870
871   if (MMI && MAI->doesSupportExceptionHandling()) {
872     // Map all labels and get rid of any dead landing pads.
873     MMI->TidyLandingPads();
874
875     // If any landing pads survive, we need an EH table.
876     if (MMI->getLandingPads().size())
877       shouldEmitTable = true;
878
879     // See if we need frame move info.
880     if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
881       shouldEmitMoves = true;
882
883     if (shouldEmitMoves || shouldEmitTable)
884       // Assumes in correct section after the entry point.
885       EmitLabel("eh_func_begin", ++SubprogramCount);
886   }
887
888   shouldEmitTableModule |= shouldEmitTable;
889   shouldEmitMovesModule |= shouldEmitMoves;
890
891   if (TimePassesIsEnabled)
892     ExceptionTimer->stopTimer();
893 }
894
895 /// EndFunction - Gather and emit post-function exception information.
896 ///
897 void DwarfException::EndFunction() {
898   if (TimePassesIsEnabled) 
899     ExceptionTimer->startTimer();
900
901   if (shouldEmitMoves || shouldEmitTable) {
902     EmitLabel("eh_func_end", SubprogramCount);
903     EmitExceptionTable();
904
905     // Save EH frame information
906     EHFrames.push_back(
907         FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
908                             SubprogramCount,
909                             MMI->getPersonalityIndex(),
910                             MF->getFrameInfo()->hasCalls(),
911                             !MMI->getLandingPads().empty(),
912                             MMI->getFrameMoves(),
913                             MF->getFunction()));
914   }
915
916   if (TimePassesIsEnabled) 
917     ExceptionTimer->stopTimer();
918 }