blob: a0cd456d372023b24bec0b447690daf25e82b256 [file] [log] [blame]
Bill Wendlingeb907212009-05-15 01:12:28 +00001//===-- CodeGen/AsmPrinter/DwarfException.cpp - Dwarf Exception Impl ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf exception info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
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/MachineLocation.h"
19#include "llvm/Support/Dwarf.h"
20#include "llvm/Support/Timer.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/Target/TargetAsmInfo.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetFrameInfo.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000025#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000026#include "llvm/Target/TargetOptions.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000027#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000028#include "llvm/ADT/StringExtras.h"
29using namespace llvm;
30
31static TimerGroup &getDwarfTimerGroup() {
32 static TimerGroup DwarfTimerGroup("Dwarf Exception");
33 return DwarfTimerGroup;
34}
35
Bill Wendlingbc0d23a2009-05-15 01:18:50 +000036DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
37 const TargetAsmInfo *T)
38 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
39 shouldEmitTableModule(false), shouldEmitMovesModule(false),
40 ExceptionTimer(0) {
41 if (TimePassesIsEnabled)
42 ExceptionTimer = new Timer("Dwarf Exception Writer",
43 getDwarfTimerGroup());
44}
45
46DwarfException::~DwarfException() {
47 delete ExceptionTimer;
48}
49
Bill Wendlingeb907212009-05-15 01:12:28 +000050void DwarfException::EmitCommonEHFrame(const Function *Personality,
51 unsigned Index) {
52 // Size and sign of stack growth.
53 int stackGrowth =
54 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
55 TargetFrameInfo::StackGrowsUp ?
56 TD->getPointerSize() : -TD->getPointerSize();
57
58 // Begin eh frame section.
Chris Lattner35039ac2009-08-02 06:52:36 +000059 Asm->SwitchToSection(Asm->getObjFileLowering().getEHFrameSection());
Bill Wendlingeb907212009-05-15 01:12:28 +000060
Chris Lattnere2cf37b2009-07-17 20:46:40 +000061 if (TAI->is_EHSymbolPrivate())
62 O << TAI->getPrivateGlobalPrefix();
Bill Wendlingeb907212009-05-15 01:12:28 +000063
64 O << "EH_frame" << Index << ":\n";
65 EmitLabel("section_eh_frame", Index);
66
67 // Define base labels.
68 EmitLabel("eh_frame_common", Index);
69
70 // Define the eh frame length.
71 EmitDifference("eh_frame_common_end", Index,
72 "eh_frame_common_begin", Index, true);
73 Asm->EOL("Length of Common Information Entry");
74
75 // EH frame header.
76 EmitLabel("eh_frame_common_begin", Index);
77 Asm->EmitInt32((int)0);
78 Asm->EOL("CIE Identifier Tag");
79 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
80 Asm->EOL("CIE Version");
81
82 // The personality presence indicates that language specific information will
83 // show up in the eh frame.
84 Asm->EmitString(Personality ? "zPLR" : "zR");
85 Asm->EOL("CIE Augmentation");
86
87 // Round out reader.
88 Asm->EmitULEB128Bytes(1);
89 Asm->EOL("CIE Code Alignment Factor");
90 Asm->EmitSLEB128Bytes(stackGrowth);
91 Asm->EOL("CIE Data Alignment Factor");
92 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
93 Asm->EOL("CIE Return Address Column");
94
95 // If there is a personality, we need to indicate the functions location.
96 if (Personality) {
97 Asm->EmitULEB128Bytes(7);
98 Asm->EOL("Augmentation Size");
99
100 if (TAI->getNeedsIndirectEncoding()) {
101 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
102 dwarf::DW_EH_PE_indirect);
103 Asm->EOL("Personality (pcrel sdata4 indirect)");
104 } else {
105 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
106 Asm->EOL("Personality (pcrel sdata4)");
107 }
108
109 PrintRelDirective(true);
110 O << TAI->getPersonalityPrefix();
111 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
112 O << TAI->getPersonalitySuffix();
113 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
114 O << "-" << TAI->getPCSymbol();
115 Asm->EOL("Personality");
116
117 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
118 Asm->EOL("LSDA Encoding (pcrel sdata4)");
119
120 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
121 Asm->EOL("FDE Encoding (pcrel sdata4)");
122 } else {
123 Asm->EmitULEB128Bytes(1);
124 Asm->EOL("Augmentation Size");
125
126 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
127 Asm->EOL("FDE Encoding (pcrel sdata4)");
128 }
129
130 // Indicate locations of general callee saved registers in frame.
131 std::vector<MachineMove> Moves;
132 RI->getInitialFrameState(Moves);
133 EmitFrameMoves(NULL, 0, Moves, true);
134
135 // On Darwin the linker honors the alignment of eh_frame, which means it must
136 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
137 // holes which confuse readers of eh_frame.
138 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
139 0, 0, false);
140 EmitLabel("eh_frame_common_end", Index);
141
142 Asm->EOL();
143}
144
145/// EmitEHFrame - Emit function exception frame information.
146///
147void DwarfException::EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
148 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
149 "Should not emit 'available externally' functions at all");
150
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000151 const Function *TheFunc = EHFrameInfo.function;
152
Chris Lattner35039ac2009-08-02 06:52:36 +0000153 Asm->SwitchToSection(Asm->getObjFileLowering().getEHFrameSection());
Bill Wendlingeb907212009-05-15 01:12:28 +0000154
155 // Externally visible entry into the functions eh frame info. If the
156 // corresponding function is static, this should not be externally visible.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000157 if (!TheFunc->hasLocalLinkage())
Bill Wendlingeb907212009-05-15 01:12:28 +0000158 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
159 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
Bill Wendlingeb907212009-05-15 01:12:28 +0000160
161 // If corresponding function is weak definition, this should be too.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000162 if (TheFunc->isWeakForLinker() && TAI->getWeakDefDirective())
Bill Wendlingeb907212009-05-15 01:12:28 +0000163 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
164
165 // If there are no calls then you can't unwind. This may mean we can omit the
166 // EH Frame, but some environments do not handle weak absolute symbols. If
167 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
168 // info is to be available for non-EH uses.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000169 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
170 (!TheFunc->isWeakForLinker() ||
Bill Wendlingeb907212009-05-15 01:12:28 +0000171 !TAI->getWeakDefDirective() ||
172 TAI->getSupportsWeakOmittedEHFrame())) {
173 O << EHFrameInfo.FnName << " = 0\n";
174 // This name has no connection to the function, so it might get
175 // dead-stripped when the function is not, erroneously. Prohibit
176 // dead-stripping unconditionally.
177 if (const char *UsedDirective = TAI->getUsedDirective())
178 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
179 } else {
180 O << EHFrameInfo.FnName << ":\n";
181
182 // EH frame header.
183 EmitDifference("eh_frame_end", EHFrameInfo.Number,
184 "eh_frame_begin", EHFrameInfo.Number, true);
185 Asm->EOL("Length of Frame Information Entry");
186
187 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
188
Chris Lattnera4ff5e42009-07-17 20:53:51 +0000189 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
190 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
191 true, true, false);
Bill Wendlingeb907212009-05-15 01:12:28 +0000192
193 Asm->EOL("FDE CIE offset");
194
195 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
196 Asm->EOL("FDE initial location");
197 EmitDifference("eh_func_end", EHFrameInfo.Number,
198 "eh_func_begin", EHFrameInfo.Number, true);
199 Asm->EOL("FDE address range");
200
201 // If there is a personality and landing pads then point to the language
202 // specific data area in the exception table.
203 if (EHFrameInfo.PersonalityIndex) {
204 Asm->EmitULEB128Bytes(4);
205 Asm->EOL("Augmentation size");
206
207 if (EHFrameInfo.hasLandingPads)
208 EmitReference("exception", EHFrameInfo.Number, true, true);
209 else
210 Asm->EmitInt32((int)0);
211 Asm->EOL("Language Specific Data Area");
212 } else {
213 Asm->EmitULEB128Bytes(0);
214 Asm->EOL("Augmentation size");
215 }
216
217 // Indicate locations of function specific callee saved registers in frame.
218 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
219 true);
220
221 // On Darwin the linker honors the alignment of eh_frame, which means it
222 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
223 // get holes which confuse readers of eh_frame.
224 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
225 0, 0, false);
226 EmitLabel("eh_frame_end", EHFrameInfo.Number);
227
228 // If the function is marked used, this table should be also. We cannot
229 // make the mark unconditional in this case, since retaining the table also
230 // retains the function in this case, and there is code around that depends
231 // on unused functions (calling undefined externals) being dead-stripped to
232 // link correctly. Yes, there really is.
Chris Lattner401e10c2009-07-20 06:14:25 +0000233 if (MMI->isUsedFunction(EHFrameInfo.function))
Bill Wendlingeb907212009-05-15 01:12:28 +0000234 if (const char *UsedDirective = TAI->getUsedDirective())
235 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
236 }
237}
238
Bill Wendlingeb907212009-05-15 01:12:28 +0000239/// SharedTypeIds - How many leading type ids two landing pads have in common.
240unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
241 const LandingPadInfo *R) {
242 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
243 unsigned LSize = LIds.size(), RSize = RIds.size();
244 unsigned MinSize = LSize < RSize ? LSize : RSize;
245 unsigned Count = 0;
246
247 for (; Count != MinSize; ++Count)
248 if (LIds[Count] != RIds[Count])
249 return Count;
250
251 return Count;
252}
253
254/// PadLT - Order landing pads lexicographically by type id.
255bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
256 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
257 unsigned LSize = LIds.size(), RSize = RIds.size();
258 unsigned MinSize = LSize < RSize ? LSize : RSize;
259
260 for (unsigned i = 0; i != MinSize; ++i)
261 if (LIds[i] != RIds[i])
262 return LIds[i] < RIds[i];
263
264 return LSize < RSize;
265}
266
Bill Wendlingd4609622009-07-28 23:23:00 +0000267/// ComputeActionsTable - Compute the actions table and gather the first action
268/// index for each landing pad site.
Bill Wendlingade025c2009-07-29 00:31:35 +0000269unsigned DwarfException::
270ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
271 SmallVectorImpl<ActionEntry> &Actions,
272 SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000273 // Negative type IDs index into FilterIds. Positive type IDs index into
274 // TypeInfos. The value written for a positive type ID is just the type ID
275 // itself. For a negative type ID, however, the value written is the
Bill Wendlingeb907212009-05-15 01:12:28 +0000276 // (negative) byte offset of the corresponding FilterIds entry. The byte
Bill Wendling5e953dd2009-07-28 23:22:13 +0000277 // offset is usually equal to the type ID (because the FilterIds entries are
278 // written using a variable width encoding, which outputs one byte per entry
279 // as long as the value written is not too large) but can differ. This kind
280 // of complication does not occur for positive type IDs because type infos are
Bill Wendlingeb907212009-05-15 01:12:28 +0000281 // output using a fixed width encoding. FilterOffsets[i] holds the byte
282 // offset corresponding to FilterIds[i].
Bill Wendling409914b2009-07-29 21:19:44 +0000283
284 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
Bill Wendlingeb907212009-05-15 01:12:28 +0000285 SmallVector<int, 16> FilterOffsets;
286 FilterOffsets.reserve(FilterIds.size());
287 int Offset = -1;
Bill Wendling409914b2009-07-29 21:19:44 +0000288
289 for (std::vector<unsigned>::const_iterator
290 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000291 FilterOffsets.push_back(Offset);
292 Offset -= TargetAsmInfo::getULEB128Size(*I);
293 }
294
Bill Wendlingeb907212009-05-15 01:12:28 +0000295 FirstActions.reserve(LandingPads.size());
296
297 int FirstAction = 0;
298 unsigned SizeActions = 0;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000299 const LandingPadInfo *PrevLPI = 0;
Bill Wendling409914b2009-07-29 21:19:44 +0000300
Bill Wendling5cff4872009-07-28 23:44:43 +0000301 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
Bill Wendling5e953dd2009-07-28 23:22:13 +0000302 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
303 const LandingPadInfo *LPI = *I;
304 const std::vector<int> &TypeIds = LPI->TypeIds;
305 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
Bill Wendlingeb907212009-05-15 01:12:28 +0000306 unsigned SizeSiteActions = 0;
307
308 if (NumShared < TypeIds.size()) {
309 unsigned SizeAction = 0;
310 ActionEntry *PrevAction = 0;
311
312 if (NumShared) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000313 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
Bill Wendlingeb907212009-05-15 01:12:28 +0000314 assert(Actions.size());
315 PrevAction = &Actions.back();
316 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
317 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
318
319 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
320 SizeAction -=
321 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
322 SizeAction += -PrevAction->NextAction;
323 PrevAction = PrevAction->Previous;
324 }
325 }
326
327 // Compute the actions.
Bill Wendling5e953dd2009-07-28 23:22:13 +0000328 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
329 int TypeID = TypeIds[J];
330 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
Bill Wendlingeb907212009-05-15 01:12:28 +0000331 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
332 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
333
334 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
335 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
336 SizeSiteActions += SizeAction;
337
338 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
339 Actions.push_back(Action);
Bill Wendlingeb907212009-05-15 01:12:28 +0000340 PrevAction = &Actions.back();
341 }
342
343 // Record the first action of the landing pad site.
344 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
345 } // else identical - re-use previous FirstAction
346
347 FirstActions.push_back(FirstAction);
348
349 // Compute this sites contribution to size.
350 SizeActions += SizeSiteActions;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000351
352 PrevLPI = LPI;
Bill Wendlingeb907212009-05-15 01:12:28 +0000353 }
354
Bill Wendling5e953dd2009-07-28 23:22:13 +0000355 return SizeActions;
356}
357
Bill Wendlingade025c2009-07-29 00:31:35 +0000358/// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
359/// has a try-range containing the call, a non-zero landing pad and an
360/// appropriate action. The entry for an ordinary call has a try-range
361/// containing the call and zero for the landing pad and the action. Calls
362/// marked 'nounwind' have no entry and must not be contained in the try-range
363/// of any entry - they form gaps in the table. Entries must be ordered by
364/// try-range address.
365void DwarfException::
366ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000367 std::map<unsigned,CallSiteEntry*> &CallSiteIndexMap,
Bill Wendlingade025c2009-07-29 00:31:35 +0000368 const RangeMapType &PadMap,
369 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
370 const SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000371 // The end label of the previous invoke or nounwind try-range.
372 unsigned LastLabel = 0;
373
374 // Whether there is a potentially throwing instruction (currently this means
375 // an ordinary call) between the end of the previous try-range and now.
376 bool SawPotentiallyThrowing = false;
377
Bill Wendling5cff4872009-07-28 23:44:43 +0000378 // Whether the last CallSite entry was for an invoke.
Bill Wendlingeb907212009-05-15 01:12:28 +0000379 bool PreviousIsInvoke = false;
380
381 // Visit all instructions in order of address.
382 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
383 I != E; ++I) {
384 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
385 MI != E; ++MI) {
386 if (!MI->isLabel()) {
387 SawPotentiallyThrowing |= MI->getDesc().isCall();
388 continue;
389 }
390
391 unsigned BeginLabel = MI->getOperand(0).getImm();
392 assert(BeginLabel && "Invalid label!");
393
394 // End of the previous try-range?
395 if (BeginLabel == LastLabel)
396 SawPotentiallyThrowing = false;
397
398 // Beginning of a new try-range?
399 RangeMapType::iterator L = PadMap.find(BeginLabel);
400 if (L == PadMap.end())
401 // Nope, it was just some random label.
402 continue;
403
404 PadRange P = L->second;
405 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
Bill Wendlingeb907212009-05-15 01:12:28 +0000406 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
407 "Inconsistent landing pad map!");
408
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000409 // For Dwarf exception handling (SjLj handling doesn't use this)
Bill Wendlingeb907212009-05-15 01:12:28 +0000410 // If some instruction between the previous try-range and this one may
411 // throw, create a call-site entry with no landing pad for the region
412 // between the try-ranges.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000413 if (SawPotentiallyThrowing &&
414 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000415 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
416 CallSites.push_back(Site);
417 PreviousIsInvoke = false;
418 }
419
420 LastLabel = LandingPad->EndLabels[P.RangeIndex];
421 assert(BeginLabel && LastLabel && "Invalid landing pad!");
422
423 if (LandingPad->LandingPadLabel) {
424 // This try-range is for an invoke.
425 CallSiteEntry Site = {BeginLabel, LastLabel,
426 LandingPad->LandingPadLabel,
427 FirstActions[P.PadIndex]};
428
429 // Try to merge with the previous call-site.
430 if (PreviousIsInvoke) {
431 CallSiteEntry &Prev = CallSites.back();
432 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
433 // Extend the range of the previous entry.
434 Prev.EndLabel = Site.EndLabel;
435 continue;
436 }
437 }
438
439 // Otherwise, create a new call-site.
440 CallSites.push_back(Site);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000441 // For SjLj handling, map the call site entry to its index
442 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
443 unsigned Index =
444 MF->getLandingPadCallSiteIndex(LandingPad->LandingPadBlock);
445 CallSiteIndexMap[Index] = &CallSites.back();
446 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000447 PreviousIsInvoke = true;
448 } else {
449 // Create a gap.
450 PreviousIsInvoke = false;
451 }
452 }
453 }
454
455 // If some instruction between the previous try-range and the end of the
456 // function may throw, create a call-site entry with no landing pad for the
457 // region following the try-range.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000458 if (SawPotentiallyThrowing &&
459 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000460 CallSiteEntry Site = {LastLabel, 0, 0, 0};
461 CallSites.push_back(Site);
462 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000463}
464
Bill Wendling0dafca92009-07-29 00:50:05 +0000465/// EmitExceptionTable - Emit landing pads and actions.
466///
467/// The general organization of the table is complex, but the basic concepts are
468/// easy. First there is a header which describes the location and organization
469/// of the three components that follow.
470///
471/// 1. The landing pad site information describes the range of code covered by
472/// the try. In our case it's an accumulation of the ranges covered by the
473/// invokes in the try. There is also a reference to the landing pad that
474/// handles the exception once processed. Finally an index into the actions
475/// table.
476/// 2. The action table, in our case, is composed of pairs of type ids and next
477/// action offset. Starting with the action index from the landing pad
478/// site, each type Id is checked for a match to the current exception. If
479/// it matches then the exception and type id are passed on to the landing
480/// pad. Otherwise the next action is looked up. This chain is terminated
481/// with a next action of zero. If no type id is found the the frame is
482/// unwound and handling continues.
483/// 3. Type id table contains references to all the C++ typeinfo for all
484/// catches in the function. This tables is reversed indexed base 1.
Bill Wendlingade025c2009-07-29 00:31:35 +0000485void DwarfException::EmitExceptionTable() {
486 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
487 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
488 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
489 if (PadInfos.empty()) return;
490
491 // Sort the landing pads in order of their type ids. This is used to fold
492 // duplicate actions.
493 SmallVector<const LandingPadInfo *, 64> LandingPads;
494 LandingPads.reserve(PadInfos.size());
495
496 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
497 LandingPads.push_back(&PadInfos[i]);
498
499 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
500
501 // Compute the actions table and gather the first action index for each
502 // landing pad site.
503 SmallVector<ActionEntry, 32> Actions;
504 SmallVector<unsigned, 64> FirstActions;
505 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
506
507 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
508 // by try-range labels when lowered). Ordinary calls do not, so appropriate
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000509 // try-ranges for them need be deduced when using Dwarf exception handling.
Bill Wendlingade025c2009-07-29 00:31:35 +0000510 RangeMapType PadMap;
511 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
512 const LandingPadInfo *LandingPad = LandingPads[i];
513 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
514 unsigned BeginLabel = LandingPad->BeginLabels[j];
515 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
516 PadRange P = { i, j };
517 PadMap[BeginLabel] = P;
518 }
519 }
520
521 // Compute the call-site table.
522 SmallVector<CallSiteEntry, 64> CallSites;
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000523 std::map<unsigned,CallSiteEntry*> CallSiteIndexMap;
524 ComputeCallSiteTable(CallSites, CallSiteIndexMap, PadMap,
525 LandingPads, FirstActions);
Bill Wendlingeb907212009-05-15 01:12:28 +0000526
527 // Final tallies.
528
529 // Call sites.
530 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
531 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
532 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000533 unsigned SizeSites;
534 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
535 SizeSites = (MF->getMaxCallSiteIndex() - CallSites.size()) *
536 TargetAsmInfo::getULEB128Size(0) * 2;
537 } else
538 SizeSites = CallSites.size() *
539 (SiteStartSize + SiteLengthSize + LandingPadSize);
540 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000541 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000542 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
543 SizeSites += TargetAsmInfo::getULEB128Size(i);
544 // FIXME: 'i' above should be the landing pad index
545 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000546 // Type infos.
547 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
548 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
549
550 unsigned TypeOffset = sizeof(int8_t) + // Call site format
551 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
552 SizeSites + SizeActions + SizeTypes;
553
554 unsigned TotalSize = sizeof(int8_t) + // LPStart format
555 sizeof(int8_t) + // TType format
556 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
557 TypeOffset;
558
559 unsigned SizeAlign = (4 - TotalSize) & 3;
560
561 // Begin the exception table.
Chris Lattnerd5bbb072009-08-02 01:34:32 +0000562 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
563 Asm->SwitchToSection(LSDASection);
Bill Wendlingeb907212009-05-15 01:12:28 +0000564 Asm->EmitAlignment(2, 0, 0, false);
565 O << "GCC_except_table" << SubprogramCount << ":\n";
566
567 for (unsigned i = 0; i != SizeAlign; ++i) {
568 Asm->EmitInt8(0);
569 Asm->EOL("Padding");
Bill Wendlingc5800a82009-07-28 21:54:03 +0000570 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000571
572 EmitLabel("exception", SubprogramCount);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000573 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
574 std::string SjLjName = "_lsda_";
575 SjLjName += MF->getFunction()->getName().str();
576 EmitLabel(SjLjName.c_str(), 0);
577 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000578
579 // Emit the header.
580 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
581 Asm->EOL("LPStart format (DW_EH_PE_omit)");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000582
Bill Wendlingade025c2009-07-29 00:31:35 +0000583#if 0
Chris Lattner81c9a062009-07-31 22:03:47 +0000584 if (TypeInfos.empty() && FilterIds.empty()) {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000585 // If there are no typeinfos or filters, there is nothing to emit, optimize
586 // by specifying the "omit" encoding.
Chris Lattner81c9a062009-07-31 22:03:47 +0000587 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
588 Asm->EOL("TType format (DW_EH_PE_omit)");
589 } else {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000590 // Okay, we have actual filters or typeinfos to emit. As such, we need to
591 // pick a type encoding for them. We're about to emit a list of pointers to
592 // typeinfo objects at the end of the LSDA. However, unless we're in static
593 // mode, this reference will require a relocation by the dynamic linker.
Chris Lattner46b754c2009-07-31 22:18:14 +0000594 //
Chris Lattnerad88bc42009-08-02 03:59:56 +0000595 // Because of this, we have a couple of options:
596 // 1) If we are in -static mode, we can always use an absolute reference
597 // from the LSDA, because the static linker will resolve it.
598 // 2) Otherwise, if the LSDA section is writable, we can output the direct
599 // reference to the typeinfo and allow the dynamic linker to relocate
600 // it. Since it is in a writable section, the dynamic linker won't
601 // have a problem.
602 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
603 // we need to use some form of indirection. For example, on Darwin,
604 // we can output a statically-relocatable reference to a dyld stub. The
605 // offset to the stub is constant, but the contents are in a section
606 // that is updated by the dynamic linker. This is easy enough, but we
607 // need to tell the personality function of the unwinder to indirect
608 // through the dyld stub.
609 //
610 // FIXME: When this is actually implemented, we'll have to emit the stubs
611 // somewhere. This predicate should be moved to a shared location that is
612 // in target-independent code.
613 //
614 if (LSDASection->isWritable() ||
615 Asm->TM.getRelocationModel() == Reloc::Static) {
616 Asm->EmitInt8(DW_EH_PE_absptr);
617 Asm->EOL("TType format (DW_EH_PE_absptr)");
618 } else {
619 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
620 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
621 " | DW_EH_PE_sdata4)");
622 }
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000623 Asm->EmitULEB128Bytes(TypeOffset);
624 Asm->EOL("TType base offset");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000625 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000626#else
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000627 // For SjLj exceptions, is there is no TypeInfo, then we just explicitly
628 // say that we're omitting that bit.
629 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
630 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj
631 && (TypeInfos.empty() || FilterIds.empty())) {
632 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
633 Asm->EOL("TType format (DW_EH_PE_omit)");
634 } else {
635 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
636 Asm->EOL("TType format (DW_EH_PE_absptr)");
637 Asm->EmitULEB128Bytes(TypeOffset);
638 Asm->EOL("TType base offset");
639 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000640#endif
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000641
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000642 // SjLj Exception handilng
643 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
644 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
645 Asm->EOL("Call site format (DW_EH_PE_udata4)");
646 Asm->EmitULEB128Bytes(SizeSites);
647 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000648
Bill Wendlingeb907212009-05-15 01:12:28 +0000649
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000650 assert(MF->getCallSiteCount() == CallSites.size());
651
652 // Emit the landing pad site information.
653 // SjLj handling assigned the call site indices in the front end, so
654 // we need to make sure the table here lines up with that. That's pretty
655 // horrible, and should be fixed ASAP to do that stuff in the back end
656 // instead.
657 std::map<unsigned, CallSiteEntry*>::const_iterator I, E;
658 I = CallSiteIndexMap.begin();
659 E = CallSiteIndexMap.end();
660 for (unsigned CurrIdx = 1; I != E; ++I) {
661 // paranoia.
662 assert(CurrIdx <= I->first);
663 // Fill in any gaps in the table
664 while (CurrIdx++ < I->first) {
665 Asm->EmitULEB128Bytes(0);
666 Asm->EOL("Filler landing pad");
667 Asm->EmitULEB128Bytes(0);
668 Asm->EOL("Filler action");
669 }
670 const CallSiteEntry &S = *(I->second);
671 Asm->EmitULEB128Bytes(I->first - 1);
672 Asm->EOL("Landing pad");
673 Asm->EmitULEB128Bytes(S.Action);
674 Asm->EOL("Action");
Bill Wendlingeb907212009-05-15 01:12:28 +0000675 }
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000676 } else {
677 // DWARF Exception handling
678 assert(TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
Bill Wendlingeb907212009-05-15 01:12:28 +0000679
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000680 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
681 Asm->EOL("Call site format (DW_EH_PE_udata4)");
682 Asm->EmitULEB128Bytes(SizeSites);
683 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000684
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000685 // Emit the landing pad site information.
686 for (SmallVectorImpl<CallSiteEntry>::const_iterator
687 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
688 const CallSiteEntry &S = *I;
689 const char *BeginTag;
690 unsigned BeginNumber;
Bill Wendlingeb907212009-05-15 01:12:28 +0000691
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000692 if (!S.BeginLabel) {
693 BeginTag = "eh_func_begin";
694 BeginNumber = SubprogramCount;
695 } else {
696 BeginTag = "label";
697 BeginNumber = S.BeginLabel;
698 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000699
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000700 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
Bill Wendlingeb907212009-05-15 01:12:28 +0000701 true, true);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000702 Asm->EOL("Region start");
Bill Wendlingeb907212009-05-15 01:12:28 +0000703
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000704 if (!S.EndLabel)
705 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
706 true);
707 else
708 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
Bill Wendlingeb907212009-05-15 01:12:28 +0000709
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000710 Asm->EOL("Region length");
711
712 if (!S.PadLabel)
713 Asm->EmitInt32(0);
714 else
715 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
716 true, true);
717
718 Asm->EOL("Landing pad");
719
720 Asm->EmitULEB128Bytes(S.Action);
721 Asm->EOL("Action");
722 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000723 }
724
725 // Emit the actions.
Bill Wendling5cff4872009-07-28 23:44:43 +0000726 for (SmallVectorImpl<ActionEntry>::const_iterator
727 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
728 const ActionEntry &Action = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000729 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
730 Asm->EOL("TypeInfo index");
731 Asm->EmitSLEB128Bytes(Action.NextAction);
732 Asm->EOL("Next action");
733 }
734
735 // Emit the type ids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000736 for (std::vector<GlobalVariable *>::const_reverse_iterator
737 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
738 GlobalVariable *GV = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000739 PrintRelDirective();
740
741 if (GV) {
742 std::string GLN;
743 O << Asm->getGlobalLinkName(GV, GLN);
744 } else {
745 O << "0";
746 }
747
748 Asm->EOL("TypeInfo");
749 }
750
751 // Emit the filter typeids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000752 for (std::vector<unsigned>::const_iterator
753 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
754 unsigned TypeID = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000755 Asm->EmitULEB128Bytes(TypeID);
756 Asm->EOL("Filter TypeInfo index");
757 }
758
759 Asm->EmitAlignment(2, 0, 0, false);
760}
761
Bill Wendlingeb907212009-05-15 01:12:28 +0000762/// EndModule - Emit all exception information that should come after the
763/// content.
764void DwarfException::EndModule() {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000765 if (TAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
766 return;
Bill Wendlingeb907212009-05-15 01:12:28 +0000767 if (TimePassesIsEnabled)
768 ExceptionTimer->startTimer();
769
770 if (shouldEmitMovesModule || shouldEmitTableModule) {
771 const std::vector<Function *> Personalities = MMI->getPersonalities();
772 for (unsigned i = 0; i < Personalities.size(); ++i)
773 EmitCommonEHFrame(Personalities[i], i);
774
775 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
776 E = EHFrames.end(); I != E; ++I)
777 EmitEHFrame(*I);
778 }
779
780 if (TimePassesIsEnabled)
781 ExceptionTimer->stopTimer();
782}
783
784/// BeginFunction - Gather pre-function exception information. Assumes being
785/// emitted immediately after the function entry point.
786void DwarfException::BeginFunction(MachineFunction *MF) {
787 if (TimePassesIsEnabled)
788 ExceptionTimer->startTimer();
789
790 this->MF = MF;
791 shouldEmitTable = shouldEmitMoves = false;
792
793 if (MMI && TAI->doesSupportExceptionHandling()) {
794 // Map all labels and get rid of any dead landing pads.
795 MMI->TidyLandingPads();
796
797 // If any landing pads survive, we need an EH table.
798 if (MMI->getLandingPads().size())
799 shouldEmitTable = true;
800
801 // See if we need frame move info.
802 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
803 shouldEmitMoves = true;
804
805 if (shouldEmitMoves || shouldEmitTable)
806 // Assumes in correct section after the entry point.
807 EmitLabel("eh_func_begin", ++SubprogramCount);
808 }
809
810 shouldEmitTableModule |= shouldEmitTable;
811 shouldEmitMovesModule |= shouldEmitMoves;
812
813 if (TimePassesIsEnabled)
814 ExceptionTimer->stopTimer();
815}
816
817/// EndFunction - Gather and emit post-function exception information.
818///
819void DwarfException::EndFunction() {
820 if (TimePassesIsEnabled)
821 ExceptionTimer->startTimer();
822
823 if (shouldEmitMoves || shouldEmitTable) {
824 EmitLabel("eh_func_end", SubprogramCount);
825 EmitExceptionTable();
826
827 // Save EH frame information
Bill Wendlingeb907212009-05-15 01:12:28 +0000828 EHFrames.push_back(
Chris Lattnere2cf37b2009-07-17 20:46:40 +0000829 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
Bill Wendlingeb907212009-05-15 01:12:28 +0000830 SubprogramCount,
831 MMI->getPersonalityIndex(),
832 MF->getFrameInfo()->hasCalls(),
833 !MMI->getLandingPads().empty(),
834 MMI->getFrameMoves(),
835 MF->getFunction()));
836 }
837
838 if (TimePassesIsEnabled)
839 ExceptionTimer->stopTimer();
840}