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