blob: aacb33b28f91c3a9984078c2edd4b1d6abdc5994 [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"
Chris Lattner6c2f9e12009-08-19 05:49:37 +000019#include "llvm/MC/MCStreamer.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000020#include "llvm/Target/TargetAsmInfo.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000021#include "llvm/Target/TargetData.h"
22#include "llvm/Target/TargetFrameInfo.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000023#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000024#include "llvm/Target/TargetOptions.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000025#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner6c2f9e12009-08-19 05:49:37 +000026#include "llvm/Support/Dwarf.h"
27#include "llvm/Support/Timer.h"
28#include "llvm/Support/raw_ostream.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000029#include "llvm/ADT/StringExtras.h"
30using namespace llvm;
31
32static TimerGroup &getDwarfTimerGroup() {
33 static TimerGroup DwarfTimerGroup("Dwarf Exception");
34 return DwarfTimerGroup;
35}
36
Bill Wendlingbc0d23a2009-05-15 01:18:50 +000037DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
38 const TargetAsmInfo *T)
39 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
40 shouldEmitTableModule(false), shouldEmitMovesModule(false),
41 ExceptionTimer(0) {
42 if (TimePassesIsEnabled)
43 ExceptionTimer = new Timer("Dwarf Exception Writer",
44 getDwarfTimerGroup());
45}
46
47DwarfException::~DwarfException() {
48 delete ExceptionTimer;
49}
50
Bill Wendlingeb907212009-05-15 01:12:28 +000051void DwarfException::EmitCommonEHFrame(const Function *Personality,
52 unsigned Index) {
53 // Size and sign of stack growth.
54 int stackGrowth =
55 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
56 TargetFrameInfo::StackGrowsUp ?
57 TD->getPointerSize() : -TD->getPointerSize();
58
59 // Begin eh frame section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +000060 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
Bill Wendlingeb907212009-05-15 01:12:28 +000061
Chris Lattnere2cf37b2009-07-17 20:46:40 +000062 if (TAI->is_EHSymbolPrivate())
63 O << TAI->getPrivateGlobalPrefix();
Bill Wendlingeb907212009-05-15 01:12:28 +000064
65 O << "EH_frame" << Index << ":\n";
66 EmitLabel("section_eh_frame", Index);
67
68 // Define base labels.
69 EmitLabel("eh_frame_common", Index);
70
71 // Define the eh frame length.
72 EmitDifference("eh_frame_common_end", Index,
73 "eh_frame_common_begin", Index, true);
74 Asm->EOL("Length of Common Information Entry");
75
76 // EH frame header.
77 EmitLabel("eh_frame_common_begin", Index);
78 Asm->EmitInt32((int)0);
79 Asm->EOL("CIE Identifier Tag");
80 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
81 Asm->EOL("CIE Version");
82
83 // The personality presence indicates that language specific information will
84 // show up in the eh frame.
85 Asm->EmitString(Personality ? "zPLR" : "zR");
86 Asm->EOL("CIE Augmentation");
87
88 // Round out reader.
89 Asm->EmitULEB128Bytes(1);
90 Asm->EOL("CIE Code Alignment Factor");
91 Asm->EmitSLEB128Bytes(stackGrowth);
92 Asm->EOL("CIE Data Alignment Factor");
93 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
94 Asm->EOL("CIE Return Address Column");
95
96 // If there is a personality, we need to indicate the functions location.
97 if (Personality) {
98 Asm->EmitULEB128Bytes(7);
99 Asm->EOL("Augmentation Size");
100
101 if (TAI->getNeedsIndirectEncoding()) {
102 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
103 dwarf::DW_EH_PE_indirect);
104 Asm->EOL("Personality (pcrel sdata4 indirect)");
105 } else {
106 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
107 Asm->EOL("Personality (pcrel sdata4)");
108 }
109
110 PrintRelDirective(true);
111 O << TAI->getPersonalityPrefix();
112 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
113 O << TAI->getPersonalitySuffix();
114 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
115 O << "-" << TAI->getPCSymbol();
116 Asm->EOL("Personality");
117
118 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
119 Asm->EOL("LSDA Encoding (pcrel sdata4)");
120
121 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
122 Asm->EOL("FDE Encoding (pcrel sdata4)");
123 } else {
124 Asm->EmitULEB128Bytes(1);
125 Asm->EOL("Augmentation Size");
126
127 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
128 Asm->EOL("FDE Encoding (pcrel sdata4)");
129 }
130
131 // Indicate locations of general callee saved registers in frame.
132 std::vector<MachineMove> Moves;
133 RI->getInitialFrameState(Moves);
134 EmitFrameMoves(NULL, 0, Moves, true);
135
136 // On Darwin the linker honors the alignment of eh_frame, which means it must
137 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
138 // holes which confuse readers of eh_frame.
139 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
140 0, 0, false);
141 EmitLabel("eh_frame_common_end", Index);
142
143 Asm->EOL();
144}
145
146/// EmitEHFrame - Emit function exception frame information.
147///
148void DwarfException::EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
149 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
150 "Should not emit 'available externally' functions at all");
151
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000152 const Function *TheFunc = EHFrameInfo.function;
153
Chris Lattner6c2f9e12009-08-19 05:49:37 +0000154 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
Chris Lattner6a66e582009-08-18 06:13:03 +0000155
Bill Wendlingeb907212009-05-15 01:12:28 +0000156 // Externally visible entry into the functions eh frame info. If the
157 // corresponding function is static, this should not be externally visible.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000158 if (!TheFunc->hasLocalLinkage())
Bill Wendlingeb907212009-05-15 01:12:28 +0000159 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
160 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
Bill Wendlingeb907212009-05-15 01:12:28 +0000161
162 // If corresponding function is weak definition, this should be too.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000163 if (TheFunc->isWeakForLinker() && TAI->getWeakDefDirective())
Bill Wendlingeb907212009-05-15 01:12:28 +0000164 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
165
166 // If there are no calls then you can't unwind. This may mean we can omit the
167 // EH Frame, but some environments do not handle weak absolute symbols. If
168 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
169 // info is to be available for non-EH uses.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000170 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
171 (!TheFunc->isWeakForLinker() ||
Bill Wendlingeb907212009-05-15 01:12:28 +0000172 !TAI->getWeakDefDirective() ||
173 TAI->getSupportsWeakOmittedEHFrame())) {
174 O << EHFrameInfo.FnName << " = 0\n";
175 // This name has no connection to the function, so it might get
176 // dead-stripped when the function is not, erroneously. Prohibit
177 // dead-stripping unconditionally.
178 if (const char *UsedDirective = TAI->getUsedDirective())
179 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
180 } else {
181 O << EHFrameInfo.FnName << ":\n";
182
183 // EH frame header.
184 EmitDifference("eh_frame_end", EHFrameInfo.Number,
185 "eh_frame_begin", EHFrameInfo.Number, true);
186 Asm->EOL("Length of Frame Information Entry");
187
188 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
189
Chris Lattnera4ff5e42009-07-17 20:53:51 +0000190 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
191 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
192 true, true, false);
Bill Wendlingeb907212009-05-15 01:12:28 +0000193
194 Asm->EOL("FDE CIE offset");
195
196 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
197 Asm->EOL("FDE initial location");
198 EmitDifference("eh_func_end", EHFrameInfo.Number,
199 "eh_func_begin", EHFrameInfo.Number, true);
200 Asm->EOL("FDE address range");
201
202 // If there is a personality and landing pads then point to the language
203 // specific data area in the exception table.
204 if (EHFrameInfo.PersonalityIndex) {
205 Asm->EmitULEB128Bytes(4);
206 Asm->EOL("Augmentation size");
207
208 if (EHFrameInfo.hasLandingPads)
209 EmitReference("exception", EHFrameInfo.Number, true, true);
210 else
211 Asm->EmitInt32((int)0);
212 Asm->EOL("Language Specific Data Area");
213 } else {
214 Asm->EmitULEB128Bytes(0);
215 Asm->EOL("Augmentation size");
216 }
217
218 // Indicate locations of function specific callee saved registers in frame.
219 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
220 true);
221
222 // On Darwin the linker honors the alignment of eh_frame, which means it
223 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
224 // get holes which confuse readers of eh_frame.
225 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
226 0, 0, false);
227 EmitLabel("eh_frame_end", EHFrameInfo.Number);
228
229 // If the function is marked used, this table should be also. We cannot
230 // make the mark unconditional in this case, since retaining the table also
231 // retains the function in this case, and there is code around that depends
232 // on unused functions (calling undefined externals) being dead-stripped to
233 // link correctly. Yes, there really is.
Chris Lattner401e10c2009-07-20 06:14:25 +0000234 if (MMI->isUsedFunction(EHFrameInfo.function))
Bill Wendlingeb907212009-05-15 01:12:28 +0000235 if (const char *UsedDirective = TAI->getUsedDirective())
236 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
237 }
238}
239
Bill Wendlingeb907212009-05-15 01:12:28 +0000240/// SharedTypeIds - How many leading type ids two landing pads have in common.
241unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
242 const LandingPadInfo *R) {
243 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
244 unsigned LSize = LIds.size(), RSize = RIds.size();
245 unsigned MinSize = LSize < RSize ? LSize : RSize;
246 unsigned Count = 0;
247
248 for (; Count != MinSize; ++Count)
249 if (LIds[Count] != RIds[Count])
250 return Count;
251
252 return Count;
253}
254
255/// PadLT - Order landing pads lexicographically by type id.
256bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
257 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
258 unsigned LSize = LIds.size(), RSize = RIds.size();
259 unsigned MinSize = LSize < RSize ? LSize : RSize;
260
261 for (unsigned i = 0; i != MinSize; ++i)
262 if (LIds[i] != RIds[i])
263 return LIds[i] < RIds[i];
264
265 return LSize < RSize;
266}
267
Bill Wendlingd4609622009-07-28 23:23:00 +0000268/// ComputeActionsTable - Compute the actions table and gather the first action
269/// index for each landing pad site.
Bill Wendlingade025c2009-07-29 00:31:35 +0000270unsigned DwarfException::
271ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
272 SmallVectorImpl<ActionEntry> &Actions,
273 SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000274 // Negative type IDs index into FilterIds. Positive type IDs index into
275 // TypeInfos. The value written for a positive type ID is just the type ID
276 // itself. For a negative type ID, however, the value written is the
Bill Wendlingeb907212009-05-15 01:12:28 +0000277 // (negative) byte offset of the corresponding FilterIds entry. The byte
Bill Wendling5e953dd2009-07-28 23:22:13 +0000278 // offset is usually equal to the type ID (because the FilterIds entries are
279 // written using a variable width encoding, which outputs one byte per entry
280 // as long as the value written is not too large) but can differ. This kind
281 // of complication does not occur for positive type IDs because type infos are
Bill Wendlingeb907212009-05-15 01:12:28 +0000282 // output using a fixed width encoding. FilterOffsets[i] holds the byte
283 // offset corresponding to FilterIds[i].
Bill Wendling409914b2009-07-29 21:19:44 +0000284
285 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
Bill Wendlingeb907212009-05-15 01:12:28 +0000286 SmallVector<int, 16> FilterOffsets;
287 FilterOffsets.reserve(FilterIds.size());
288 int Offset = -1;
Bill Wendling409914b2009-07-29 21:19:44 +0000289
290 for (std::vector<unsigned>::const_iterator
291 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000292 FilterOffsets.push_back(Offset);
293 Offset -= TargetAsmInfo::getULEB128Size(*I);
294 }
295
Bill Wendlingeb907212009-05-15 01:12:28 +0000296 FirstActions.reserve(LandingPads.size());
297
298 int FirstAction = 0;
299 unsigned SizeActions = 0;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000300 const LandingPadInfo *PrevLPI = 0;
Bill Wendling409914b2009-07-29 21:19:44 +0000301
Bill Wendling5cff4872009-07-28 23:44:43 +0000302 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
Bill Wendling5e953dd2009-07-28 23:22:13 +0000303 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
304 const LandingPadInfo *LPI = *I;
305 const std::vector<int> &TypeIds = LPI->TypeIds;
306 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
Bill Wendlingeb907212009-05-15 01:12:28 +0000307 unsigned SizeSiteActions = 0;
308
309 if (NumShared < TypeIds.size()) {
310 unsigned SizeAction = 0;
311 ActionEntry *PrevAction = 0;
312
313 if (NumShared) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000314 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
Bill Wendlingeb907212009-05-15 01:12:28 +0000315 assert(Actions.size());
316 PrevAction = &Actions.back();
317 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
318 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
319
320 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
321 SizeAction -=
322 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
323 SizeAction += -PrevAction->NextAction;
324 PrevAction = PrevAction->Previous;
325 }
326 }
327
328 // Compute the actions.
Bill Wendling5e953dd2009-07-28 23:22:13 +0000329 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
330 int TypeID = TypeIds[J];
331 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
Bill Wendlingeb907212009-05-15 01:12:28 +0000332 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
333 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
334
335 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
336 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
337 SizeSiteActions += SizeAction;
338
339 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
340 Actions.push_back(Action);
Bill Wendlingeb907212009-05-15 01:12:28 +0000341 PrevAction = &Actions.back();
342 }
343
344 // Record the first action of the landing pad site.
345 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
346 } // else identical - re-use previous FirstAction
347
348 FirstActions.push_back(FirstAction);
349
350 // Compute this sites contribution to size.
351 SizeActions += SizeSiteActions;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000352
353 PrevLPI = LPI;
Bill Wendlingeb907212009-05-15 01:12:28 +0000354 }
355
Bill Wendling5e953dd2009-07-28 23:22:13 +0000356 return SizeActions;
357}
358
Bill Wendlingade025c2009-07-29 00:31:35 +0000359/// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
360/// has a try-range containing the call, a non-zero landing pad and an
361/// appropriate action. The entry for an ordinary call has a try-range
362/// containing the call and zero for the landing pad and the action. Calls
363/// marked 'nounwind' have no entry and must not be contained in the try-range
364/// of any entry - they form gaps in the table. Entries must be ordered by
365/// try-range address.
366void DwarfException::
367ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
368 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);
441 PreviousIsInvoke = true;
442 } else {
443 // Create a gap.
444 PreviousIsInvoke = false;
445 }
446 }
447 }
448
449 // If some instruction between the previous try-range and the end of the
450 // function may throw, create a call-site entry with no landing pad for the
451 // region following the try-range.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000452 if (SawPotentiallyThrowing &&
453 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000454 CallSiteEntry Site = {LastLabel, 0, 0, 0};
455 CallSites.push_back(Site);
456 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000457}
458
Bill Wendling0dafca92009-07-29 00:50:05 +0000459/// EmitExceptionTable - Emit landing pads and actions.
460///
461/// The general organization of the table is complex, but the basic concepts are
462/// easy. First there is a header which describes the location and organization
463/// of the three components that follow.
464///
465/// 1. The landing pad site information describes the range of code covered by
466/// the try. In our case it's an accumulation of the ranges covered by the
467/// invokes in the try. There is also a reference to the landing pad that
468/// handles the exception once processed. Finally an index into the actions
469/// table.
470/// 2. The action table, in our case, is composed of pairs of type ids and next
471/// action offset. Starting with the action index from the landing pad
472/// site, each type Id is checked for a match to the current exception. If
473/// it matches then the exception and type id are passed on to the landing
474/// pad. Otherwise the next action is looked up. This chain is terminated
475/// with a next action of zero. If no type id is found the the frame is
476/// unwound and handling continues.
477/// 3. Type id table contains references to all the C++ typeinfo for all
478/// catches in the function. This tables is reversed indexed base 1.
Bill Wendlingade025c2009-07-29 00:31:35 +0000479void DwarfException::EmitExceptionTable() {
480 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
481 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
482 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
483 if (PadInfos.empty()) return;
484
485 // Sort the landing pads in order of their type ids. This is used to fold
486 // duplicate actions.
487 SmallVector<const LandingPadInfo *, 64> LandingPads;
488 LandingPads.reserve(PadInfos.size());
489
490 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
491 LandingPads.push_back(&PadInfos[i]);
492
493 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
494
495 // Compute the actions table and gather the first action index for each
496 // landing pad site.
497 SmallVector<ActionEntry, 32> Actions;
498 SmallVector<unsigned, 64> FirstActions;
499 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
500
501 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
502 // by try-range labels when lowered). Ordinary calls do not, so appropriate
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000503 // try-ranges for them need be deduced when using Dwarf exception handling.
Bill Wendlingade025c2009-07-29 00:31:35 +0000504 RangeMapType PadMap;
505 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
506 const LandingPadInfo *LandingPad = LandingPads[i];
507 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
508 unsigned BeginLabel = LandingPad->BeginLabels[j];
509 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
510 PadRange P = { i, j };
511 PadMap[BeginLabel] = P;
512 }
513 }
514
515 // Compute the call-site table.
516 SmallVector<CallSiteEntry, 64> CallSites;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000517 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
Bill Wendlingeb907212009-05-15 01:12:28 +0000518
519 // Final tallies.
520
521 // Call sites.
522 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
523 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
524 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000525 unsigned SizeSites;
Jim Grosbachbff39232009-08-12 17:38:44 +0000526
527 bool HaveTTData = (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
528 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
529
530
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000531 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000532 SizeSites = 0;
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000533 } else
534 SizeSites = CallSites.size() *
535 (SiteStartSize + SiteLengthSize + LandingPadSize);
536 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000537 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000538 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
539 SizeSites += TargetAsmInfo::getULEB128Size(i);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000540 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000541 // Type infos.
542 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
543 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
544
545 unsigned TypeOffset = sizeof(int8_t) + // Call site format
546 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
547 SizeSites + SizeActions + SizeTypes;
548
549 unsigned TotalSize = sizeof(int8_t) + // LPStart format
550 sizeof(int8_t) + // TType format
Jim Grosbachbff39232009-08-12 17:38:44 +0000551 (HaveTTData ?
552 TargetAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
Bill Wendlingeb907212009-05-15 01:12:28 +0000553 TypeOffset;
554
555 unsigned SizeAlign = (4 - TotalSize) & 3;
556
557 // Begin the exception table.
Chris Lattnerd5bbb072009-08-02 01:34:32 +0000558 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
Chris Lattner6c2f9e12009-08-19 05:49:37 +0000559 Asm->OutStreamer.SwitchSection(LSDASection);
Bill Wendlingeb907212009-05-15 01:12:28 +0000560 Asm->EmitAlignment(2, 0, 0, false);
561 O << "GCC_except_table" << SubprogramCount << ":\n";
562
563 for (unsigned i = 0; i != SizeAlign; ++i) {
564 Asm->EmitInt8(0);
565 Asm->EOL("Padding");
Bill Wendlingc5800a82009-07-28 21:54:03 +0000566 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000567
568 EmitLabel("exception", SubprogramCount);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000569 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
570 std::string SjLjName = "_lsda_";
571 SjLjName += MF->getFunction()->getName().str();
572 EmitLabel(SjLjName.c_str(), 0);
573 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000574
575 // Emit the header.
576 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
577 Asm->EOL("LPStart format (DW_EH_PE_omit)");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000578
Bill Wendlingade025c2009-07-29 00:31:35 +0000579#if 0
Chris Lattner81c9a062009-07-31 22:03:47 +0000580 if (TypeInfos.empty() && FilterIds.empty()) {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000581 // If there are no typeinfos or filters, there is nothing to emit, optimize
582 // by specifying the "omit" encoding.
Chris Lattner81c9a062009-07-31 22:03:47 +0000583 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
584 Asm->EOL("TType format (DW_EH_PE_omit)");
585 } else {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000586 // Okay, we have actual filters or typeinfos to emit. As such, we need to
587 // pick a type encoding for them. We're about to emit a list of pointers to
588 // typeinfo objects at the end of the LSDA. However, unless we're in static
589 // mode, this reference will require a relocation by the dynamic linker.
Chris Lattner46b754c2009-07-31 22:18:14 +0000590 //
Chris Lattnerad88bc42009-08-02 03:59:56 +0000591 // Because of this, we have a couple of options:
592 // 1) If we are in -static mode, we can always use an absolute reference
593 // from the LSDA, because the static linker will resolve it.
594 // 2) Otherwise, if the LSDA section is writable, we can output the direct
595 // reference to the typeinfo and allow the dynamic linker to relocate
596 // it. Since it is in a writable section, the dynamic linker won't
597 // have a problem.
598 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
599 // we need to use some form of indirection. For example, on Darwin,
600 // we can output a statically-relocatable reference to a dyld stub. The
601 // offset to the stub is constant, but the contents are in a section
602 // that is updated by the dynamic linker. This is easy enough, but we
603 // need to tell the personality function of the unwinder to indirect
604 // through the dyld stub.
605 //
606 // FIXME: When this is actually implemented, we'll have to emit the stubs
607 // somewhere. This predicate should be moved to a shared location that is
608 // in target-independent code.
609 //
610 if (LSDASection->isWritable() ||
611 Asm->TM.getRelocationModel() == Reloc::Static) {
612 Asm->EmitInt8(DW_EH_PE_absptr);
613 Asm->EOL("TType format (DW_EH_PE_absptr)");
614 } else {
615 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
616 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
617 " | DW_EH_PE_sdata4)");
618 }
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000619 Asm->EmitULEB128Bytes(TypeOffset);
620 Asm->EOL("TType base offset");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000621 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000622#else
Jim Grosbachbff39232009-08-12 17:38:44 +0000623 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000624 // say that we're omitting that bit.
625 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
Jim Grosbachbff39232009-08-12 17:38:44 +0000626 if (!HaveTTData) {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000627 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
628 Asm->EOL("TType format (DW_EH_PE_omit)");
629 } else {
630 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
631 Asm->EOL("TType format (DW_EH_PE_absptr)");
632 Asm->EmitULEB128Bytes(TypeOffset);
633 Asm->EOL("TType base offset");
634 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000635#endif
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000636
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000637 // SjLj Exception handilng
638 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
639 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
640 Asm->EOL("Call site format (DW_EH_PE_udata4)");
641 Asm->EmitULEB128Bytes(SizeSites);
642 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000643
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000644 // Emit the landing pad site information.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000645 unsigned idx = 0;
646 for (SmallVectorImpl<CallSiteEntry>::const_iterator
647 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
648 const CallSiteEntry &S = *I;
649 Asm->EmitULEB128Bytes(idx);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000650 Asm->EOL("Landing pad");
651 Asm->EmitULEB128Bytes(S.Action);
652 Asm->EOL("Action");
Bill Wendlingeb907212009-05-15 01:12:28 +0000653 }
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000654 } else {
655 // DWARF Exception handling
656 assert(TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
Bill Wendlingeb907212009-05-15 01:12:28 +0000657
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000658 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
659 Asm->EOL("Call site format (DW_EH_PE_udata4)");
660 Asm->EmitULEB128Bytes(SizeSites);
661 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000662
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000663 // Emit the landing pad site information.
664 for (SmallVectorImpl<CallSiteEntry>::const_iterator
665 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
666 const CallSiteEntry &S = *I;
667 const char *BeginTag;
668 unsigned BeginNumber;
Bill Wendlingeb907212009-05-15 01:12:28 +0000669
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000670 if (!S.BeginLabel) {
671 BeginTag = "eh_func_begin";
672 BeginNumber = SubprogramCount;
673 } else {
674 BeginTag = "label";
675 BeginNumber = S.BeginLabel;
676 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000677
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000678 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
Bill Wendlingeb907212009-05-15 01:12:28 +0000679 true, true);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000680 Asm->EOL("Region start");
Bill Wendlingeb907212009-05-15 01:12:28 +0000681
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000682 if (!S.EndLabel)
683 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
684 true);
685 else
686 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
Bill Wendlingeb907212009-05-15 01:12:28 +0000687
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000688 Asm->EOL("Region length");
689
690 if (!S.PadLabel)
691 Asm->EmitInt32(0);
692 else
693 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
694 true, true);
695
696 Asm->EOL("Landing pad");
697
698 Asm->EmitULEB128Bytes(S.Action);
699 Asm->EOL("Action");
700 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000701 }
702
703 // Emit the actions.
Bill Wendling5cff4872009-07-28 23:44:43 +0000704 for (SmallVectorImpl<ActionEntry>::const_iterator
705 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
706 const ActionEntry &Action = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000707 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
708 Asm->EOL("TypeInfo index");
709 Asm->EmitSLEB128Bytes(Action.NextAction);
710 Asm->EOL("Next action");
711 }
712
713 // Emit the type ids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000714 for (std::vector<GlobalVariable *>::const_reverse_iterator
715 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
716 GlobalVariable *GV = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000717 PrintRelDirective();
718
719 if (GV) {
720 std::string GLN;
721 O << Asm->getGlobalLinkName(GV, GLN);
722 } else {
723 O << "0";
724 }
725
726 Asm->EOL("TypeInfo");
727 }
728
729 // Emit the filter typeids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000730 for (std::vector<unsigned>::const_iterator
731 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
732 unsigned TypeID = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000733 Asm->EmitULEB128Bytes(TypeID);
734 Asm->EOL("Filter TypeInfo index");
735 }
736
737 Asm->EmitAlignment(2, 0, 0, false);
738}
739
Bill Wendlingeb907212009-05-15 01:12:28 +0000740/// EndModule - Emit all exception information that should come after the
741/// content.
742void DwarfException::EndModule() {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000743 if (TAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
744 return;
Bill Wendlingeb907212009-05-15 01:12:28 +0000745 if (TimePassesIsEnabled)
746 ExceptionTimer->startTimer();
747
748 if (shouldEmitMovesModule || shouldEmitTableModule) {
749 const std::vector<Function *> Personalities = MMI->getPersonalities();
750 for (unsigned i = 0; i < Personalities.size(); ++i)
751 EmitCommonEHFrame(Personalities[i], i);
752
753 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
754 E = EHFrames.end(); I != E; ++I)
755 EmitEHFrame(*I);
756 }
757
758 if (TimePassesIsEnabled)
759 ExceptionTimer->stopTimer();
760}
761
762/// BeginFunction - Gather pre-function exception information. Assumes being
763/// emitted immediately after the function entry point.
764void DwarfException::BeginFunction(MachineFunction *MF) {
765 if (TimePassesIsEnabled)
766 ExceptionTimer->startTimer();
767
768 this->MF = MF;
769 shouldEmitTable = shouldEmitMoves = false;
770
771 if (MMI && TAI->doesSupportExceptionHandling()) {
772 // Map all labels and get rid of any dead landing pads.
773 MMI->TidyLandingPads();
774
775 // If any landing pads survive, we need an EH table.
776 if (MMI->getLandingPads().size())
777 shouldEmitTable = true;
778
779 // See if we need frame move info.
780 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
781 shouldEmitMoves = true;
782
783 if (shouldEmitMoves || shouldEmitTable)
784 // Assumes in correct section after the entry point.
785 EmitLabel("eh_func_begin", ++SubprogramCount);
786 }
787
788 shouldEmitTableModule |= shouldEmitTable;
789 shouldEmitMovesModule |= shouldEmitMoves;
790
791 if (TimePassesIsEnabled)
792 ExceptionTimer->stopTimer();
793}
794
795/// EndFunction - Gather and emit post-function exception information.
796///
797void DwarfException::EndFunction() {
798 if (TimePassesIsEnabled)
799 ExceptionTimer->startTimer();
800
801 if (shouldEmitMoves || shouldEmitTable) {
802 EmitLabel("eh_func_end", SubprogramCount);
803 EmitExceptionTable();
804
805 // Save EH frame information
Bill Wendlingeb907212009-05-15 01:12:28 +0000806 EHFrames.push_back(
Chris Lattnere2cf37b2009-07-17 20:46:40 +0000807 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
Bill Wendlingeb907212009-05-15 01:12:28 +0000808 SubprogramCount,
809 MMI->getPersonalityIndex(),
810 MF->getFrameInfo()->hasCalls(),
811 !MMI->getLandingPads().empty(),
812 MMI->getFrameMoves(),
813 MF->getFunction()));
814 }
815
816 if (TimePassesIsEnabled)
817 ExceptionTimer->stopTimer();
818}