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