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/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/Target/TargetData.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Target/TargetLoweringObjectFile.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringExtras.h"
38 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
40 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
41 shouldEmitTableModule(false), shouldEmitMovesModule(false),
43 if (TimePassesIsEnabled)
44 ExceptionTimer = new Timer("DWARF Exception Writer");
47 DwarfException::~DwarfException() {
48 delete ExceptionTimer;
51 /// SizeOfEncodedValue - Return the size of the encoding in bytes.
52 unsigned DwarfException::SizeOfEncodedValue(unsigned Encoding) {
53 if (Encoding == dwarf::DW_EH_PE_omit)
56 switch (Encoding & 0x07) {
57 case dwarf::DW_EH_PE_absptr:
58 return TD->getPointerSize();
59 case dwarf::DW_EH_PE_udata2:
61 case dwarf::DW_EH_PE_udata4:
63 case dwarf::DW_EH_PE_udata8:
67 assert(0 && "Invalid encoded value.");
71 /// CreateLabelDiff - Emit a label and subtract it from the expression we
72 /// already have. This is equivalent to emitting "foo - .", but we have to emit
73 /// the label for "." directly.
74 const MCExpr *DwarfException::CreateLabelDiff(const MCExpr *ExprRef,
75 const char *LabelName,
78 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
79 << LabelName << Asm->getFunctionNumber()
81 MCSymbol *DotSym = Asm->OutContext.GetOrCreateSymbol(Name.str());
82 Asm->OutStreamer.EmitLabel(DotSym);
84 return MCBinaryExpr::CreateSub(ExprRef,
85 MCSymbolRefExpr::Create(DotSym,
90 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
91 /// is shared among many Frame Description Entries. There is at least one CIE
92 /// in every non-empty .debug_frame section.
93 void DwarfException::EmitCIE(const Function *PersonalityFn, unsigned Index) {
94 // Size and sign of stack growth.
96 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
97 TargetFrameInfo::StackGrowsUp ?
98 TD->getPointerSize() : -TD->getPointerSize();
100 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
102 // Begin eh frame section.
103 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
105 if (MAI->is_EHSymbolPrivate())
106 O << MAI->getPrivateGlobalPrefix();
107 O << "EH_frame" << Index << ":\n";
109 EmitLabel("section_eh_frame", Index);
111 // Define base labels.
112 EmitLabel("eh_frame_common", Index);
114 // Define the eh frame length.
115 EmitDifference("eh_frame_common_end", Index,
116 "eh_frame_common_begin", Index, true);
117 Asm->EOL("Length of Common Information Entry");
120 EmitLabel("eh_frame_common_begin", Index);
121 Asm->EmitInt32((int)0);
122 Asm->EOL("CIE Identifier Tag");
123 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
124 Asm->EOL("CIE Version");
126 // The personality presence indicates that language specific information will
127 // show up in the eh frame. Find out how we are supposed to lower the
128 // personality function reference:
129 const MCExpr *PersonalityRef = 0;
130 bool IsPersonalityIndirect = false, IsPersonalityPCRel = false;
132 // FIXME: HANDLE STATIC CODEGEN MODEL HERE.
134 // In non-static mode, ask the object file how to represent this reference.
136 TLOF.getSymbolForDwarfGlobalReference(PersonalityFn, Asm->Mang,
138 IsPersonalityIndirect,
142 unsigned PerEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
143 if (IsPersonalityIndirect)
144 PerEncoding |= dwarf::DW_EH_PE_indirect;
145 unsigned LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
146 unsigned FDEEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
148 char Augmentation[5] = { 0 };
149 unsigned AugmentationSize = 0;
150 char *APtr = Augmentation + 1;
152 if (PersonalityRef) {
153 // There is a personality function.
155 AugmentationSize += 1 + SizeOfEncodedValue(PerEncoding);
158 if (UsesLSDA[Index]) {
159 // An LSDA pointer is in the FDE augmentation.
164 if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
165 // A non-default pointer encoding for the FDE.
170 if (APtr != Augmentation + 1)
171 Augmentation[0] = 'z';
173 Asm->EmitString(Augmentation);
174 Asm->EOL("CIE Augmentation");
177 Asm->EmitULEB128Bytes(1);
178 Asm->EOL("CIE Code Alignment Factor");
179 Asm->EmitSLEB128Bytes(stackGrowth);
180 Asm->EOL("CIE Data Alignment Factor");
181 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
182 Asm->EOL("CIE Return Address Column");
184 Asm->EmitULEB128Bytes(AugmentationSize);
185 Asm->EOL("Augmentation Size");
187 Asm->EmitInt8(PerEncoding);
188 Asm->EOL("Personality", PerEncoding);
190 // If there is a personality, we need to indicate the function's location.
191 if (PersonalityRef) {
192 if (!IsPersonalityPCRel)
193 PersonalityRef = CreateLabelDiff(PersonalityRef, "personalityref_addr",
196 O << MAI->getData32bitsDirective();
197 PersonalityRef->print(O, MAI);
198 Asm->EOL("Personality");
200 Asm->EmitInt8(LSDAEncoding);
201 Asm->EOL("LSDA Encoding", LSDAEncoding);
203 Asm->EmitInt8(FDEEncoding);
204 Asm->EOL("FDE Encoding", FDEEncoding);
207 // Indicate locations of general callee saved registers in frame.
208 std::vector<MachineMove> Moves;
209 RI->getInitialFrameState(Moves);
210 EmitFrameMoves(NULL, 0, Moves, true);
212 // On Darwin the linker honors the alignment of eh_frame, which means it must
213 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
214 // holes which confuse readers of eh_frame.
215 Asm->EmitAlignment(TD->getPointerSize() == 4 ? 2 : 3, 0, 0, false);
216 EmitLabel("eh_frame_common_end", Index);
221 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
222 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
223 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
224 "Should not emit 'available externally' functions at all");
226 const Function *TheFunc = EHFrameInfo.function;
228 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
230 // Externally visible entry into the functions eh frame info. If the
231 // corresponding function is static, this should not be externally visible.
232 if (!TheFunc->hasLocalLinkage())
233 if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
234 O << GlobalEHDirective << EHFrameInfo.FnName << '\n';
236 // If corresponding function is weak definition, this should be too.
237 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
238 O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << '\n';
240 // If corresponding function is hidden, this should be too.
241 if (TheFunc->hasHiddenVisibility())
242 if (const char *HiddenDirective = MAI->getHiddenDirective())
243 O << HiddenDirective << EHFrameInfo.FnName << '\n' ;
245 // If there are no calls then you can't unwind. This may mean we can omit the
246 // EH Frame, but some environments do not handle weak absolute symbols. If
247 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
248 // info is to be available for non-EH uses.
249 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
250 (!TheFunc->isWeakForLinker() ||
251 !MAI->getWeakDefDirective() ||
252 MAI->getSupportsWeakOmittedEHFrame())) {
253 O << EHFrameInfo.FnName << " = 0\n";
254 // This name has no connection to the function, so it might get
255 // dead-stripped when the function is not, erroneously. Prohibit
256 // dead-stripping unconditionally.
257 if (const char *UsedDirective = MAI->getUsedDirective())
258 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
260 O << EHFrameInfo.FnName << ":\n";
263 EmitDifference("eh_frame_end", EHFrameInfo.Number,
264 "eh_frame_begin", EHFrameInfo.Number, true);
265 Asm->EOL("Length of Frame Information Entry");
267 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
269 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
270 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
273 Asm->EOL("FDE CIE offset");
275 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
276 Asm->EOL("FDE initial location");
277 EmitDifference("eh_func_end", EHFrameInfo.Number,
278 "eh_func_begin", EHFrameInfo.Number, true);
279 Asm->EOL("FDE address range");
281 // If there is a personality and landing pads then point to the language
282 // specific data area in the exception table.
283 if (MMI->getPersonalities()[0] != NULL) {
284 bool is4Byte = TD->getPointerSize() == sizeof(int32_t);
286 Asm->EmitULEB128Bytes(is4Byte ? 4 : 8);
287 Asm->EOL("Augmentation size");
289 if (EHFrameInfo.hasLandingPads)
290 EmitReference("exception", EHFrameInfo.Number, true, false);
293 Asm->EmitInt32((int)0);
295 Asm->EmitInt64((int)0);
297 Asm->EOL("Language Specific Data Area");
299 Asm->EmitULEB128Bytes(0);
300 Asm->EOL("Augmentation size");
303 // Indicate locations of function specific callee saved registers in frame.
304 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
307 // On Darwin the linker honors the alignment of eh_frame, which means it
308 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
309 // get holes which confuse readers of eh_frame.
310 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
312 EmitLabel("eh_frame_end", EHFrameInfo.Number);
314 // If the function is marked used, this table should be also. We cannot
315 // make the mark unconditional in this case, since retaining the table also
316 // retains the function in this case, and there is code around that depends
317 // on unused functions (calling undefined externals) being dead-stripped to
318 // link correctly. Yes, there really is.
319 if (MMI->isUsedFunction(EHFrameInfo.function))
320 if (const char *UsedDirective = MAI->getUsedDirective())
321 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
327 /// SharedTypeIds - How many leading type ids two landing pads have in common.
328 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
329 const LandingPadInfo *R) {
330 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
331 unsigned LSize = LIds.size(), RSize = RIds.size();
332 unsigned MinSize = LSize < RSize ? LSize : RSize;
335 for (; Count != MinSize; ++Count)
336 if (LIds[Count] != RIds[Count])
342 /// PadLT - Order landing pads lexicographically by type id.
343 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
344 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
345 unsigned LSize = LIds.size(), RSize = RIds.size();
346 unsigned MinSize = LSize < RSize ? LSize : RSize;
348 for (unsigned i = 0; i != MinSize; ++i)
349 if (LIds[i] != RIds[i])
350 return LIds[i] < RIds[i];
352 return LSize < RSize;
355 /// ComputeActionsTable - Compute the actions table and gather the first action
356 /// index for each landing pad site.
357 unsigned DwarfException::
358 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
359 SmallVectorImpl<ActionEntry> &Actions,
360 SmallVectorImpl<unsigned> &FirstActions) {
362 // The action table follows the call-site table in the LSDA. The individual
363 // records are of two types:
366 // * Exception specification
368 // The two record kinds have the same format, with only small differences.
369 // They are distinguished by the "switch value" field: Catch clauses
370 // (TypeInfos) have strictly positive switch values, and exception
371 // specifications (FilterIds) have strictly negative switch values. Value 0
372 // indicates a catch-all clause.
374 // Negative type IDs index into FilterIds. Positive type IDs index into
375 // TypeInfos. The value written for a positive type ID is just the type ID
376 // itself. For a negative type ID, however, the value written is the
377 // (negative) byte offset of the corresponding FilterIds entry. The byte
378 // offset is usually equal to the type ID (because the FilterIds entries are
379 // written using a variable width encoding, which outputs one byte per entry
380 // as long as the value written is not too large) but can differ. This kind
381 // of complication does not occur for positive type IDs because type infos are
382 // output using a fixed width encoding. FilterOffsets[i] holds the byte
383 // offset corresponding to FilterIds[i].
385 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
386 SmallVector<int, 16> FilterOffsets;
387 FilterOffsets.reserve(FilterIds.size());
390 for (std::vector<unsigned>::const_iterator
391 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
392 FilterOffsets.push_back(Offset);
393 Offset -= MCAsmInfo::getULEB128Size(*I);
396 FirstActions.reserve(LandingPads.size());
399 unsigned SizeActions = 0;
400 const LandingPadInfo *PrevLPI = 0;
402 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
403 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
404 const LandingPadInfo *LPI = *I;
405 const std::vector<int> &TypeIds = LPI->TypeIds;
406 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
407 unsigned SizeSiteActions = 0;
409 if (NumShared < TypeIds.size()) {
410 unsigned SizeAction = 0;
411 ActionEntry *PrevAction = 0;
414 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
415 assert(Actions.size());
416 PrevAction = &Actions.back();
417 SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
418 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
420 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
422 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
423 SizeAction += -PrevAction->NextAction;
424 PrevAction = PrevAction->Previous;
428 // Compute the actions.
429 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
430 int TypeID = TypeIds[J];
431 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
432 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
433 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
435 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
436 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
437 SizeSiteActions += SizeAction;
439 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
440 Actions.push_back(Action);
441 PrevAction = &Actions.back();
444 // Record the first action of the landing pad site.
445 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
446 } // else identical - re-use previous FirstAction
448 // Information used when created the call-site table. The action record
449 // field of the call site record is the offset of the first associated
450 // action record, relative to the start of the actions table. This value is
451 // biased by 1 (1 in dicating the start of the actions table), and 0
452 // indicates that there are no actions.
453 FirstActions.push_back(FirstAction);
455 // Compute this sites contribution to size.
456 SizeActions += SizeSiteActions;
464 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
465 /// marked `nounwind'. Return `false' otherwise.
466 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
467 assert(MI->getDesc().isCall() && "This should be a call instruction!");
469 bool MarkedNoUnwind = false;
470 bool SawFunc = false;
472 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
473 const MachineOperand &MO = MI->getOperand(I);
476 if (Function *F = dyn_cast<Function>(MO.getGlobal())) {
478 // Be conservative. If we have more than one function operand for this
479 // call, then we can't make the assumption that it's the callee and
480 // not a parameter to the call.
482 // FIXME: Determine if there's a way to say that `F' is the callee or
484 MarkedNoUnwind = false;
488 MarkedNoUnwind = F->doesNotThrow();
494 return MarkedNoUnwind;
497 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
498 /// has a try-range containing the call, a non-zero landing pad, and an
499 /// appropriate action. The entry for an ordinary call has a try-range
500 /// containing the call and zero for the landing pad and the action. Calls
501 /// marked 'nounwind' have no entry and must not be contained in the try-range
502 /// of any entry - they form gaps in the table. Entries must be ordered by
503 /// try-range address.
504 void DwarfException::
505 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
506 const RangeMapType &PadMap,
507 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
508 const SmallVectorImpl<unsigned> &FirstActions) {
509 // The end label of the previous invoke or nounwind try-range.
510 unsigned LastLabel = 0;
512 // Whether there is a potentially throwing instruction (currently this means
513 // an ordinary call) between the end of the previous try-range and now.
514 bool SawPotentiallyThrowing = false;
516 // Whether the last CallSite entry was for an invoke.
517 bool PreviousIsInvoke = false;
519 // Visit all instructions in order of address.
520 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
522 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
524 if (!MI->isLabel()) {
525 if (MI->getDesc().isCall())
526 SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
531 unsigned BeginLabel = MI->getOperand(0).getImm();
532 assert(BeginLabel && "Invalid label!");
534 // End of the previous try-range?
535 if (BeginLabel == LastLabel)
536 SawPotentiallyThrowing = false;
538 // Beginning of a new try-range?
539 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
540 if (L == PadMap.end())
541 // Nope, it was just some random label.
544 const PadRange &P = L->second;
545 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
546 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
547 "Inconsistent landing pad map!");
549 // For Dwarf exception handling (SjLj handling doesn't use this). If some
550 // instruction between the previous try-range and this one may throw,
551 // create a call-site entry with no landing pad for the region between the
553 if (SawPotentiallyThrowing &&
554 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
555 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
556 CallSites.push_back(Site);
557 PreviousIsInvoke = false;
560 LastLabel = LandingPad->EndLabels[P.RangeIndex];
561 assert(BeginLabel && LastLabel && "Invalid landing pad!");
563 if (LandingPad->LandingPadLabel) {
564 // This try-range is for an invoke.
565 CallSiteEntry Site = {
568 LandingPad->LandingPadLabel,
569 FirstActions[P.PadIndex]
572 // Try to merge with the previous call-site. SJLJ doesn't do this
573 if (PreviousIsInvoke &&
574 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
575 CallSiteEntry &Prev = CallSites.back();
576 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
577 // Extend the range of the previous entry.
578 Prev.EndLabel = Site.EndLabel;
583 // Otherwise, create a new call-site.
584 CallSites.push_back(Site);
585 PreviousIsInvoke = true;
588 PreviousIsInvoke = false;
593 // If some instruction between the previous try-range and the end of the
594 // function may throw, create a call-site entry with no landing pad for the
595 // region following the try-range.
596 if (SawPotentiallyThrowing &&
597 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
598 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
599 CallSites.push_back(Site);
603 /// EmitExceptionTable - Emit landing pads and actions.
605 /// The general organization of the table is complex, but the basic concepts are
606 /// easy. First there is a header which describes the location and organization
607 /// of the three components that follow.
609 /// 1. The landing pad site information describes the range of code covered by
610 /// the try. In our case it's an accumulation of the ranges covered by the
611 /// invokes in the try. There is also a reference to the landing pad that
612 /// handles the exception once processed. Finally an index into the actions
614 /// 2. The action table, in our case, is composed of pairs of type IDs and next
615 /// action offset. Starting with the action index from the landing pad
616 /// site, each type ID is checked for a match to the current exception. If
617 /// it matches then the exception and type id are passed on to the landing
618 /// pad. Otherwise the next action is looked up. This chain is terminated
619 /// with a next action of zero. If no type id is found then the frame is
620 /// unwound and handling continues.
621 /// 3. Type ID table contains references to all the C++ typeinfo for all
622 /// catches in the function. This tables is reverse indexed base 1.
623 void DwarfException::EmitExceptionTable() {
624 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
625 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
626 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
627 if (PadInfos.empty()) return;
629 // Sort the landing pads in order of their type ids. This is used to fold
630 // duplicate actions.
631 SmallVector<const LandingPadInfo *, 64> LandingPads;
632 LandingPads.reserve(PadInfos.size());
634 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
635 LandingPads.push_back(&PadInfos[i]);
637 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
639 // Compute the actions table and gather the first action index for each
641 SmallVector<ActionEntry, 32> Actions;
642 SmallVector<unsigned, 64> FirstActions;
643 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions,
646 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
647 // by try-range labels when lowered). Ordinary calls do not, so appropriate
648 // try-ranges for them need be deduced when using DWARF exception handling.
650 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
651 const LandingPadInfo *LandingPad = LandingPads[i];
652 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
653 unsigned BeginLabel = LandingPad->BeginLabels[j];
654 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
655 PadRange P = { i, j };
656 PadMap[BeginLabel] = P;
660 // Compute the call-site table.
661 SmallVector<CallSiteEntry, 64> CallSites;
662 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
667 const unsigned SiteStartSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
668 const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
669 const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
670 bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
671 bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
677 SizeSites = CallSites.size() *
678 (SiteStartSize + SiteLengthSize + LandingPadSize);
680 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
681 SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
683 SizeSites += MCAsmInfo::getULEB128Size(i);
687 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
688 unsigned TTypeFormat;
689 unsigned TypeFormatSize;
692 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
693 // that we're omitting that bit.
694 TTypeFormat = dwarf::DW_EH_PE_omit;
695 TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
697 // Okay, we have actual filters or typeinfos to emit. As such, we need to
698 // pick a type encoding for them. We're about to emit a list of pointers to
699 // typeinfo objects at the end of the LSDA. However, unless we're in static
700 // mode, this reference will require a relocation by the dynamic linker.
702 // Because of this, we have a couple of options:
704 // 1) If we are in -static mode, we can always use an absolute reference
705 // from the LSDA, because the static linker will resolve it.
707 // 2) Otherwise, if the LSDA section is writable, we can output the direct
708 // reference to the typeinfo and allow the dynamic linker to relocate
709 // it. Since it is in a writable section, the dynamic linker won't
712 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
713 // we need to use some form of indirection. For example, on Darwin,
714 // we can output a statically-relocatable reference to a dyld stub. The
715 // offset to the stub is constant, but the contents are in a section
716 // that is updated by the dynamic linker. This is easy enough, but we
717 // need to tell the personality function of the unwinder to indirect
718 // through the dyld stub.
720 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
721 // somewhere. This predicate should be moved to a shared location that is
722 // in target-independent code.
724 if (LSDASection->getKind().isWriteable() ||
725 Asm->TM.getRelocationModel() == Reloc::Static)
726 TTypeFormat = dwarf::DW_EH_PE_absptr;
728 TTypeFormat = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
729 dwarf::DW_EH_PE_sdata4;
731 TypeFormatSize = SizeOfEncodedValue(TTypeFormat);
734 // Begin the exception table.
735 Asm->OutStreamer.SwitchSection(LSDASection);
736 Asm->EmitAlignment(2, 0, 0, false);
738 O << "GCC_except_table" << SubprogramCount << ":\n";
740 // The type infos need to be aligned. GCC does this by inserting padding just
741 // before the type infos. However, this changes the size of the exception
742 // table, so you need to take this into account when you output the exception
743 // table size. However, the size is output using a variable length encoding.
744 // So by increasing the size by inserting padding, you may increase the number
745 // of bytes used for writing the size. If it increases, say by one byte, then
746 // you now need to output one less byte of padding to get the type infos
747 // aligned. However this decreases the size of the exception table. This
748 // changes the value you have to output for the exception table size. Due to
749 // the variable length encoding, the number of bytes used for writing the
750 // length may decrease. If so, you then have to increase the amount of
751 // padding. And so on. If you look carefully at the GCC code you will see that
752 // it indeed does this in a loop, going on and on until the values stabilize.
753 // We chose another solution: don't output padding inside the table like GCC
754 // does, instead output it before the table.
755 unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
756 unsigned TyOffset = sizeof(int8_t) + // Call site format
757 MCAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
758 SizeSites + SizeActions + SizeTypes;
759 unsigned TotalSize = sizeof(int8_t) + // LPStart format
760 sizeof(int8_t) + // TType format
762 MCAsmInfo::getULEB128Size(TyOffset) : 0) + // TType base offset
764 unsigned SizeAlign = (4 - TotalSize) & 3;
766 for (unsigned i = 0; i != SizeAlign; ++i) {
771 EmitLabel("exception", SubprogramCount);
774 SmallString<16> LSDAName;
775 raw_svector_ostream(LSDAName) << MAI->getPrivateGlobalPrefix() <<
776 "_LSDA_" << Asm->getFunctionNumber();
777 O << LSDAName.str() << ":\n";
781 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
782 Asm->EOL("@LPStart format", dwarf::DW_EH_PE_omit);
784 Asm->EmitInt8(TTypeFormat);
785 Asm->EOL("@TType format", TTypeFormat);
788 Asm->EmitULEB128Bytes(TyOffset);
789 Asm->EOL("@TType base offset");
792 // SjLj Exception handling
794 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
795 Asm->EOL("Call site format", dwarf::DW_EH_PE_udata4);
796 Asm->EmitULEB128Bytes(SizeSites);
797 Asm->EOL("Call site table length");
799 // Emit the landing pad site information.
801 for (SmallVectorImpl<CallSiteEntry>::const_iterator
802 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
803 const CallSiteEntry &S = *I;
805 // Offset of the landing pad, counted in 16-byte bundles relative to the
807 Asm->EmitULEB128Bytes(idx);
808 Asm->EOL("Landing pad");
810 // Offset of the first associated action record, relative to the start of
811 // the action table. This value is biased by 1 (1 indicates the start of
812 // the action table), and 0 indicates that there are no actions.
813 Asm->EmitULEB128Bytes(S.Action);
817 // DWARF Exception handling
818 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
820 // The call-site table is a list of all call sites that may throw an
821 // exception (including C++ 'throw' statements) in the procedure
822 // fragment. It immediately follows the LSDA header. Each entry indicates,
823 // for a given call, the first corresponding action record and corresponding
826 // The table begins with the number of bytes, stored as an LEB128
827 // compressed, unsigned integer. The records immediately follow the record
828 // count. They are sorted in increasing call-site address. Each record
831 // * The position of the call-site.
832 // * The position of the landing pad.
833 // * The first action record for that call site.
835 // A missing entry in the call-site table indicates that a call is not
836 // supposed to throw.
838 // Emit the landing pad call site table.
839 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
840 Asm->EOL("Call site format", dwarf::DW_EH_PE_udata4);
841 Asm->EmitULEB128Bytes(SizeSites);
842 Asm->EOL("Call site table size");
844 for (SmallVectorImpl<CallSiteEntry>::const_iterator
845 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
846 const CallSiteEntry &S = *I;
847 const char *BeginTag;
848 unsigned BeginNumber;
851 BeginTag = "eh_func_begin";
852 BeginNumber = SubprogramCount;
855 BeginNumber = S.BeginLabel;
858 // Offset of the call site relative to the previous call site, counted in
859 // number of 16-byte bundles. The first call site is counted relative to
860 // the start of the procedure fragment.
861 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
863 Asm->EOL("Region start");
866 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
869 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
871 Asm->EOL("Region length");
873 // Offset of the landing pad, counted in 16-byte bundles relative to the
878 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
881 Asm->EOL("Landing pad");
883 // Offset of the first associated action record, relative to the start of
884 // the action table. This value is biased by 1 (1 indicates the start of
885 // the action table), and 0 indicates that there are no actions.
886 Asm->EmitULEB128Bytes(S.Action);
891 // Emit the Action Table.
892 for (SmallVectorImpl<ActionEntry>::const_iterator
893 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
894 const ActionEntry &Action = *I;
898 // Used by the runtime to match the type of the thrown exception to the
899 // type of the catch clauses or the types in the exception specification.
901 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
902 Asm->EOL("TypeInfo index");
906 // Self-relative signed displacement in bytes of the next action record,
907 // or 0 if there is no next action record.
909 Asm->EmitSLEB128Bytes(Action.NextAction);
910 Asm->EOL("Next action");
913 // Emit the Catch TypeInfos.
914 for (std::vector<GlobalVariable *>::const_reverse_iterator
915 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
916 const GlobalVariable *GV = *I;
920 O << Asm->Mang->getMangledName(GV);
925 Asm->EOL("TypeInfo");
928 // Emit the Exception Specifications.
929 for (std::vector<unsigned>::const_iterator
930 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
931 unsigned TypeID = *I;
932 Asm->EmitULEB128Bytes(TypeID);
934 Asm->EOL("Exception specification");
939 Asm->EmitAlignment(2, 0, 0, false);
942 /// EndModule - Emit all exception information that should come after the
944 void DwarfException::EndModule() {
945 if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
948 if (!shouldEmitMovesModule && !shouldEmitTableModule)
951 if (TimePassesIsEnabled)
952 ExceptionTimer->startTimer();
954 const std::vector<Function *> Personalities = MMI->getPersonalities();
956 for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
957 EmitCIE(Personalities[I], I);
959 for (std::vector<FunctionEHFrameInfo>::iterator
960 I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
963 if (TimePassesIsEnabled)
964 ExceptionTimer->stopTimer();
967 /// BeginFunction - Gather pre-function exception information. Assumes it's
968 /// being emitted immediately after the function entry point.
969 void DwarfException::BeginFunction(MachineFunction *MF) {
970 if (!MMI || !MAI->doesSupportExceptionHandling()) return;
972 if (TimePassesIsEnabled)
973 ExceptionTimer->startTimer();
976 shouldEmitTable = shouldEmitMoves = false;
978 // Map all labels and get rid of any dead landing pads.
979 MMI->TidyLandingPads();
981 // If any landing pads survive, we need an EH table.
982 if (!MMI->getLandingPads().empty())
983 shouldEmitTable = true;
985 // See if we need frame move info.
986 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
987 shouldEmitMoves = true;
989 if (shouldEmitMoves || shouldEmitTable)
990 // Assumes in correct section after the entry point.
991 EmitLabel("eh_func_begin", ++SubprogramCount);
993 shouldEmitTableModule |= shouldEmitTable;
994 shouldEmitMovesModule |= shouldEmitMoves;
996 if (TimePassesIsEnabled)
997 ExceptionTimer->stopTimer();
1000 /// EndFunction - Gather and emit post-function exception information.
1002 void DwarfException::EndFunction() {
1003 if (!shouldEmitMoves && !shouldEmitTable) return;
1005 if (TimePassesIsEnabled)
1006 ExceptionTimer->startTimer();
1008 EmitLabel("eh_func_end", SubprogramCount);
1009 EmitExceptionTable();
1011 std::string FunctionEHName =
1012 Asm->Mang->getMangledName(MF->getFunction(), ".eh",
1013 Asm->MAI->is_EHSymbolPrivate());
1015 // Save EH frame information
1016 EHFrames.push_back(FunctionEHFrameInfo(FunctionEHName, SubprogramCount,
1017 MMI->getPersonalityIndex(),
1018 MF->getFrameInfo()->hasCalls(),
1019 !MMI->getLandingPads().empty(),
1020 MMI->getFrameMoves(),
1021 MF->getFunction()));
1023 // Record if this personality index uses a landing pad.
1024 UsesLSDA[MMI->getPersonalityIndex()] |= !MMI->getLandingPads().empty();
1026 if (TimePassesIsEnabled)
1027 ExceptionTimer->stopTimer();