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