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