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);
156 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common_end", Index));
159 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
160 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
161 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
162 "Should not emit 'available externally' functions at all");
164 const Function *TheFunc = EHFrameInfo.function;
165 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
167 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
168 unsigned FDEEncoding = TLOF.getFDEEncoding();
170 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
172 // Externally visible entry into the functions eh frame info. If the
173 // corresponding function is static, this should not be externally visible.
174 if (!TheFunc->hasLocalLinkage() && TLOF.isFunctionEHSymbolGlobal())
175 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,MCSA_Global);
177 // If corresponding function is weak definition, this should be too.
178 if (TheFunc->isWeakForLinker() && Asm->MAI->getWeakDefDirective())
179 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
180 MCSA_WeakDefinition);
182 // If corresponding function is hidden, this should be too.
183 if (TheFunc->hasHiddenVisibility())
184 if (MCSymbolAttr HiddenAttr = Asm->MAI->getHiddenVisibilityAttr())
185 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
188 // If there are no calls then you can't unwind. This may mean we can omit the
189 // EH Frame, but some environments do not handle weak absolute symbols. If
190 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
191 // info is to be available for non-EH uses.
192 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
193 (!TheFunc->isWeakForLinker() ||
194 !Asm->MAI->getWeakDefDirective() ||
195 TLOF.getSupportsWeakOmittedEHFrame())) {
196 Asm->OutStreamer.EmitAssignment(EHFrameInfo.FunctionEHSym,
197 MCConstantExpr::Create(0, Asm->OutContext));
198 // This name has no connection to the function, so it might get
199 // dead-stripped when the function is not, erroneously. Prohibit
200 // dead-stripping unconditionally.
201 if (Asm->MAI->hasNoDeadStrip())
202 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
205 Asm->OutStreamer.EmitLabel(EHFrameInfo.FunctionEHSym);
208 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
209 Asm->EmitLabelDifference(
210 Asm->GetTempSymbol("eh_frame_end", EHFrameInfo.Number),
211 Asm->GetTempSymbol("eh_frame_begin", EHFrameInfo.Number), 4);
213 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_begin",
214 EHFrameInfo.Number));
216 Asm->OutStreamer.AddComment("FDE CIE offset");
217 Asm->EmitLabelDifference(
218 Asm->GetTempSymbol("eh_frame_begin", EHFrameInfo.Number),
219 Asm->GetTempSymbol("eh_frame_common",
220 EHFrameInfo.PersonalityIndex), 4);
222 MCSymbol *EHFuncBeginSym =
223 Asm->GetTempSymbol("eh_func_begin", EHFrameInfo.Number);
225 Asm->OutStreamer.AddComment("FDE initial location");
226 Asm->EmitReference(EHFuncBeginSym, FDEEncoding);
228 Asm->OutStreamer.AddComment("FDE address range");
229 Asm->EmitLabelDifference(Asm->GetTempSymbol("eh_func_end",
232 Asm->GetSizeOfEncodedValue(FDEEncoding));
234 // If there is a personality and landing pads then point to the language
235 // specific data area in the exception table.
236 if (MMI->getPersonalities()[0] != NULL) {
237 unsigned Size = Asm->GetSizeOfEncodedValue(LSDAEncoding);
239 Asm->EmitULEB128(Size, "Augmentation size");
240 Asm->OutStreamer.AddComment("Language Specific Data Area");
241 if (EHFrameInfo.hasLandingPads)
242 Asm->EmitReference(Asm->GetTempSymbol("exception", EHFrameInfo.Number),
245 Asm->OutStreamer.EmitIntValue(0, Size/*size*/, 0/*addrspace*/);
248 Asm->EmitULEB128(0, "Augmentation size");
251 // Indicate locations of function specific callee saved registers in frame.
252 Asm->EmitFrameMoves(EHFrameInfo.Moves, EHFuncBeginSym, true);
254 // On Darwin the linker honors the alignment of eh_frame, which means it
255 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
256 // get holes which confuse readers of eh_frame.
257 Asm->EmitAlignment(Asm->getTargetData().getPointerSize() == 4 ? 2 : 3);
258 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_end",
259 EHFrameInfo.Number));
261 // If the function is marked used, this table should be also. We cannot
262 // make the mark unconditional in this case, since retaining the table also
263 // retains the function in this case, and there is code around that depends
264 // on unused functions (calling undefined externals) being dead-stripped to
265 // link correctly. Yes, there really is.
266 if (MMI->isUsedFunction(EHFrameInfo.function))
267 if (Asm->MAI->hasNoDeadStrip())
268 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
271 Asm->OutStreamer.AddBlankLine();
274 /// SharedTypeIds - How many leading type ids two landing pads have in common.
275 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
276 const LandingPadInfo *R) {
277 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
278 unsigned LSize = LIds.size(), RSize = RIds.size();
279 unsigned MinSize = LSize < RSize ? LSize : RSize;
282 for (; Count != MinSize; ++Count)
283 if (LIds[Count] != RIds[Count])
289 /// PadLT - Order landing pads lexicographically by type id.
290 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
291 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
292 unsigned LSize = LIds.size(), RSize = RIds.size();
293 unsigned MinSize = LSize < RSize ? LSize : RSize;
295 for (unsigned i = 0; i != MinSize; ++i)
296 if (LIds[i] != RIds[i])
297 return LIds[i] < RIds[i];
299 return LSize < RSize;
302 /// ComputeActionsTable - Compute the actions table and gather the first action
303 /// index for each landing pad site.
304 unsigned DwarfException::
305 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
306 SmallVectorImpl<ActionEntry> &Actions,
307 SmallVectorImpl<unsigned> &FirstActions) {
309 // The action table follows the call-site table in the LSDA. The individual
310 // records are of two types:
313 // * Exception specification
315 // The two record kinds have the same format, with only small differences.
316 // They are distinguished by the "switch value" field: Catch clauses
317 // (TypeInfos) have strictly positive switch values, and exception
318 // specifications (FilterIds) have strictly negative switch values. Value 0
319 // indicates a catch-all clause.
321 // Negative type IDs index into FilterIds. Positive type IDs index into
322 // TypeInfos. The value written for a positive type ID is just the type ID
323 // itself. For a negative type ID, however, the value written is the
324 // (negative) byte offset of the corresponding FilterIds entry. The byte
325 // offset is usually equal to the type ID (because the FilterIds entries are
326 // written using a variable width encoding, which outputs one byte per entry
327 // as long as the value written is not too large) but can differ. This kind
328 // of complication does not occur for positive type IDs because type infos are
329 // output using a fixed width encoding. FilterOffsets[i] holds the byte
330 // offset corresponding to FilterIds[i].
332 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
333 SmallVector<int, 16> FilterOffsets;
334 FilterOffsets.reserve(FilterIds.size());
337 for (std::vector<unsigned>::const_iterator
338 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
339 FilterOffsets.push_back(Offset);
340 Offset -= MCAsmInfo::getULEB128Size(*I);
343 FirstActions.reserve(LandingPads.size());
346 unsigned SizeActions = 0;
347 const LandingPadInfo *PrevLPI = 0;
349 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
350 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
351 const LandingPadInfo *LPI = *I;
352 const std::vector<int> &TypeIds = LPI->TypeIds;
353 unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
354 unsigned SizeSiteActions = 0;
356 if (NumShared < TypeIds.size()) {
357 unsigned SizeAction = 0;
358 unsigned PrevAction = (unsigned)-1;
361 unsigned SizePrevIds = PrevLPI->TypeIds.size();
362 assert(Actions.size());
363 PrevAction = Actions.size() - 1;
365 MCAsmInfo::getSLEB128Size(Actions[PrevAction].NextAction) +
366 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
368 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
369 assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
371 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
372 SizeAction += -Actions[PrevAction].NextAction;
373 PrevAction = Actions[PrevAction].Previous;
377 // Compute the actions.
378 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
379 int TypeID = TypeIds[J];
380 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
381 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
382 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
384 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
385 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
386 SizeSiteActions += SizeAction;
388 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
389 Actions.push_back(Action);
390 PrevAction = Actions.size() - 1;
393 // Record the first action of the landing pad site.
394 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
395 } // else identical - re-use previous FirstAction
397 // Information used when created the call-site table. The action record
398 // field of the call site record is the offset of the first associated
399 // action record, relative to the start of the actions table. This value is
400 // biased by 1 (1 indicating the start of the actions table), and 0
401 // indicates that there are no actions.
402 FirstActions.push_back(FirstAction);
404 // Compute this sites contribution to size.
405 SizeActions += SizeSiteActions;
413 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
414 /// marked `nounwind'. Return `false' otherwise.
415 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
416 assert(MI->getDesc().isCall() && "This should be a call instruction!");
418 bool MarkedNoUnwind = false;
419 bool SawFunc = false;
421 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
422 const MachineOperand &MO = MI->getOperand(I);
424 if (!MO.isGlobal()) continue;
426 const Function *F = dyn_cast<Function>(MO.getGlobal());
427 if (F == 0) continue;
430 // Be conservative. If we have more than one function operand for this
431 // call, then we can't make the assumption that it's the callee and
432 // not a parameter to the call.
434 // FIXME: Determine if there's a way to say that `F' is the callee or
436 MarkedNoUnwind = false;
440 MarkedNoUnwind = F->doesNotThrow();
444 return MarkedNoUnwind;
447 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
448 /// has a try-range containing the call, a non-zero landing pad, and an
449 /// appropriate action. The entry for an ordinary call has a try-range
450 /// containing the call and zero for the landing pad and the action. Calls
451 /// marked 'nounwind' have no entry and must not be contained in the try-range
452 /// of any entry - they form gaps in the table. Entries must be ordered by
453 /// try-range address.
454 void DwarfException::
455 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
456 const RangeMapType &PadMap,
457 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
458 const SmallVectorImpl<unsigned> &FirstActions) {
459 // The end label of the previous invoke or nounwind try-range.
460 MCSymbol *LastLabel = 0;
462 // Whether there is a potentially throwing instruction (currently this means
463 // an ordinary call) between the end of the previous try-range and now.
464 bool SawPotentiallyThrowing = false;
466 // Whether the last CallSite entry was for an invoke.
467 bool PreviousIsInvoke = false;
469 // Visit all instructions in order of address.
470 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
472 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
474 if (!MI->isLabel()) {
475 if (MI->getDesc().isCall())
476 SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
480 // End of the previous try-range?
481 MCSymbol *BeginLabel = MI->getOperand(0).getMCSymbol();
482 if (BeginLabel == LastLabel)
483 SawPotentiallyThrowing = false;
485 // Beginning of a new try-range?
486 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
487 if (L == PadMap.end())
488 // Nope, it was just some random label.
491 const PadRange &P = L->second;
492 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
493 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
494 "Inconsistent landing pad map!");
496 // For Dwarf exception handling (SjLj handling doesn't use this). If some
497 // instruction between the previous try-range and this one may throw,
498 // create a call-site entry with no landing pad for the region between the
500 if (SawPotentiallyThrowing &&
501 Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
502 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
503 CallSites.push_back(Site);
504 PreviousIsInvoke = false;
507 LastLabel = LandingPad->EndLabels[P.RangeIndex];
508 assert(BeginLabel && LastLabel && "Invalid landing pad!");
510 if (!LandingPad->LandingPadLabel) {
512 PreviousIsInvoke = false;
514 // This try-range is for an invoke.
515 CallSiteEntry Site = {
518 LandingPad->LandingPadLabel,
519 FirstActions[P.PadIndex]
522 // Try to merge with the previous call-site. SJLJ doesn't do this
523 if (PreviousIsInvoke &&
524 Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
525 CallSiteEntry &Prev = CallSites.back();
526 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
527 // Extend the range of the previous entry.
528 Prev.EndLabel = Site.EndLabel;
533 // Otherwise, create a new call-site.
534 if (Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf)
535 CallSites.push_back(Site);
537 // SjLj EH must maintain the call sites in the order assigned
538 // to them by the SjLjPrepare pass.
539 unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
540 if (CallSites.size() < SiteNo)
541 CallSites.resize(SiteNo);
542 CallSites[SiteNo - 1] = Site;
544 PreviousIsInvoke = true;
549 // If some instruction between the previous try-range and the end of the
550 // function may throw, create a call-site entry with no landing pad for the
551 // region following the try-range.
552 if (SawPotentiallyThrowing &&
553 Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
554 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
555 CallSites.push_back(Site);
559 /// EmitExceptionTable - Emit landing pads and actions.
561 /// The general organization of the table is complex, but the basic concepts are
562 /// easy. First there is a header which describes the location and organization
563 /// of the three components that follow.
565 /// 1. The landing pad site information describes the range of code covered by
566 /// the try. In our case it's an accumulation of the ranges covered by the
567 /// invokes in the try. There is also a reference to the landing pad that
568 /// handles the exception once processed. Finally an index into the actions
570 /// 2. The action table, in our case, is composed of pairs of type IDs and next
571 /// action offset. Starting with the action index from the landing pad
572 /// site, each type ID is checked for a match to the current exception. If
573 /// it matches then the exception and type id are passed on to the landing
574 /// pad. Otherwise the next action is looked up. This chain is terminated
575 /// with a next action of zero. If no type id is found then the frame is
576 /// unwound and handling continues.
577 /// 3. Type ID table contains references to all the C++ typeinfo for all
578 /// catches in the function. This tables is reverse indexed base 1.
579 void DwarfException::EmitExceptionTable() {
580 const std::vector<const GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
581 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
582 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
584 // Sort the landing pads in order of their type ids. This is used to fold
585 // duplicate actions.
586 SmallVector<const LandingPadInfo *, 64> LandingPads;
587 LandingPads.reserve(PadInfos.size());
589 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
590 LandingPads.push_back(&PadInfos[i]);
592 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
594 // Compute the actions table and gather the first action index for each
596 SmallVector<ActionEntry, 32> Actions;
597 SmallVector<unsigned, 64> FirstActions;
598 unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
600 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
601 // by try-range labels when lowered). Ordinary calls do not, so appropriate
602 // try-ranges for them need be deduced when using DWARF exception handling.
604 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
605 const LandingPadInfo *LandingPad = LandingPads[i];
606 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
607 MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
608 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
609 PadRange P = { i, j };
610 PadMap[BeginLabel] = P;
614 // Compute the call-site table.
615 SmallVector<CallSiteEntry, 64> CallSites;
616 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
621 bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
622 bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
624 unsigned CallSiteTableLength;
626 CallSiteTableLength = 0;
628 unsigned SiteStartSize = 4; // dwarf::DW_EH_PE_udata4
629 unsigned SiteLengthSize = 4; // dwarf::DW_EH_PE_udata4
630 unsigned LandingPadSize = 4; // dwarf::DW_EH_PE_udata4
631 CallSiteTableLength =
632 CallSites.size() * (SiteStartSize + SiteLengthSize + LandingPadSize);
635 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
636 CallSiteTableLength += MCAsmInfo::getULEB128Size(CallSites[i].Action);
638 CallSiteTableLength += MCAsmInfo::getULEB128Size(i);
642 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
643 unsigned TTypeEncoding;
644 unsigned TypeFormatSize;
647 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
648 // that we're omitting that bit.
649 TTypeEncoding = dwarf::DW_EH_PE_omit;
650 // dwarf::DW_EH_PE_absptr
651 TypeFormatSize = Asm->getTargetData().getPointerSize();
653 // Okay, we have actual filters or typeinfos to emit. As such, we need to
654 // pick a type encoding for them. We're about to emit a list of pointers to
655 // typeinfo objects at the end of the LSDA. However, unless we're in static
656 // mode, this reference will require a relocation by the dynamic linker.
658 // Because of this, we have a couple of options:
660 // 1) If we are in -static mode, we can always use an absolute reference
661 // from the LSDA, because the static linker will resolve it.
663 // 2) Otherwise, if the LSDA section is writable, we can output the direct
664 // reference to the typeinfo and allow the dynamic linker to relocate
665 // it. Since it is in a writable section, the dynamic linker won't
668 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
669 // we need to use some form of indirection. For example, on Darwin,
670 // we can output a statically-relocatable reference to a dyld stub. The
671 // offset to the stub is constant, but the contents are in a section
672 // that is updated by the dynamic linker. This is easy enough, but we
673 // need to tell the personality function of the unwinder to indirect
674 // through the dyld stub.
676 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
677 // somewhere. This predicate should be moved to a shared location that is
678 // in target-independent code.
680 TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
681 TypeFormatSize = Asm->GetSizeOfEncodedValue(TTypeEncoding);
684 // Begin the exception table.
685 Asm->OutStreamer.SwitchSection(LSDASection);
686 Asm->EmitAlignment(2);
690 Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
691 Twine(Asm->getFunctionNumber()));
692 Asm->OutStreamer.EmitLabel(GCCETSym);
693 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("exception",
694 Asm->getFunctionNumber()));
697 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("_LSDA_",
698 Asm->getFunctionNumber()));
700 // Emit the LSDA header.
701 Asm->EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
702 Asm->EmitEncodingByte(TTypeEncoding, "@TType");
704 // The type infos need to be aligned. GCC does this by inserting padding just
705 // before the type infos. However, this changes the size of the exception
706 // table, so you need to take this into account when you output the exception
707 // table size. However, the size is output using a variable length encoding.
708 // So by increasing the size by inserting padding, you may increase the number
709 // of bytes used for writing the size. If it increases, say by one byte, then
710 // you now need to output one less byte of padding to get the type infos
711 // aligned. However this decreases the size of the exception table. This
712 // changes the value you have to output for the exception table size. Due to
713 // the variable length encoding, the number of bytes used for writing the
714 // length may decrease. If so, you then have to increase the amount of
715 // padding. And so on. If you look carefully at the GCC code you will see that
716 // it indeed does this in a loop, going on and on until the values stabilize.
717 // We chose another solution: don't output padding inside the table like GCC
718 // does, instead output it before the table.
719 unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
720 unsigned CallSiteTableLengthSize =
721 MCAsmInfo::getULEB128Size(CallSiteTableLength);
722 unsigned TTypeBaseOffset =
723 sizeof(int8_t) + // Call site format
724 CallSiteTableLengthSize + // Call site table length size
725 CallSiteTableLength + // Call site table length
726 SizeActions + // Actions size
728 unsigned TTypeBaseOffsetSize = MCAsmInfo::getULEB128Size(TTypeBaseOffset);
730 sizeof(int8_t) + // LPStart format
731 sizeof(int8_t) + // TType format
732 (HaveTTData ? TTypeBaseOffsetSize : 0) + // TType base offset size
733 TTypeBaseOffset; // TType base offset
734 unsigned SizeAlign = (4 - TotalSize) & 3;
737 // Account for any extra padding that will be added to the call site table
739 Asm->EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
743 // SjLj Exception handling
745 Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
747 // Add extra padding if it wasn't added to the TType base offset.
748 Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
750 // Emit the landing pad site information.
752 for (SmallVectorImpl<CallSiteEntry>::const_iterator
753 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
754 const CallSiteEntry &S = *I;
756 // Offset of the landing pad, counted in 16-byte bundles relative to the
758 Asm->EmitULEB128(idx, "Landing pad");
760 // Offset of the first associated action record, relative to the start of
761 // the action table. This value is biased by 1 (1 indicates the start of
762 // the action table), and 0 indicates that there are no actions.
763 Asm->EmitULEB128(S.Action, "Action");
766 // DWARF Exception handling
767 assert(Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
769 // The call-site table is a list of all call sites that may throw an
770 // exception (including C++ 'throw' statements) in the procedure
771 // fragment. It immediately follows the LSDA header. Each entry indicates,
772 // for a given call, the first corresponding action record and corresponding
775 // The table begins with the number of bytes, stored as an LEB128
776 // compressed, unsigned integer. The records immediately follow the record
777 // count. They are sorted in increasing call-site address. Each record
780 // * The position of the call-site.
781 // * The position of the landing pad.
782 // * The first action record for that call site.
784 // A missing entry in the call-site table indicates that a call is not
785 // supposed to throw.
787 // Emit the landing pad call site table.
788 Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
790 // Add extra padding if it wasn't added to the TType base offset.
791 Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
793 for (SmallVectorImpl<CallSiteEntry>::const_iterator
794 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
795 const CallSiteEntry &S = *I;
797 MCSymbol *EHFuncBeginSym =
798 Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber());
800 MCSymbol *BeginLabel = S.BeginLabel;
802 BeginLabel = EHFuncBeginSym;
803 MCSymbol *EndLabel = S.EndLabel;
805 EndLabel = Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber());
807 // Offset of the call site relative to the previous call site, counted in
808 // number of 16-byte bundles. The first call site is counted relative to
809 // the start of the procedure fragment.
810 Asm->OutStreamer.AddComment("Region start");
811 Asm->EmitLabelDifference(BeginLabel, EHFuncBeginSym, 4);
813 Asm->OutStreamer.AddComment("Region length");
814 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
817 // Offset of the landing pad, counted in 16-byte bundles relative to the
819 Asm->OutStreamer.AddComment("Landing pad");
821 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
823 Asm->EmitLabelDifference(S.PadLabel, EHFuncBeginSym, 4);
825 // Offset of the first associated action record, relative to the start of
826 // the action table. This value is biased by 1 (1 indicates the start of
827 // the action table), and 0 indicates that there are no actions.
828 Asm->EmitULEB128(S.Action, "Action");
832 // Emit the Action Table.
833 if (Actions.size() != 0) {
834 Asm->OutStreamer.AddComment("-- Action Record Table --");
835 Asm->OutStreamer.AddBlankLine();
838 for (SmallVectorImpl<ActionEntry>::const_iterator
839 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
840 const ActionEntry &Action = *I;
841 Asm->OutStreamer.AddComment("Action Record");
842 Asm->OutStreamer.AddBlankLine();
846 // Used by the runtime to match the type of the thrown exception to the
847 // type of the catch clauses or the types in the exception specification.
848 Asm->EmitSLEB128(Action.ValueForTypeID, " TypeInfo index");
852 // Self-relative signed displacement in bytes of the next action record,
853 // or 0 if there is no next action record.
854 Asm->EmitSLEB128(Action.NextAction, " Next action");
857 // Emit the Catch TypeInfos.
858 if (!TypeInfos.empty()) {
859 Asm->OutStreamer.AddComment("-- Catch TypeInfos --");
860 Asm->OutStreamer.AddBlankLine();
862 for (std::vector<const GlobalVariable *>::const_reverse_iterator
863 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
864 const GlobalVariable *GV = *I;
866 Asm->OutStreamer.AddComment("TypeInfo");
868 Asm->EmitReference(GV, TTypeEncoding);
870 Asm->OutStreamer.EmitIntValue(0,Asm->GetSizeOfEncodedValue(TTypeEncoding),
874 // Emit the Exception Specifications.
875 if (!FilterIds.empty()) {
876 Asm->OutStreamer.AddComment("-- Filter IDs --");
877 Asm->OutStreamer.AddBlankLine();
879 for (std::vector<unsigned>::const_iterator
880 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
881 unsigned TypeID = *I;
882 Asm->EmitULEB128(TypeID, TypeID != 0 ? "Exception specification" : 0);
885 Asm->EmitAlignment(2);
888 /// EndModule - Emit all exception information that should come after the
890 void DwarfException::EndModule() {
891 if (Asm->MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
894 if (!shouldEmitMovesModule && !shouldEmitTableModule)
897 const std::vector<const Function *> Personalities = MMI->getPersonalities();
899 for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
900 EmitCIE(Personalities[I], I);
902 for (std::vector<FunctionEHFrameInfo>::iterator
903 I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
907 /// BeginFunction - Gather pre-function exception information. Assumes it's
908 /// being emitted immediately after the function entry point.
909 void DwarfException::BeginFunction(const MachineFunction *MF) {
910 shouldEmitTable = shouldEmitMoves = false;
912 // If any landing pads survive, we need an EH table.
913 shouldEmitTable = !MMI->getLandingPads().empty();
915 // See if we need frame move info.
917 !Asm->MF->getFunction()->doesNotThrow() || UnwindTablesMandatory;
919 if (shouldEmitMoves || shouldEmitTable)
920 // Assumes in correct section after the entry point.
921 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin",
922 Asm->getFunctionNumber()));
924 shouldEmitTableModule |= shouldEmitTable;
925 shouldEmitMovesModule |= shouldEmitMoves;
928 /// EndFunction - Gather and emit post-function exception information.
930 void DwarfException::EndFunction() {
931 if (!shouldEmitMoves && !shouldEmitTable) return;
933 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end",
934 Asm->getFunctionNumber()));
936 // Record if this personality index uses a landing pad.
937 bool HasLandingPad = !MMI->getLandingPads().empty();
938 UsesLSDA[MMI->getPersonalityIndex()] |= HasLandingPad;
940 // Map all labels and get rid of any dead landing pads.
941 MMI->TidyLandingPads();
944 EmitExceptionTable();
946 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
947 MCSymbol *FunctionEHSym =
948 Asm->GetSymbolWithGlobalValueBase(Asm->MF->getFunction(), ".eh",
949 TLOF.isFunctionEHFrameSymbolPrivate());
951 // Save EH frame information
952 EHFrames.push_back(FunctionEHFrameInfo(FunctionEHSym,
953 Asm->getFunctionNumber(),
954 MMI->getPersonalityIndex(),
955 Asm->MF->getFrameInfo()->hasCalls(),
956 !MMI->getLandingPads().empty(),
957 MMI->getFrameMoves(),
958 Asm->MF->getFunction()));