1 //===-- CodeGen/AsmPrinter/DwarfException.cpp - Dwarf Exception Impl ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing DWARF exception info into asm files.
12 //===----------------------------------------------------------------------===//
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/MCSection.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetFrameInfo.h"
25 #include "llvm/Target/TargetLoweringObjectFile.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Support/Timer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
36 static TimerGroup &getDwarfTimerGroup() {
37 static TimerGroup DwarfTimerGroup("DWARF Exception");
38 return DwarfTimerGroup;
41 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
43 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
44 shouldEmitTableModule(false), shouldEmitMovesModule(false),
46 if (TimePassesIsEnabled)
47 ExceptionTimer = new Timer("DWARF Exception Writer",
48 getDwarfTimerGroup());
51 DwarfException::~DwarfException() {
52 delete ExceptionTimer;
55 /// SizeOfEncodedValue - Return the size of the encoding in bytes.
56 unsigned DwarfException::SizeOfEncodedValue(unsigned Encoding) {
57 if (Encoding == dwarf::DW_EH_PE_omit)
60 switch (Encoding & 0x07) {
61 case dwarf::DW_EH_PE_absptr:
62 return TD->getPointerSize();
63 case dwarf::DW_EH_PE_udata2:
65 case dwarf::DW_EH_PE_udata4:
67 case dwarf::DW_EH_PE_udata8:
71 assert(0 && "Invalid encoded value.");
75 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
76 /// is shared among many Frame Description Entries. There is at least one CIE
77 /// in every non-empty .debug_frame section.
78 void DwarfException::EmitCIE(const Function *Personality, unsigned Index) {
79 // Size and sign of stack growth.
81 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
82 TargetFrameInfo::StackGrowsUp ?
83 TD->getPointerSize() : -TD->getPointerSize();
85 // Begin eh frame section.
86 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
88 if (MAI->is_EHSymbolPrivate())
89 O << MAI->getPrivateGlobalPrefix();
91 O << "EH_frame" << Index << ":\n";
92 EmitLabel("section_eh_frame", Index);
94 // Define base labels.
95 EmitLabel("eh_frame_common", Index);
97 // Define the eh frame length.
98 EmitDifference("eh_frame_common_end", Index,
99 "eh_frame_common_begin", Index, true);
100 Asm->EOL("Length of Common Information Entry");
103 EmitLabel("eh_frame_common_begin", Index);
104 Asm->EmitInt32((int)0);
105 Asm->EOL("CIE Identifier Tag");
106 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
107 Asm->EOL("CIE Version");
109 // The personality presence indicates that language specific information will
110 // show up in the eh frame.
112 // FIXME: Don't hardcode these encodings.
113 unsigned PerEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
114 if (Personality && MAI->getNeedsIndirectEncoding())
115 PerEncoding |= dwarf::DW_EH_PE_indirect;
116 unsigned LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
117 unsigned FDEEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
119 char Augmentation[5] = { 0 };
120 unsigned AugmentationSize = 0;
121 char *APtr = Augmentation + 1;
124 // There is a personality function.
126 AugmentationSize += 1 + SizeOfEncodedValue(PerEncoding);
129 if (UsesLSDA[Index]) {
130 // An LSDA pointer is in the FDE augmentation.
135 if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
136 // A non-default pointer encoding for the FDE.
141 if (APtr != Augmentation + 1)
142 Augmentation[0] = 'z';
144 Asm->EmitString(Augmentation);
145 Asm->EOL("CIE Augmentation");
148 Asm->EmitULEB128Bytes(1);
149 Asm->EOL("CIE Code Alignment Factor");
150 Asm->EmitSLEB128Bytes(stackGrowth);
151 Asm->EOL("CIE Data Alignment Factor");
152 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
153 Asm->EOL("CIE Return Address Column");
155 Asm->EmitULEB128Bytes(AugmentationSize);
156 Asm->EOL("Augmentation Size");
158 Asm->EmitInt8(PerEncoding);
159 Asm->EOL("Personality", PerEncoding);
161 // If there is a personality, we need to indicate the function's location.
163 O << MAI->getData32bitsDirective();
165 O << MAI->getPersonalityPrefix();
166 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
167 O << MAI->getPersonalitySuffix();
169 if (strcmp(MAI->getPersonalitySuffix(), "+4@GOTPCREL"))
170 O << "-" << MAI->getPCSymbol();
171 Asm->EOL("Personality");
173 Asm->EmitInt8(LSDAEncoding);
174 Asm->EOL("LSDA Encoding", LSDAEncoding);
176 Asm->EmitInt8(FDEEncoding);
177 Asm->EOL("FDE Encoding", FDEEncoding);
180 // Indicate locations of general callee saved registers in frame.
181 std::vector<MachineMove> Moves;
182 RI->getInitialFrameState(Moves);
183 EmitFrameMoves(NULL, 0, Moves, true);
185 // On Darwin the linker honors the alignment of eh_frame, which means it must
186 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
187 // holes which confuse readers of eh_frame.
188 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
190 EmitLabel("eh_frame_common_end", Index);
195 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
196 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
197 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
198 "Should not emit 'available externally' functions at all");
200 const Function *TheFunc = EHFrameInfo.function;
202 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
204 // Externally visible entry into the functions eh frame info. If the
205 // corresponding function is static, this should not be externally visible.
206 if (!TheFunc->hasLocalLinkage())
207 if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
208 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
210 // If corresponding function is weak definition, this should be too.
211 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
212 O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
214 // If there are no calls then you can't unwind. This may mean we can omit the
215 // EH Frame, but some environments do not handle weak absolute symbols. If
216 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
217 // info is to be available for non-EH uses.
218 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
219 (!TheFunc->isWeakForLinker() ||
220 !MAI->getWeakDefDirective() ||
221 MAI->getSupportsWeakOmittedEHFrame())) {
222 O << EHFrameInfo.FnName << " = 0\n";
223 // This name has no connection to the function, so it might get
224 // dead-stripped when the function is not, erroneously. Prohibit
225 // dead-stripping unconditionally.
226 if (const char *UsedDirective = MAI->getUsedDirective())
227 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
229 O << EHFrameInfo.FnName << ":\n";
232 EmitDifference("eh_frame_end", EHFrameInfo.Number,
233 "eh_frame_begin", EHFrameInfo.Number, true);
234 Asm->EOL("Length of Frame Information Entry");
236 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
238 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
239 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
242 Asm->EOL("FDE CIE offset");
244 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
245 Asm->EOL("FDE initial location");
246 EmitDifference("eh_func_end", EHFrameInfo.Number,
247 "eh_func_begin", EHFrameInfo.Number, true);
248 Asm->EOL("FDE address range");
250 // If there is a personality and landing pads then point to the language
251 // specific data area in the exception table.
252 if (MMI->getPersonalities()[0] != NULL) {
253 bool is4Byte = TD->getPointerSize() == sizeof(int32_t);
255 Asm->EmitULEB128Bytes(is4Byte ? 4 : 8);
256 Asm->EOL("Augmentation size");
258 if (EHFrameInfo.hasLandingPads)
259 EmitReference("exception", EHFrameInfo.Number, true, false);
262 Asm->EmitInt32((int)0);
264 Asm->EmitInt64((int)0);
266 Asm->EOL("Language Specific Data Area");
268 Asm->EmitULEB128Bytes(0);
269 Asm->EOL("Augmentation size");
272 // Indicate locations of function specific callee saved registers in frame.
273 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
276 // On Darwin the linker honors the alignment of eh_frame, which means it
277 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
278 // get holes which confuse readers of eh_frame.
279 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
281 EmitLabel("eh_frame_end", EHFrameInfo.Number);
283 // If the function is marked used, this table should be also. We cannot
284 // make the mark unconditional in this case, since retaining the table also
285 // retains the function in this case, and there is code around that depends
286 // on unused functions (calling undefined externals) being dead-stripped to
287 // link correctly. Yes, there really is.
288 if (MMI->isUsedFunction(EHFrameInfo.function))
289 if (const char *UsedDirective = MAI->getUsedDirective())
290 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
296 /// SharedTypeIds - How many leading type ids two landing pads have in common.
297 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
298 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;
304 for (; Count != MinSize; ++Count)
305 if (LIds[Count] != RIds[Count])
311 /// PadLT - Order landing pads lexicographically by type id.
312 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
313 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
314 unsigned LSize = LIds.size(), RSize = RIds.size();
315 unsigned MinSize = LSize < RSize ? LSize : RSize;
317 for (unsigned i = 0; i != MinSize; ++i)
318 if (LIds[i] != RIds[i])
319 return LIds[i] < RIds[i];
321 return LSize < RSize;
324 /// ComputeActionsTable - Compute the actions table and gather the first action
325 /// index for each landing pad site.
326 unsigned DwarfException::
327 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
328 SmallVectorImpl<ActionEntry> &Actions,
329 SmallVectorImpl<unsigned> &FirstActions) {
331 // The action table follows the call-site table in the LSDA. The individual
332 // records are of two types:
335 // * Exception specification
337 // The two record kinds have the same format, with only small differences.
338 // They are distinguished by the "switch value" field: Catch clauses
339 // (TypeInfos) have strictly positive switch values, and exception
340 // specifications (FilterIds) have strictly negative switch values. Value 0
341 // indicates a catch-all clause.
343 // Negative type IDs index into FilterIds. Positive type IDs index into
344 // TypeInfos. The value written for a positive type ID is just the type ID
345 // itself. For a negative type ID, however, the value written is the
346 // (negative) byte offset of the corresponding FilterIds entry. The byte
347 // offset is usually equal to the type ID (because the FilterIds entries are
348 // written using a variable width encoding, which outputs one byte per entry
349 // as long as the value written is not too large) but can differ. This kind
350 // of complication does not occur for positive type IDs because type infos are
351 // output using a fixed width encoding. FilterOffsets[i] holds the byte
352 // offset corresponding to FilterIds[i].
354 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
355 SmallVector<int, 16> FilterOffsets;
356 FilterOffsets.reserve(FilterIds.size());
359 for (std::vector<unsigned>::const_iterator
360 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
361 FilterOffsets.push_back(Offset);
362 Offset -= MCAsmInfo::getULEB128Size(*I);
365 FirstActions.reserve(LandingPads.size());
368 unsigned SizeActions = 0;
369 const LandingPadInfo *PrevLPI = 0;
371 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
372 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
373 const LandingPadInfo *LPI = *I;
374 const std::vector<int> &TypeIds = LPI->TypeIds;
375 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
376 unsigned SizeSiteActions = 0;
378 if (NumShared < TypeIds.size()) {
379 unsigned SizeAction = 0;
380 ActionEntry *PrevAction = 0;
383 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
384 assert(Actions.size());
385 PrevAction = &Actions.back();
386 SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
387 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
389 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
391 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
392 SizeAction += -PrevAction->NextAction;
393 PrevAction = PrevAction->Previous;
397 // Compute the actions.
398 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
399 int TypeID = TypeIds[J];
400 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
401 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
402 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
404 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
405 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
406 SizeSiteActions += SizeAction;
408 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
409 Actions.push_back(Action);
410 PrevAction = &Actions.back();
413 // Record the first action of the landing pad site.
414 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
415 } // else identical - re-use previous FirstAction
417 // Information used when created the call-site table. The action record
418 // field of the call site record is the offset of the first associated
419 // action record, relative to the start of the actions table. This value is
420 // biased by 1 (1 in dicating the start of the actions table), and 0
421 // indicates that there are no actions.
422 FirstActions.push_back(FirstAction);
424 // Compute this sites contribution to size.
425 SizeActions += SizeSiteActions;
433 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
434 /// has a try-range containing the call, a non-zero landing pad, and an
435 /// appropriate action. The entry for an ordinary call has a try-range
436 /// containing the call and zero for the landing pad and the action. Calls
437 /// marked 'nounwind' have no entry and must not be contained in the try-range
438 /// of any entry - they form gaps in the table. Entries must be ordered by
439 /// try-range address.
440 void DwarfException::
441 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
442 const RangeMapType &PadMap,
443 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
444 const SmallVectorImpl<unsigned> &FirstActions) {
445 // The end label of the previous invoke or nounwind try-range.
446 unsigned LastLabel = 0;
448 // Whether there is a potentially throwing instruction (currently this means
449 // an ordinary call) between the end of the previous try-range and now.
450 bool SawPotentiallyThrowing = false;
452 // Whether the last CallSite entry was for an invoke.
453 bool PreviousIsInvoke = false;
455 // Visit all instructions in order of address.
456 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
458 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
460 if (!MI->isLabel()) {
461 SawPotentiallyThrowing |= MI->getDesc().isCall();
465 unsigned BeginLabel = MI->getOperand(0).getImm();
466 assert(BeginLabel && "Invalid label!");
468 // End of the previous try-range?
469 if (BeginLabel == LastLabel)
470 SawPotentiallyThrowing = false;
472 // Beginning of a new try-range?
473 RangeMapType::iterator L = PadMap.find(BeginLabel);
474 if (L == PadMap.end())
475 // Nope, it was just some random label.
478 const PadRange &P = L->second;
479 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
480 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
481 "Inconsistent landing pad map!");
483 // For Dwarf exception handling (SjLj handling doesn't use this). If some
484 // instruction between the previous try-range and this one may throw,
485 // create a call-site entry with no landing pad for the region between the
487 if (SawPotentiallyThrowing &&
488 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
489 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
490 CallSites.push_back(Site);
491 PreviousIsInvoke = false;
494 LastLabel = LandingPad->EndLabels[P.RangeIndex];
495 assert(BeginLabel && LastLabel && "Invalid landing pad!");
497 if (LandingPad->LandingPadLabel) {
498 // This try-range is for an invoke.
499 CallSiteEntry Site = {
502 LandingPad->LandingPadLabel,
503 FirstActions[P.PadIndex]
506 // Try to merge with the previous call-site. SJLJ doesn't do this
507 if (PreviousIsInvoke &&
508 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
509 CallSiteEntry &Prev = CallSites.back();
510 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
511 // Extend the range of the previous entry.
512 Prev.EndLabel = Site.EndLabel;
517 // Otherwise, create a new call-site.
518 CallSites.push_back(Site);
519 PreviousIsInvoke = true;
522 PreviousIsInvoke = false;
527 // If some instruction between the previous try-range and the end of the
528 // function may throw, create a call-site entry with no landing pad for the
529 // region following the try-range.
530 if (SawPotentiallyThrowing &&
531 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
532 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
533 CallSites.push_back(Site);
537 /// EmitExceptionTable - Emit landing pads and actions.
539 /// The general organization of the table is complex, but the basic concepts are
540 /// easy. First there is a header which describes the location and organization
541 /// of the three components that follow.
543 /// 1. The landing pad site information describes the range of code covered by
544 /// the try. In our case it's an accumulation of the ranges covered by the
545 /// invokes in the try. There is also a reference to the landing pad that
546 /// handles the exception once processed. Finally an index into the actions
548 /// 2. The action table, in our case, is composed of pairs of type IDs and next
549 /// action offset. Starting with the action index from the landing pad
550 /// site, each type ID is checked for a match to the current exception. If
551 /// it matches then the exception and type id are passed on to the landing
552 /// pad. Otherwise the next action is looked up. This chain is terminated
553 /// with a next action of zero. If no type id is found then the frame is
554 /// unwound and handling continues.
555 /// 3. Type ID table contains references to all the C++ typeinfo for all
556 /// catches in the function. This tables is reverse indexed base 1.
557 void DwarfException::EmitExceptionTable() {
558 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
559 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
560 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
561 if (PadInfos.empty()) return;
563 // Sort the landing pads in order of their type ids. This is used to fold
564 // duplicate actions.
565 SmallVector<const LandingPadInfo *, 64> LandingPads;
566 LandingPads.reserve(PadInfos.size());
568 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
569 LandingPads.push_back(&PadInfos[i]);
571 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
573 // Compute the actions table and gather the first action index for each
575 SmallVector<ActionEntry, 32> Actions;
576 SmallVector<unsigned, 64> FirstActions;
577 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions,
580 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
581 // by try-range labels when lowered). Ordinary calls do not, so appropriate
582 // try-ranges for them need be deduced when using DWARF exception handling.
584 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
585 const LandingPadInfo *LandingPad = LandingPads[i];
586 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
587 unsigned BeginLabel = LandingPad->BeginLabels[j];
588 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
589 PadRange P = { i, j };
590 PadMap[BeginLabel] = P;
594 // Compute the call-site table.
595 SmallVector<CallSiteEntry, 64> CallSites;
596 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
601 const unsigned SiteStartSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
602 const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
603 const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
604 bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
605 bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
611 SizeSites = CallSites.size() *
612 (SiteStartSize + SiteLengthSize + LandingPadSize);
614 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
615 SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
617 SizeSites += MCAsmInfo::getULEB128Size(i);
621 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
622 unsigned TTypeFormat;
623 unsigned TypeFormatSize;
626 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
627 // that we're omitting that bit.
628 TTypeFormat = dwarf::DW_EH_PE_omit;
629 TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
631 // Okay, we have actual filters or typeinfos to emit. As such, we need to
632 // pick a type encoding for them. We're about to emit a list of pointers to
633 // typeinfo objects at the end of the LSDA. However, unless we're in static
634 // mode, this reference will require a relocation by the dynamic linker.
636 // Because of this, we have a couple of options:
638 // 1) If we are in -static mode, we can always use an absolute reference
639 // from the LSDA, because the static linker will resolve it.
641 // 2) Otherwise, if the LSDA section is writable, we can output the direct
642 // reference to the typeinfo and allow the dynamic linker to relocate
643 // it. Since it is in a writable section, the dynamic linker won't
646 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
647 // we need to use some form of indirection. For example, on Darwin,
648 // we can output a statically-relocatable reference to a dyld stub. The
649 // offset to the stub is constant, but the contents are in a section
650 // that is updated by the dynamic linker. This is easy enough, but we
651 // need to tell the personality function of the unwinder to indirect
652 // through the dyld stub.
654 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
655 // somewhere. This predicate should be moved to a shared location that is
656 // in target-independent code.
658 if (LSDASection->getKind().isWriteable() ||
659 Asm->TM.getRelocationModel() == Reloc::Static)
660 TTypeFormat = dwarf::DW_EH_PE_absptr;
662 TTypeFormat = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
663 dwarf::DW_EH_PE_sdata4;
665 TypeFormatSize = SizeOfEncodedValue(TTypeFormat);
668 // Begin the exception table.
669 Asm->OutStreamer.SwitchSection(LSDASection);
670 Asm->EmitAlignment(2, 0, 0, false);
672 O << "GCC_except_table" << SubprogramCount << ":\n";
674 // The type infos need to be aligned. GCC does this by inserting padding just
675 // before the type infos. However, this changes the size of the exception
676 // table, so you need to take this into account when you output the exception
677 // table size. However, the size is output using a variable length encoding.
678 // So by increasing the size by inserting padding, you may increase the number
679 // of bytes used for writing the size. If it increases, say by one byte, then
680 // you now need to output one less byte of padding to get the type infos
681 // aligned. However this decreases the size of the exception table. This
682 // changes the value you have to output for the exception table size. Due to
683 // the variable length encoding, the number of bytes used for writing the
684 // length may decrease. If so, you then have to increase the amount of
685 // padding. And so on. If you look carefully at the GCC code you will see that
686 // it indeed does this in a loop, going on and on until the values stabilize.
687 // We chose another solution: don't output padding inside the table like GCC
688 // does, instead output it before the table.
689 unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
690 unsigned TyOffset = sizeof(int8_t) + // Call site format
691 MCAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
692 SizeSites + SizeActions + SizeTypes;
693 unsigned TotalSize = sizeof(int8_t) + // LPStart format
694 sizeof(int8_t) + // TType format
696 MCAsmInfo::getULEB128Size(TyOffset) : 0) + // TType base offset
698 unsigned SizeAlign = (4 - TotalSize) & 3;
700 for (unsigned i = 0; i != SizeAlign; ++i) {
705 EmitLabel("exception", SubprogramCount);
708 SmallString<16> LSDAName;
709 raw_svector_ostream(LSDAName) << MAI->getPrivateGlobalPrefix() <<
710 "_LSDA_" << Asm->getFunctionNumber();
711 O << LSDAName.str() << ":\n";
715 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
716 Asm->EOL("@LPStart format", dwarf::DW_EH_PE_omit);
718 Asm->EmitInt8(TTypeFormat);
719 Asm->EOL("@TType format", TTypeFormat);
722 Asm->EmitULEB128Bytes(TyOffset);
723 Asm->EOL("@TType base offset");
726 // SjLj Exception handling
728 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
729 Asm->EOL("Call site format", dwarf::DW_EH_PE_udata4);
730 Asm->EmitULEB128Bytes(SizeSites);
731 Asm->EOL("Call site table length");
733 // Emit the landing pad site information.
735 for (SmallVectorImpl<CallSiteEntry>::const_iterator
736 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
737 const CallSiteEntry &S = *I;
739 // Offset of the landing pad, counted in 16-byte bundles relative to the
741 Asm->EmitULEB128Bytes(idx);
742 Asm->EOL("Landing pad");
744 // Offset of the first associated action record, relative to the start of
745 // the action table. This value is biased by 1 (1 indicates the start of
746 // the action table), and 0 indicates that there are no actions.
747 Asm->EmitULEB128Bytes(S.Action);
751 // DWARF Exception handling
752 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
754 // The call-site table is a list of all call sites that may throw an
755 // exception (including C++ 'throw' statements) in the procedure
756 // fragment. It immediately follows the LSDA header. Each entry indicates,
757 // for a given call, the first corresponding action record and corresponding
760 // The table begins with the number of bytes, stored as an LEB128
761 // compressed, unsigned integer. The records immediately follow the record
762 // count. They are sorted in increasing call-site address. Each record
765 // * The position of the call-site.
766 // * The position of the landing pad.
767 // * The first action record for that call site.
769 // A missing entry in the call-site table indicates that a call is not
770 // supposed to throw.
772 // Emit the landing pad call site table.
773 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
774 Asm->EOL("Call site format", dwarf::DW_EH_PE_udata4);
775 Asm->EmitULEB128Bytes(SizeSites);
776 Asm->EOL("Call site table size");
778 for (SmallVectorImpl<CallSiteEntry>::const_iterator
779 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
780 const CallSiteEntry &S = *I;
781 const char *BeginTag;
782 unsigned BeginNumber;
785 BeginTag = "eh_func_begin";
786 BeginNumber = SubprogramCount;
789 BeginNumber = S.BeginLabel;
792 // Offset of the call site relative to the previous call site, counted in
793 // number of 16-byte bundles. The first call site is counted relative to
794 // the start of the procedure fragment.
795 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
797 Asm->EOL("Region start");
800 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
803 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
805 Asm->EOL("Region length");
807 // Offset of the landing pad, counted in 16-byte bundles relative to the
812 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
815 Asm->EOL("Landing pad");
817 // Offset of the first associated action record, relative to the start of
818 // the action table. This value is biased by 1 (1 indicates the start of
819 // the action table), and 0 indicates that there are no actions.
820 Asm->EmitULEB128Bytes(S.Action);
825 // Emit the Action Table.
826 for (SmallVectorImpl<ActionEntry>::const_iterator
827 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
828 const ActionEntry &Action = *I;
832 // Used by the runtime to match the type of the thrown exception to the
833 // type of the catch clauses or the types in the exception specification.
835 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
836 Asm->EOL("TypeInfo index");
840 // Self-relative signed displacement in bytes of the next action record,
841 // or 0 if there is no next action record.
843 Asm->EmitSLEB128Bytes(Action.NextAction);
844 Asm->EOL("Next action");
847 // Emit the Catch Clauses. The code for the catch clauses following the same
848 // try is similar to a switch statement. The catch clause action record
849 // informs the runtime about the type of a catch clause and about the
850 // associated switch value.
852 // Action Record Fields:
855 // Positive value, starting at 1. Index in the types table of the
856 // __typeinfo for the catch-clause type. 1 is the first word preceding
857 // TTBase, 2 is the second word, and so on. Used by the runtime to check
858 // if the thrown exception type matches the catch-clause type. Back-end
859 // generated switch statements check against this value.
862 // Signed offset, in bytes from the start of this field, to the next
863 // chained action record, or zero if none.
865 // The order of the action records determined by the next field is the order
866 // of the catch clauses as they appear in the source code, and must be kept in
867 // the same order. As a result, changing the order of the catch clause would
868 // change the semantics of the program.
869 for (std::vector<GlobalVariable *>::const_reverse_iterator
870 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
871 const GlobalVariable *GV = *I;
875 O << Asm->Mang->getMangledName(GV);
880 Asm->EOL("TypeInfo");
883 // Emit the Type Table.
884 for (std::vector<unsigned>::const_iterator
885 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
886 unsigned TypeID = *I;
887 Asm->EmitULEB128Bytes(TypeID);
888 Asm->EOL("Filter TypeInfo index");
891 Asm->EmitAlignment(2, 0, 0, false);
894 /// EndModule - Emit all exception information that should come after the
896 void DwarfException::EndModule() {
897 if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
900 if (!shouldEmitMovesModule && !shouldEmitTableModule)
903 if (TimePassesIsEnabled)
904 ExceptionTimer->startTimer();
906 const std::vector<Function *> Personalities = MMI->getPersonalities();
908 for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
909 EmitCIE(Personalities[I], I);
911 for (std::vector<FunctionEHFrameInfo>::iterator
912 I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
915 if (TimePassesIsEnabled)
916 ExceptionTimer->stopTimer();
919 /// BeginFunction - Gather pre-function exception information. Assumes it's
920 /// being emitted immediately after the function entry point.
921 void DwarfException::BeginFunction(MachineFunction *MF) {
922 if (!MMI || !MAI->doesSupportExceptionHandling()) return;
924 if (TimePassesIsEnabled)
925 ExceptionTimer->startTimer();
928 shouldEmitTable = shouldEmitMoves = false;
930 // Map all labels and get rid of any dead landing pads.
931 MMI->TidyLandingPads();
933 // If any landing pads survive, we need an EH table.
934 if (!MMI->getLandingPads().empty())
935 shouldEmitTable = true;
937 // See if we need frame move info.
938 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
939 shouldEmitMoves = true;
941 if (shouldEmitMoves || shouldEmitTable)
942 // Assumes in correct section after the entry point.
943 EmitLabel("eh_func_begin", ++SubprogramCount);
945 shouldEmitTableModule |= shouldEmitTable;
946 shouldEmitMovesModule |= shouldEmitMoves;
948 if (TimePassesIsEnabled)
949 ExceptionTimer->stopTimer();
952 /// EndFunction - Gather and emit post-function exception information.
954 void DwarfException::EndFunction() {
955 if (!shouldEmitMoves && !shouldEmitTable) return;
957 if (TimePassesIsEnabled)
958 ExceptionTimer->startTimer();
960 EmitLabel("eh_func_end", SubprogramCount);
961 EmitExceptionTable();
963 // Save EH frame information
964 EHFrames.push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
966 MMI->getPersonalityIndex(),
967 MF->getFrameInfo()->hasCalls(),
968 !MMI->getLandingPads().empty(),
969 MMI->getFrameMoves(),
972 // Record if this personality index uses a landing pad.
973 UsesLSDA[MMI->getPersonalityIndex()] |= !MMI->getLandingPads().empty();
975 if (TimePassesIsEnabled)
976 ExceptionTimer->stopTimer();