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