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/MCStreamer.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetFrameInfo.h"
24 #include "llvm/Target/TargetLoweringObjectFile.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/StringExtras.h"
34 static TimerGroup &getDwarfTimerGroup() {
35 static TimerGroup DwarfTimerGroup("Dwarf Exception");
36 return DwarfTimerGroup;
39 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
41 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
42 shouldEmitTableModule(false), shouldEmitMovesModule(false),
44 if (TimePassesIsEnabled)
45 ExceptionTimer = new Timer("Dwarf Exception Writer",
46 getDwarfTimerGroup());
49 DwarfException::~DwarfException() {
50 delete ExceptionTimer;
53 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
54 /// is shared among many Frame Description Entries. There is at least one CIE
55 /// in every non-empty .debug_frame section.
56 void DwarfException::EmitCIE(const Function *Personality, unsigned Index) {
57 // Size and sign of stack growth.
59 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
60 TargetFrameInfo::StackGrowsUp ?
61 TD->getPointerSize() : -TD->getPointerSize();
63 // Begin eh frame section.
64 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
66 if (MAI->is_EHSymbolPrivate())
67 O << MAI->getPrivateGlobalPrefix();
69 O << "EH_frame" << Index << ":\n";
70 EmitLabel("section_eh_frame", Index);
72 // Define base labels.
73 EmitLabel("eh_frame_common", Index);
75 // Define the eh frame length.
76 EmitDifference("eh_frame_common_end", Index,
77 "eh_frame_common_begin", Index, true);
78 Asm->EOL("Length of Common Information Entry");
81 EmitLabel("eh_frame_common_begin", Index);
82 Asm->EmitInt32((int)0);
83 Asm->EOL("CIE Identifier Tag");
85 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
86 Asm->EOL("CIE Version");
88 // The personality presence indicates that language specific information will
89 // show up in the eh frame.
90 Asm->EmitString(Personality ? "zPLR" : "zR");
91 Asm->EOL("CIE Augmentation");
94 Asm->EmitULEB128Bytes(1);
95 Asm->EOL("CIE Code Alignment Factor");
97 Asm->EmitSLEB128Bytes(stackGrowth);
98 Asm->EOL("CIE Data Alignment Factor");
100 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
101 Asm->EOL("CIE Return Address Column");
103 unsigned Encoding = 0;
105 // If there is a personality, we need to indicate the function's location.
107 Asm->EmitULEB128Bytes(7);
108 Asm->EOL("Augmentation Size");
110 if (MAI->getNeedsIndirectEncoding()) {
111 Encoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
112 dwarf::DW_EH_PE_indirect;
113 Asm->EmitInt8(Encoding);
114 Asm->EOL("Personality", Encoding);
116 Encoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
117 Asm->EmitInt8(Encoding);
118 Asm->EOL("Personality", Encoding);
121 PrintRelDirective(true);
122 O << MAI->getPersonalityPrefix();
123 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
124 O << MAI->getPersonalitySuffix();
125 if (strcmp(MAI->getPersonalitySuffix(), "+4@GOTPCREL"))
126 O << "-" << MAI->getPCSymbol();
127 Asm->EOL("Personality");
129 Encoding = Asm->TM.getTargetLowering()->getPreferredLSDADataFormat();
130 Asm->EmitInt8(Encoding);
131 Asm->EOL("LSDA Encoding", Encoding);
133 Encoding = Asm->TM.getTargetLowering()->getPreferredFDEDataFormat();
134 Asm->EmitInt8(Encoding);
135 Asm->EOL("FDE Encoding", Encoding);
137 Asm->EmitULEB128Bytes(1);
138 Asm->EOL("Augmentation Size");
140 Encoding = Asm->TM.getTargetLowering()->getPreferredFDEDataFormat();
141 Asm->EmitInt8(Encoding);
142 Asm->EOL("FDE Encoding", Encoding);
145 // Indicate locations of general callee saved registers in frame.
146 std::vector<MachineMove> Moves;
147 RI->getInitialFrameState(Moves);
148 EmitFrameMoves(NULL, 0, Moves, true);
150 // On Darwin the linker honors the alignment of eh_frame, which means it must
151 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
152 // holes which confuse readers of eh_frame.
153 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
155 EmitLabel("eh_frame_common_end", Index);
160 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
161 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
162 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
163 "Should not emit 'available externally' functions at all");
165 const Function *TheFunc = EHFrameInfo.function;
166 bool is4Byte = TD->getPointerSize() == sizeof(int32_t);
168 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
170 // Externally visible entry into the functions eh frame info. If the
171 // corresponding function is static, this should not be externally visible.
172 if (!TheFunc->hasLocalLinkage())
173 if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
174 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
176 // If corresponding function is weak definition, this should be too.
177 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
178 O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
180 // If there are no calls then you can't unwind. This may mean we can omit the
181 // EH Frame, but some environments do not handle weak absolute symbols. If
182 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
183 // info is to be available for non-EH uses.
184 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
185 (!TheFunc->isWeakForLinker() ||
186 !MAI->getWeakDefDirective() ||
187 MAI->getSupportsWeakOmittedEHFrame())) {
188 O << EHFrameInfo.FnName << " = 0\n";
189 // This name has no connection to the function, so it might get
190 // dead-stripped when the function is not, erroneously. Prohibit
191 // dead-stripping unconditionally.
192 if (const char *UsedDirective = MAI->getUsedDirective())
193 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
195 O << EHFrameInfo.FnName << ":\n";
198 EmitDifference("eh_frame_end", EHFrameInfo.Number,
199 "eh_frame_begin", EHFrameInfo.Number, true);
200 Asm->EOL("Length of Frame Information Entry");
202 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
204 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
205 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
208 Asm->EOL("FDE CIE offset");
210 EmitReference("eh_func_begin", EHFrameInfo.Number, true, is4Byte);
211 Asm->EOL("FDE initial location");
213 EmitDifference("eh_func_end", EHFrameInfo.Number,
214 "eh_func_begin", EHFrameInfo.Number, is4Byte);
215 Asm->EOL("FDE address range");
217 // If there is a personality and landing pads then point to the language
218 // specific data area in the exception table.
219 if (MMI->getPersonalities()[0] != NULL) {
220 Asm->EmitULEB128Bytes(is4Byte ? 4 : 8);
221 Asm->EOL("Augmentation size");
223 if (EHFrameInfo.hasLandingPads) {
224 EmitReference("exception", EHFrameInfo.Number, true, false);
227 Asm->EmitInt32((int)0);
229 Asm->EmitInt64((int)0);
231 Asm->EOL("Language Specific Data Area");
233 Asm->EmitULEB128Bytes(0);
234 Asm->EOL("Augmentation size");
237 // Indicate locations of function specific callee saved registers in frame.
238 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
241 // On Darwin the linker honors the alignment of eh_frame, which means it
242 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
243 // get holes which confuse readers of eh_frame.
244 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
246 EmitLabel("eh_frame_end", EHFrameInfo.Number);
248 // If the function is marked used, this table should be also. We cannot
249 // make the mark unconditional in this case, since retaining the table also
250 // retains the function in this case, and there is code around that depends
251 // on unused functions (calling undefined externals) being dead-stripped to
252 // link correctly. Yes, there really is.
253 if (MMI->isUsedFunction(EHFrameInfo.function))
254 if (const char *UsedDirective = MAI->getUsedDirective())
255 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
261 /// SharedTypeIds - How many leading type ids two landing pads have in common.
262 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
263 const LandingPadInfo *R) {
264 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
265 unsigned LSize = LIds.size(), RSize = RIds.size();
266 unsigned MinSize = LSize < RSize ? LSize : RSize;
269 for (; Count != MinSize; ++Count)
270 if (LIds[Count] != RIds[Count])
276 /// PadLT - Order landing pads lexicographically by type id.
277 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
278 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
279 unsigned LSize = LIds.size(), RSize = RIds.size();
280 unsigned MinSize = LSize < RSize ? LSize : RSize;
282 for (unsigned i = 0; i != MinSize; ++i)
283 if (LIds[i] != RIds[i])
284 return LIds[i] < RIds[i];
286 return LSize < RSize;
289 /// ComputeActionsTable - Compute the actions table and gather the first action
290 /// index for each landing pad site.
291 unsigned DwarfException::
292 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
293 SmallVectorImpl<ActionEntry> &Actions,
294 SmallVectorImpl<unsigned> &FirstActions) {
296 // The action table follows the call-site table in the LSDA. The individual
297 // records are of two types:
300 // * Exception specification
302 // The two record kinds have the same format, with only small differences.
303 // They are distinguished by the "switch value" field: Catch clauses
304 // (TypeInfos) have strictly positive switch values, and exception
305 // specifications (FilterIds) have strictly negative switch values. Value 0
306 // indicates a catch-all clause.
308 // Negative type IDs index into FilterIds. Positive type IDs index into
309 // TypeInfos. The value written for a positive type ID is just the type ID
310 // itself. For a negative type ID, however, the value written is the
311 // (negative) byte offset of the corresponding FilterIds entry. The byte
312 // offset is usually equal to the type ID (because the FilterIds entries are
313 // written using a variable width encoding, which outputs one byte per entry
314 // as long as the value written is not too large) but can differ. This kind
315 // of complication does not occur for positive type IDs because type infos are
316 // output using a fixed width encoding. FilterOffsets[i] holds the byte
317 // offset corresponding to FilterIds[i].
319 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
320 SmallVector<int, 16> FilterOffsets;
321 FilterOffsets.reserve(FilterIds.size());
324 for (std::vector<unsigned>::const_iterator
325 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
326 FilterOffsets.push_back(Offset);
327 Offset -= MCAsmInfo::getULEB128Size(*I);
330 FirstActions.reserve(LandingPads.size());
333 unsigned SizeActions = 0;
334 const LandingPadInfo *PrevLPI = 0;
336 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
337 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
338 const LandingPadInfo *LPI = *I;
339 const std::vector<int> &TypeIds = LPI->TypeIds;
340 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
341 unsigned SizeSiteActions = 0;
343 if (NumShared < TypeIds.size()) {
344 unsigned SizeAction = 0;
345 ActionEntry *PrevAction = 0;
348 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
349 assert(Actions.size());
350 PrevAction = &Actions.back();
351 SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
352 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
354 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
356 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
357 SizeAction += -PrevAction->NextAction;
358 PrevAction = PrevAction->Previous;
362 // Compute the actions.
363 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
364 int TypeID = TypeIds[J];
365 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
366 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
367 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
369 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
370 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
371 SizeSiteActions += SizeAction;
373 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
374 Actions.push_back(Action);
375 PrevAction = &Actions.back();
378 // Record the first action of the landing pad site.
379 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
380 } // else identical - re-use previous FirstAction
382 // Information used when created the call-site table. The action record
383 // field of the call site record is the offset of the first associated
384 // action record, relative to the start of the actions table. This value is
385 // biased by 1 (1 in dicating the start of the actions table), and 0
386 // indicates that there are no actions.
387 FirstActions.push_back(FirstAction);
389 // Compute this sites contribution to size.
390 SizeActions += SizeSiteActions;
398 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
399 /// has a try-range containing the call, a non-zero landing pad, and an
400 /// appropriate action. The entry for an ordinary call has a try-range
401 /// containing the call and zero for the landing pad and the action. Calls
402 /// marked 'nounwind' have no entry and must not be contained in the try-range
403 /// of any entry - they form gaps in the table. Entries must be ordered by
404 /// try-range address.
405 void DwarfException::
406 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
407 const RangeMapType &PadMap,
408 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
409 const SmallVectorImpl<unsigned> &FirstActions) {
410 // The end label of the previous invoke or nounwind try-range.
411 unsigned LastLabel = 0;
413 // Whether there is a potentially throwing instruction (currently this means
414 // an ordinary call) between the end of the previous try-range and now.
415 bool SawPotentiallyThrowing = false;
417 // Whether the last CallSite entry was for an invoke.
418 bool PreviousIsInvoke = false;
420 // Visit all instructions in order of address.
421 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
423 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
425 if (!MI->isLabel()) {
426 SawPotentiallyThrowing |= MI->getDesc().isCall();
430 unsigned BeginLabel = MI->getOperand(0).getImm();
431 assert(BeginLabel && "Invalid label!");
433 // End of the previous try-range?
434 if (BeginLabel == LastLabel)
435 SawPotentiallyThrowing = false;
437 // Beginning of a new try-range?
438 RangeMapType::iterator L = PadMap.find(BeginLabel);
439 if (L == PadMap.end())
440 // Nope, it was just some random label.
443 const PadRange &P = L->second;
444 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
445 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
446 "Inconsistent landing pad map!");
448 // For Dwarf exception handling (SjLj handling doesn't use this). If some
449 // instruction between the previous try-range and this one may throw,
450 // create a call-site entry with no landing pad for the region between the
452 if (SawPotentiallyThrowing &&
453 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
454 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
455 CallSites.push_back(Site);
456 PreviousIsInvoke = false;
459 LastLabel = LandingPad->EndLabels[P.RangeIndex];
460 assert(BeginLabel && LastLabel && "Invalid landing pad!");
462 if (LandingPad->LandingPadLabel) {
463 // This try-range is for an invoke.
464 CallSiteEntry Site = {
467 LandingPad->LandingPadLabel,
468 FirstActions[P.PadIndex]
471 // Try to merge with the previous call-site.
472 if (PreviousIsInvoke) {
473 CallSiteEntry &Prev = CallSites.back();
474 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
475 // Extend the range of the previous entry.
476 Prev.EndLabel = Site.EndLabel;
481 // Otherwise, create a new call-site.
482 CallSites.push_back(Site);
483 PreviousIsInvoke = true;
486 PreviousIsInvoke = false;
491 // If some instruction between the previous try-range and the end of the
492 // function may throw, create a call-site entry with no landing pad for the
493 // region following the try-range.
494 if (SawPotentiallyThrowing &&
495 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
496 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
497 CallSites.push_back(Site);
501 /// EmitExceptionTable - Emit landing pads and actions.
503 /// The general organization of the table is complex, but the basic concepts are
504 /// easy. First there is a header which describes the location and organization
505 /// of the three components that follow.
507 /// 1. The landing pad site information describes the range of code covered by
508 /// the try. In our case it's an accumulation of the ranges covered by the
509 /// invokes in the try. There is also a reference to the landing pad that
510 /// handles the exception once processed. Finally an index into the actions
512 /// 2. The action table, in our case, is composed of pairs of type IDs and next
513 /// action offset. Starting with the action index from the landing pad
514 /// site, each type ID is checked for a match to the current exception. If
515 /// it matches then the exception and type id are passed on to the landing
516 /// pad. Otherwise the next action is looked up. This chain is terminated
517 /// with a next action of zero. If no type id is found the the frame is
518 /// unwound and handling continues.
519 /// 3. Type ID table contains references to all the C++ typeinfo for all
520 /// catches in the function. This tables is reversed indexed base 1.
521 void DwarfException::EmitExceptionTable() {
522 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
523 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
524 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
525 if (PadInfos.empty()) return;
527 // Sort the landing pads in order of their type ids. This is used to fold
528 // duplicate actions.
529 SmallVector<const LandingPadInfo *, 64> LandingPads;
530 LandingPads.reserve(PadInfos.size());
532 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
533 LandingPads.push_back(&PadInfos[i]);
535 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
537 // Compute the actions table and gather the first action index for each
539 SmallVector<ActionEntry, 32> Actions;
540 SmallVector<unsigned, 64> FirstActions;
541 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
543 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
544 // by try-range labels when lowered). Ordinary calls do not, so appropriate
545 // try-ranges for them need be deduced when using Dwarf exception handling.
547 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
548 const LandingPadInfo *LandingPad = LandingPads[i];
549 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
550 unsigned BeginLabel = LandingPad->BeginLabels[j];
551 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
552 PadRange P = { i, j };
553 PadMap[BeginLabel] = P;
557 // Compute the call-site table.
558 SmallVector<CallSiteEntry, 64> CallSites;
559 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
564 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
565 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
566 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
569 bool HaveTTData = (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
570 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
573 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
576 SizeSites = CallSites.size() *
577 (SiteStartSize + SiteLengthSize + LandingPadSize);
578 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
579 SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
580 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
581 SizeSites += MCAsmInfo::getULEB128Size(i);
584 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
585 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
587 unsigned TypeOffset = sizeof(int8_t) + // Call site format
588 MCAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
589 SizeSites + SizeActions + SizeTypes;
591 unsigned TotalSize = sizeof(int8_t) + // LPStart format
592 sizeof(int8_t) + // TType format
594 MCAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
597 unsigned SizeAlign = (4 - TotalSize) & 3;
599 // Begin the exception table.
600 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
601 Asm->OutStreamer.SwitchSection(LSDASection);
602 Asm->EmitAlignment(2, 0, 0, false);
603 O << "GCC_except_table" << SubprogramCount << ":\n";
605 for (unsigned i = 0; i != SizeAlign; ++i) {
610 EmitLabel("exception", SubprogramCount);
611 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
612 std::string SjLjName = "_lsda_";
613 SjLjName += MF->getFunction()->getName().str();
614 EmitLabel(SjLjName.c_str(), 0);
618 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
619 Asm->EOL("@LPStart format (DW_EH_PE_omit)");
622 if (TypeInfos.empty() && FilterIds.empty()) {
623 // If there are no typeinfos or filters, there is nothing to emit, optimize
624 // by specifying the "omit" encoding.
625 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
626 Asm->EOL("@TType format (DW_EH_PE_omit)");
628 // Okay, we have actual filters or typeinfos to emit. As such, we need to
629 // pick a type encoding for them. We're about to emit a list of pointers to
630 // typeinfo objects at the end of the LSDA. However, unless we're in static
631 // mode, this reference will require a relocation by the dynamic linker.
633 // Because of this, we have a couple of options:
634 // 1) If we are in -static mode, we can always use an absolute reference
635 // from the LSDA, because the static linker will resolve it.
636 // 2) Otherwise, if the LSDA section is writable, we can output the direct
637 // reference to the typeinfo and allow the dynamic linker to relocate
638 // it. Since it is in a writable section, the dynamic linker won't
640 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
641 // we need to use some form of indirection. For example, on Darwin,
642 // we can output a statically-relocatable reference to a dyld stub. The
643 // offset to the stub is constant, but the contents are in a section
644 // that is updated by the dynamic linker. This is easy enough, but we
645 // need to tell the personality function of the unwinder to indirect
646 // through the dyld stub.
648 // FIXME: When this is actually implemented, we'll have to emit the stubs
649 // somewhere. This predicate should be moved to a shared location that is
650 // in target-independent code.
652 if (LSDASection->isWritable() ||
653 Asm->TM.getRelocationModel() == Reloc::Static) {
654 Asm->EmitInt8(DW_EH_PE_absptr);
655 Asm->EOL("TType format (DW_EH_PE_absptr)");
657 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
658 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
659 " | DW_EH_PE_sdata4)");
661 Asm->EmitULEB128Bytes(TypeOffset);
662 Asm->EOL("TType base offset");
665 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
666 // say that we're omitting that bit.
667 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
669 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
670 Asm->EOL("@TType format (DW_EH_PE_omit)");
672 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
673 Asm->EOL("@TType format (DW_EH_PE_absptr)");
674 Asm->EmitULEB128Bytes(TypeOffset);
675 Asm->EOL("@TType base offset");
679 // SjLj Exception handilng
680 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
681 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
682 Asm->EOL("Call site format (DW_EH_PE_udata4)");
683 Asm->EmitULEB128Bytes(SizeSites);
684 Asm->EOL("Call site table length");
686 // Emit the landing pad site information.
688 for (SmallVectorImpl<CallSiteEntry>::const_iterator
689 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
690 const CallSiteEntry &S = *I;
692 // Offset of the landing pad, counted in 16-byte bundles relative to the
694 Asm->EmitULEB128Bytes(idx);
695 Asm->EOL("Landing pad");
697 // Offset of the first associated action record, relative to the start of
698 // the action table. This value is biased by 1 (1 indicates the start of
699 // the action table), and 0 indicates that there are no actions.
700 Asm->EmitULEB128Bytes(S.Action);
704 // DWARF Exception handling
705 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
707 // The call-site table is a list of all call sites that may throw an
708 // exception (including C++ 'throw' statements) in the procedure
709 // fragment. It immediately follows the LSDA header. Each entry indicates,
710 // for a given call, the first corresponding action record and corresponding
713 // The table begins with the number of bytes, stored as an LEB128
714 // compressed, unsigned integer. The records immediately follow the record
715 // count. They are sorted in increasing call-site address. Each record
718 // * The position of the call-site.
719 // * The position of the landing pad.
720 // * The first action record for that call site.
722 // A missing entry in the call-site table indicates that a call is not
723 // supposed to throw. Such calls include:
725 // * Calls to destructors within cleanup code. C++ semantics forbids these
727 // * Calls to intrinsic routines in the standard library which are known
728 // not to throw (sin, memcpy, et al).
730 // If the runtime does not find the call-site entry for a given call, it
731 // will call `terminate()'.
733 // Emit the landing pad call site table.
734 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
735 Asm->EOL("Call site format (DW_EH_PE_udata4)");
736 Asm->EmitULEB128Bytes(SizeSites);
737 Asm->EOL("Call site table size");
739 for (SmallVectorImpl<CallSiteEntry>::const_iterator
740 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
741 const CallSiteEntry &S = *I;
742 const char *BeginTag;
743 unsigned BeginNumber;
746 BeginTag = "eh_func_begin";
747 BeginNumber = SubprogramCount;
750 BeginNumber = S.BeginLabel;
753 // Offset of the call site relative to the previous call site, counted in
754 // number of 16-byte bundles. The first call site is counted relative to
755 // the start of the procedure fragment.
756 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
758 Asm->EOL("Region start");
761 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
764 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
766 Asm->EOL("Region length");
768 // Offset of the landing pad, counted in 16-byte bundles relative to the
773 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
776 Asm->EOL("Landing pad");
778 // Offset of the first associated action record, relative to the start of
779 // the action table. This value is biased by 1 (1 indicates the start of
780 // the action table), and 0 indicates that there are no actions.
781 Asm->EmitULEB128Bytes(S.Action);
786 // Emit the Action Table.
787 for (SmallVectorImpl<ActionEntry>::const_iterator
788 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
789 const ActionEntry &Action = *I;
793 // Used by the runtime to match the type of the thrown exception to the
794 // type of the catch clauses or the types in the exception specification.
796 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
797 Asm->EOL("TypeInfo index");
801 // Self-relative signed displacement in bytes of the next action record,
802 // or 0 if there is no next action record.
804 Asm->EmitSLEB128Bytes(Action.NextAction);
805 Asm->EOL("Next action");
808 // Emit the Catch Clauses. The code for the catch clauses following the same
809 // try is similar to a switch statement. The catch clause action record
810 // informs the runtime about the type of a catch clause and about the
811 // associated switch value.
813 // Action Record Fields:
816 // Positive value, starting at 1. Index in the types table of the
817 // __typeinfo for the catch-clause type. 1 is the first word preceding
818 // TTBase, 2 is the second word, and so on. Used by the runtime to check
819 // if the thrown exception type matches the catch-clause type. Back-end
820 // generated switch statements check against this value.
823 // Signed offset, in bytes from the start of this field, to the next
824 // chained action record, or zero if none.
826 // The order of the action records determined by the next field is the order
827 // of the catch clauses as they appear in the source code, and must be kept in
828 // the same order. As a result, changing the order of the catch clause would
829 // change the semantics of the program.
830 for (std::vector<GlobalVariable *>::const_reverse_iterator
831 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
832 const GlobalVariable *GV = *I;
837 O << Asm->getGlobalLinkName(GV, GLN);
842 Asm->EOL("TypeInfo");
845 // Emit the Type Table.
846 for (std::vector<unsigned>::const_iterator
847 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
848 unsigned TypeID = *I;
849 Asm->EmitULEB128Bytes(TypeID);
850 Asm->EOL("Filter TypeInfo index");
853 Asm->EmitAlignment(2, 0, 0, false);
856 /// EndModule - Emit all exception information that should come after the
858 void DwarfException::EndModule() {
859 if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
861 if (TimePassesIsEnabled)
862 ExceptionTimer->startTimer();
864 if (shouldEmitMovesModule || shouldEmitTableModule) {
865 const std::vector<Function *> Personalities = MMI->getPersonalities();
866 for (unsigned i = 0; i < Personalities.size(); ++i)
867 EmitCIE(Personalities[i], i);
869 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
870 E = EHFrames.end(); I != E; ++I)
874 if (TimePassesIsEnabled)
875 ExceptionTimer->stopTimer();
878 /// BeginFunction - Gather pre-function exception information. Assumes being
879 /// emitted immediately after the function entry point.
880 void DwarfException::BeginFunction(MachineFunction *MF) {
881 if (TimePassesIsEnabled)
882 ExceptionTimer->startTimer();
885 shouldEmitTable = shouldEmitMoves = false;
887 if (MMI && MAI->doesSupportExceptionHandling()) {
888 // Map all labels and get rid of any dead landing pads.
889 MMI->TidyLandingPads();
891 // If any landing pads survive, we need an EH table.
892 if (MMI->getLandingPads().size())
893 shouldEmitTable = true;
895 // See if we need frame move info.
896 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
897 shouldEmitMoves = true;
899 if (shouldEmitMoves || shouldEmitTable)
900 // Assumes in correct section after the entry point.
901 EmitLabel("eh_func_begin", ++SubprogramCount);
904 shouldEmitTableModule |= shouldEmitTable;
905 shouldEmitMovesModule |= shouldEmitMoves;
907 if (TimePassesIsEnabled)
908 ExceptionTimer->stopTimer();
911 /// EndFunction - Gather and emit post-function exception information.
913 void DwarfException::EndFunction() {
914 if (TimePassesIsEnabled)
915 ExceptionTimer->startTimer();
917 if (shouldEmitMoves || shouldEmitTable) {
918 EmitLabel("eh_func_end", SubprogramCount);
919 EmitExceptionTable();
921 // Save EH frame information
923 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
925 MMI->getPersonalityIndex(),
926 MF->getFrameInfo()->hasCalls(),
927 !MMI->getLandingPads().empty(),
928 MMI->getFrameMoves(),
934 if (TimePassesIsEnabled)
935 ExceptionTimer->stopTimer();