make reassociate more careful about not leaving around dead mul's
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfException.cpp
1 //===-- 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/MachineFunction.h"
19 #include "llvm/CodeGen/MachineLocation.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Target/TargetLoweringObjectFile.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringExtras.h"
36 using namespace llvm;
37
38 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
39                                const MCAsmInfo *T)
40   : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
41     shouldEmitTableModule(false), shouldEmitMovesModule(false),
42     ExceptionTimer(0) {
43   if (TimePassesIsEnabled)
44     ExceptionTimer = new Timer("DWARF Exception Writer");
45 }
46
47 DwarfException::~DwarfException() {
48   delete ExceptionTimer;
49 }
50
51 /// SizeOfEncodedValue - Return the size of the encoding in bytes.
52 unsigned DwarfException::SizeOfEncodedValue(unsigned Encoding) {
53   if (Encoding == dwarf::DW_EH_PE_omit)
54     return 0;
55
56   switch (Encoding & 0x07) {
57   case dwarf::DW_EH_PE_absptr:
58     return TD->getPointerSize();
59   case dwarf::DW_EH_PE_udata2:
60     return 2;
61   case dwarf::DW_EH_PE_udata4:
62     return 4;
63   case dwarf::DW_EH_PE_udata8:
64     return 8;
65   }
66
67   assert(0 && "Invalid encoded value.");
68   return 0;
69 }
70
71 /// CreateLabelDiff - Emit a label and subtract it from the expression we
72 /// already have.  This is equivalent to emitting "foo - .", but we have to emit
73 /// the label for "." directly.
74 const MCExpr *DwarfException::CreateLabelDiff(const MCExpr *ExprRef,
75                                               const char *LabelName,
76                                               unsigned Index) {
77   SmallString<64> Name;
78   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
79                             << LabelName << Asm->getFunctionNumber()
80                             << "_" << Index;
81   MCSymbol *DotSym = Asm->OutContext.GetOrCreateSymbol(Name.str());
82   Asm->OutStreamer.EmitLabel(DotSym);
83
84   return MCBinaryExpr::CreateSub(ExprRef,
85                                  MCSymbolRefExpr::Create(DotSym,
86                                                          Asm->OutContext),
87                                  Asm->OutContext);
88 }
89
90 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
91 /// is shared among many Frame Description Entries.  There is at least one CIE
92 /// in every non-empty .debug_frame section.
93 void DwarfException::EmitCIE(const Function *PersonalityFn, unsigned Index) {
94   // Size and sign of stack growth.
95   int stackGrowth =
96     Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
97     TargetFrameInfo::StackGrowsUp ?
98     TD->getPointerSize() : -TD->getPointerSize();
99
100   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
101   
102   // Begin eh frame section.
103   Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
104
105   if (MAI->is_EHSymbolPrivate())
106     O << MAI->getPrivateGlobalPrefix();
107   O << "EH_frame" << Index << ":\n";
108   
109   EmitLabel("section_eh_frame", Index);
110
111   // Define base labels.
112   EmitLabel("eh_frame_common", Index);
113
114   // Define the eh frame length.
115   EmitDifference("eh_frame_common_end", Index,
116                  "eh_frame_common_begin", Index, true);
117   Asm->EOL("Length of Common Information Entry");
118
119   // EH frame header.
120   EmitLabel("eh_frame_common_begin", Index);
121   Asm->EmitInt32((int)0);
122   Asm->EOL("CIE Identifier Tag");
123   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
124   Asm->EOL("CIE Version");
125
126   // The personality presence indicates that language specific information will
127   // show up in the eh frame.  Find out how we are supposed to lower the
128   // personality function reference:
129   const MCExpr *PersonalityRef = 0;
130   bool IsPersonalityIndirect = false, IsPersonalityPCRel = false;
131   if (PersonalityFn) {
132     // FIXME: HANDLE STATIC CODEGEN MODEL HERE.
133     
134     // In non-static mode, ask the object file how to represent this reference.
135     PersonalityRef =
136       TLOF.getSymbolForDwarfGlobalReference(PersonalityFn, Asm->Mang,
137                                             Asm->MMI,
138                                             IsPersonalityIndirect,
139                                             IsPersonalityPCRel);
140   }
141   
142   unsigned PerEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
143   if (IsPersonalityIndirect)
144     PerEncoding |= dwarf::DW_EH_PE_indirect;
145   unsigned LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
146   unsigned FDEEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
147
148   char Augmentation[5] = { 0 };
149   unsigned AugmentationSize = 0;
150   char *APtr = Augmentation + 1;
151
152   if (PersonalityRef) {
153     // There is a personality function.
154     *APtr++ = 'P';
155     AugmentationSize += 1 + SizeOfEncodedValue(PerEncoding);
156   }
157
158   if (UsesLSDA[Index]) {
159     // An LSDA pointer is in the FDE augmentation.
160     *APtr++ = 'L';
161     ++AugmentationSize;
162   }
163
164   if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
165     // A non-default pointer encoding for the FDE.
166     *APtr++ = 'R';
167     ++AugmentationSize;
168   }
169
170   if (APtr != Augmentation + 1)
171     Augmentation[0] = 'z';
172
173   Asm->EmitString(Augmentation);
174   Asm->EOL("CIE Augmentation");
175
176   // Round out reader.
177   Asm->EmitULEB128Bytes(1);
178   Asm->EOL("CIE Code Alignment Factor");
179   Asm->EmitSLEB128Bytes(stackGrowth);
180   Asm->EOL("CIE Data Alignment Factor");
181   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
182   Asm->EOL("CIE Return Address Column");
183
184   Asm->EmitULEB128Bytes(AugmentationSize);
185   Asm->EOL("Augmentation Size");
186
187   Asm->EmitInt8(PerEncoding);
188   Asm->EOL("Personality", PerEncoding);
189
190   // If there is a personality, we need to indicate the function's location.
191   if (PersonalityRef) {
192     if (!IsPersonalityPCRel)
193       PersonalityRef = CreateLabelDiff(PersonalityRef, "personalityref_addr",
194                                        Index);
195
196     O << MAI->getData32bitsDirective();
197     PersonalityRef->print(O, MAI);
198     Asm->EOL("Personality");
199
200     Asm->EmitInt8(LSDAEncoding);
201     Asm->EOL("LSDA Encoding", LSDAEncoding);
202
203     Asm->EmitInt8(FDEEncoding);
204     Asm->EOL("FDE Encoding", FDEEncoding);
205   }
206
207   // Indicate locations of general callee saved registers in frame.
208   std::vector<MachineMove> Moves;
209   RI->getInitialFrameState(Moves);
210   EmitFrameMoves(NULL, 0, Moves, true);
211
212   // On Darwin the linker honors the alignment of eh_frame, which means it must
213   // be 8-byte on 64-bit targets to match what gcc does.  Otherwise you get
214   // holes which confuse readers of eh_frame.
215   Asm->EmitAlignment(TD->getPointerSize() == 4 ? 2 : 3, 0, 0, false);
216   EmitLabel("eh_frame_common_end", Index);
217
218   Asm->EOL();
219 }
220
221 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
222 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
223   assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
224          "Should not emit 'available externally' functions at all");
225
226   const Function *TheFunc = EHFrameInfo.function;
227
228   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
229
230   // Externally visible entry into the functions eh frame info. If the
231   // corresponding function is static, this should not be externally visible.
232   if (!TheFunc->hasLocalLinkage())
233     if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
234       O << GlobalEHDirective << EHFrameInfo.FnName << '\n';
235
236   // If corresponding function is weak definition, this should be too.
237   if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
238     O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << '\n';
239
240   // If corresponding function is hidden, this should be too.
241   if (TheFunc->hasHiddenVisibility())
242     if (const char *HiddenDirective = MAI->getHiddenDirective())
243       O << HiddenDirective << EHFrameInfo.FnName << '\n' ;
244
245   // If there are no calls then you can't unwind.  This may mean we can omit the
246   // EH Frame, but some environments do not handle weak absolute symbols. If
247   // UnwindTablesMandatory is set we cannot do this optimization; the unwind
248   // info is to be available for non-EH uses.
249   if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
250       (!TheFunc->isWeakForLinker() ||
251        !MAI->getWeakDefDirective() ||
252        MAI->getSupportsWeakOmittedEHFrame())) {
253     O << EHFrameInfo.FnName << " = 0\n";
254     // This name has no connection to the function, so it might get
255     // dead-stripped when the function is not, erroneously.  Prohibit
256     // dead-stripping unconditionally.
257     if (const char *UsedDirective = MAI->getUsedDirective())
258       O << UsedDirective << EHFrameInfo.FnName << "\n\n";
259   } else {
260     O << EHFrameInfo.FnName << ":\n";
261
262     // EH frame header.
263     EmitDifference("eh_frame_end", EHFrameInfo.Number,
264                    "eh_frame_begin", EHFrameInfo.Number, true);
265     Asm->EOL("Length of Frame Information Entry");
266
267     EmitLabel("eh_frame_begin", EHFrameInfo.Number);
268
269     EmitSectionOffset("eh_frame_begin", "eh_frame_common",
270                       EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
271                       true, true, false);
272
273     Asm->EOL("FDE CIE offset");
274
275     EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
276     Asm->EOL("FDE initial location");
277     EmitDifference("eh_func_end", EHFrameInfo.Number,
278                    "eh_func_begin", EHFrameInfo.Number, true);
279     Asm->EOL("FDE address range");
280
281     // If there is a personality and landing pads then point to the language
282     // specific data area in the exception table.
283     if (MMI->getPersonalities()[0] != NULL) {
284       bool is4Byte = TD->getPointerSize() == sizeof(int32_t);
285
286       Asm->EmitULEB128Bytes(is4Byte ? 4 : 8);
287       Asm->EOL("Augmentation size");
288
289       if (EHFrameInfo.hasLandingPads)
290         EmitReference("exception", EHFrameInfo.Number, true, false);
291       else {
292         if (is4Byte)
293           Asm->EmitInt32((int)0);
294         else
295           Asm->EmitInt64((int)0);
296       }
297       Asm->EOL("Language Specific Data Area");
298     } else {
299       Asm->EmitULEB128Bytes(0);
300       Asm->EOL("Augmentation size");
301     }
302
303     // Indicate locations of function specific callee saved registers in frame.
304     EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
305                    true);
306
307     // On Darwin the linker honors the alignment of eh_frame, which means it
308     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise you
309     // get holes which confuse readers of eh_frame.
310     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
311                        0, 0, false);
312     EmitLabel("eh_frame_end", EHFrameInfo.Number);
313
314     // If the function is marked used, this table should be also.  We cannot
315     // make the mark unconditional in this case, since retaining the table also
316     // retains the function in this case, and there is code around that depends
317     // on unused functions (calling undefined externals) being dead-stripped to
318     // link correctly.  Yes, there really is.
319     if (MMI->isUsedFunction(EHFrameInfo.function))
320       if (const char *UsedDirective = MAI->getUsedDirective())
321         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
322   }
323
324   Asm->EOL();
325 }
326
327 /// SharedTypeIds - How many leading type ids two landing pads have in common.
328 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
329                                        const LandingPadInfo *R) {
330   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
331   unsigned LSize = LIds.size(), RSize = RIds.size();
332   unsigned MinSize = LSize < RSize ? LSize : RSize;
333   unsigned Count = 0;
334
335   for (; Count != MinSize; ++Count)
336     if (LIds[Count] != RIds[Count])
337       return Count;
338
339   return Count;
340 }
341
342 /// PadLT - Order landing pads lexicographically by type id.
343 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
344   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
345   unsigned LSize = LIds.size(), RSize = RIds.size();
346   unsigned MinSize = LSize < RSize ? LSize : RSize;
347
348   for (unsigned i = 0; i != MinSize; ++i)
349     if (LIds[i] != RIds[i])
350       return LIds[i] < RIds[i];
351
352   return LSize < RSize;
353 }
354
355 /// ComputeActionsTable - Compute the actions table and gather the first action
356 /// index for each landing pad site.
357 unsigned DwarfException::
358 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
359                     SmallVectorImpl<ActionEntry> &Actions,
360                     SmallVectorImpl<unsigned> &FirstActions) {
361
362   // The action table follows the call-site table in the LSDA. The individual
363   // records are of two types:
364   //
365   //   * Catch clause
366   //   * Exception specification
367   //
368   // The two record kinds have the same format, with only small differences.
369   // They are distinguished by the "switch value" field: Catch clauses
370   // (TypeInfos) have strictly positive switch values, and exception
371   // specifications (FilterIds) have strictly negative switch values. Value 0
372   // indicates a catch-all clause.
373   //
374   // Negative type IDs index into FilterIds. Positive type IDs index into
375   // TypeInfos.  The value written for a positive type ID is just the type ID
376   // itself.  For a negative type ID, however, the value written is the
377   // (negative) byte offset of the corresponding FilterIds entry.  The byte
378   // offset is usually equal to the type ID (because the FilterIds entries are
379   // written using a variable width encoding, which outputs one byte per entry
380   // as long as the value written is not too large) but can differ.  This kind
381   // of complication does not occur for positive type IDs because type infos are
382   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
383   // offset corresponding to FilterIds[i].
384
385   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
386   SmallVector<int, 16> FilterOffsets;
387   FilterOffsets.reserve(FilterIds.size());
388   int Offset = -1;
389
390   for (std::vector<unsigned>::const_iterator
391          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
392     FilterOffsets.push_back(Offset);
393     Offset -= MCAsmInfo::getULEB128Size(*I);
394   }
395
396   FirstActions.reserve(LandingPads.size());
397
398   int FirstAction = 0;
399   unsigned SizeActions = 0;
400   const LandingPadInfo *PrevLPI = 0;
401
402   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
403          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
404     const LandingPadInfo *LPI = *I;
405     const std::vector<int> &TypeIds = LPI->TypeIds;
406     const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
407     unsigned SizeSiteActions = 0;
408
409     if (NumShared < TypeIds.size()) {
410       unsigned SizeAction = 0;
411       ActionEntry *PrevAction = 0;
412
413       if (NumShared) {
414         const unsigned SizePrevIds = PrevLPI->TypeIds.size();
415         assert(Actions.size());
416         PrevAction = &Actions.back();
417         SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
418           MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
419
420         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
421           SizeAction -=
422             MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
423           SizeAction += -PrevAction->NextAction;
424           PrevAction = PrevAction->Previous;
425         }
426       }
427
428       // Compute the actions.
429       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
430         int TypeID = TypeIds[J];
431         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
432         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
433         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
434
435         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
436         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
437         SizeSiteActions += SizeAction;
438
439         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
440         Actions.push_back(Action);
441         PrevAction = &Actions.back();
442       }
443
444       // Record the first action of the landing pad site.
445       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
446     } // else identical - re-use previous FirstAction
447
448     // Information used when created the call-site table. The action record
449     // field of the call site record is the offset of the first associated
450     // action record, relative to the start of the actions table. This value is
451     // biased by 1 (1 in dicating the start of the actions table), and 0
452     // indicates that there are no actions.
453     FirstActions.push_back(FirstAction);
454
455     // Compute this sites contribution to size.
456     SizeActions += SizeSiteActions;
457
458     PrevLPI = LPI;
459   }
460
461   return SizeActions;
462 }
463
464 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
465 /// marked `nounwind'. Return `false' otherwise.
466 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
467   assert(MI->getDesc().isCall() && "This should be a call instruction!");
468
469   bool MarkedNoUnwind = false;
470   bool SawFunc = false;
471
472   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
473     const MachineOperand &MO = MI->getOperand(I);
474
475     if (MO.isGlobal()) {
476       if (Function *F = dyn_cast<Function>(MO.getGlobal())) {
477         if (SawFunc) {
478           // Be conservative. If we have more than one function operand for this
479           // call, then we can't make the assumption that it's the callee and
480           // not a parameter to the call.
481           // 
482           // FIXME: Determine if there's a way to say that `F' is the callee or
483           // parameter.
484           MarkedNoUnwind = false;
485           break;
486         }
487
488         MarkedNoUnwind = F->doesNotThrow();
489         SawFunc = true;
490       }
491     }
492   }
493
494   return MarkedNoUnwind;
495 }
496
497 /// ComputeCallSiteTable - Compute the call-site table.  The entry for an invoke
498 /// has a try-range containing the call, a non-zero landing pad, and an
499 /// appropriate action.  The entry for an ordinary call has a try-range
500 /// containing the call and zero for the landing pad and the action.  Calls
501 /// marked 'nounwind' have no entry and must not be contained in the try-range
502 /// of any entry - they form gaps in the table.  Entries must be ordered by
503 /// try-range address.
504 void DwarfException::
505 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
506                      const RangeMapType &PadMap,
507                      const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
508                      const SmallVectorImpl<unsigned> &FirstActions) {
509   // The end label of the previous invoke or nounwind try-range.
510   unsigned LastLabel = 0;
511
512   // Whether there is a potentially throwing instruction (currently this means
513   // an ordinary call) between the end of the previous try-range and now.
514   bool SawPotentiallyThrowing = false;
515
516   // Whether the last CallSite entry was for an invoke.
517   bool PreviousIsInvoke = false;
518
519   // Visit all instructions in order of address.
520   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
521        I != E; ++I) {
522     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
523          MI != E; ++MI) {
524       if (!MI->isLabel()) {
525         if (MI->getDesc().isCall())
526           SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
527
528         continue;
529       }
530
531       unsigned BeginLabel = MI->getOperand(0).getImm();
532       assert(BeginLabel && "Invalid label!");
533
534       // End of the previous try-range?
535       if (BeginLabel == LastLabel)
536         SawPotentiallyThrowing = false;
537
538       // Beginning of a new try-range?
539       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
540       if (L == PadMap.end())
541         // Nope, it was just some random label.
542         continue;
543
544       const PadRange &P = L->second;
545       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
546       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
547              "Inconsistent landing pad map!");
548
549       // For Dwarf exception handling (SjLj handling doesn't use this). If some
550       // instruction between the previous try-range and this one may throw,
551       // create a call-site entry with no landing pad for the region between the
552       // try-ranges.
553       if (SawPotentiallyThrowing &&
554           MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
555         CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
556         CallSites.push_back(Site);
557         PreviousIsInvoke = false;
558       }
559
560       LastLabel = LandingPad->EndLabels[P.RangeIndex];
561       assert(BeginLabel && LastLabel && "Invalid landing pad!");
562
563       if (LandingPad->LandingPadLabel) {
564         // This try-range is for an invoke.
565         CallSiteEntry Site = {
566           BeginLabel,
567           LastLabel,
568           LandingPad->LandingPadLabel,
569           FirstActions[P.PadIndex]
570         };
571
572         // Try to merge with the previous call-site. SJLJ doesn't do this
573         if (PreviousIsInvoke &&
574           MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
575           CallSiteEntry &Prev = CallSites.back();
576           if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
577             // Extend the range of the previous entry.
578             Prev.EndLabel = Site.EndLabel;
579             continue;
580           }
581         }
582
583         // Otherwise, create a new call-site.
584         CallSites.push_back(Site);
585         PreviousIsInvoke = true;
586       } else {
587         // Create a gap.
588         PreviousIsInvoke = false;
589       }
590     }
591   }
592
593   // If some instruction between the previous try-range and the end of the
594   // function may throw, create a call-site entry with no landing pad for the
595   // region following the try-range.
596   if (SawPotentiallyThrowing &&
597       MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
598     CallSiteEntry Site = { LastLabel, 0, 0, 0 };
599     CallSites.push_back(Site);
600   }
601 }
602
603 /// EmitExceptionTable - Emit landing pads and actions.
604 ///
605 /// The general organization of the table is complex, but the basic concepts are
606 /// easy.  First there is a header which describes the location and organization
607 /// of the three components that follow.
608 ///
609 ///  1. The landing pad site information describes the range of code covered by
610 ///     the try.  In our case it's an accumulation of the ranges covered by the
611 ///     invokes in the try.  There is also a reference to the landing pad that
612 ///     handles the exception once processed.  Finally an index into the actions
613 ///     table.
614 ///  2. The action table, in our case, is composed of pairs of type IDs and next
615 ///     action offset.  Starting with the action index from the landing pad
616 ///     site, each type ID is checked for a match to the current exception.  If
617 ///     it matches then the exception and type id are passed on to the landing
618 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
619 ///     with a next action of zero.  If no type id is found then the frame is
620 ///     unwound and handling continues.
621 ///  3. Type ID table contains references to all the C++ typeinfo for all
622 ///     catches in the function.  This tables is reverse indexed base 1.
623 void DwarfException::EmitExceptionTable() {
624   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
625   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
626   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
627   if (PadInfos.empty()) return;
628
629   // Sort the landing pads in order of their type ids.  This is used to fold
630   // duplicate actions.
631   SmallVector<const LandingPadInfo *, 64> LandingPads;
632   LandingPads.reserve(PadInfos.size());
633
634   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
635     LandingPads.push_back(&PadInfos[i]);
636
637   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
638
639   // Compute the actions table and gather the first action index for each
640   // landing pad site.
641   SmallVector<ActionEntry, 32> Actions;
642   SmallVector<unsigned, 64> FirstActions;
643   unsigned SizeActions = ComputeActionsTable(LandingPads, Actions,
644                                              FirstActions);
645
646   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
647   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
648   // try-ranges for them need be deduced when using DWARF exception handling.
649   RangeMapType PadMap;
650   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
651     const LandingPadInfo *LandingPad = LandingPads[i];
652     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
653       unsigned BeginLabel = LandingPad->BeginLabels[j];
654       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
655       PadRange P = { i, j };
656       PadMap[BeginLabel] = P;
657     }
658   }
659
660   // Compute the call-site table.
661   SmallVector<CallSiteEntry, 64> CallSites;
662   ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
663
664   // Final tallies.
665
666   // Call sites.
667   const unsigned SiteStartSize  = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
668   const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
669   const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
670   bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
671   bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
672   unsigned SizeSites;
673
674   if (IsSJLJ)
675     SizeSites = 0;
676   else
677     SizeSites = CallSites.size() *
678       (SiteStartSize + SiteLengthSize + LandingPadSize);
679
680   for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
681     SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
682     if (IsSJLJ)
683       SizeSites += MCAsmInfo::getULEB128Size(i);
684   }
685
686   // Type infos.
687   const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
688   unsigned TTypeFormat;
689   unsigned TypeFormatSize;
690
691   if (!HaveTTData) {
692     // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
693     // that we're omitting that bit.
694     TTypeFormat = dwarf::DW_EH_PE_omit;
695     TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
696   } else {
697     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
698     // pick a type encoding for them.  We're about to emit a list of pointers to
699     // typeinfo objects at the end of the LSDA.  However, unless we're in static
700     // mode, this reference will require a relocation by the dynamic linker.
701     //
702     // Because of this, we have a couple of options:
703     // 
704     //   1) If we are in -static mode, we can always use an absolute reference
705     //      from the LSDA, because the static linker will resolve it.
706     //      
707     //   2) Otherwise, if the LSDA section is writable, we can output the direct
708     //      reference to the typeinfo and allow the dynamic linker to relocate
709     //      it.  Since it is in a writable section, the dynamic linker won't
710     //      have a problem.
711     //      
712     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
713     //      we need to use some form of indirection.  For example, on Darwin,
714     //      we can output a statically-relocatable reference to a dyld stub. The
715     //      offset to the stub is constant, but the contents are in a section
716     //      that is updated by the dynamic linker.  This is easy enough, but we
717     //      need to tell the personality function of the unwinder to indirect
718     //      through the dyld stub.
719     //
720     // FIXME: When (3) is actually implemented, we'll have to emit the stubs
721     // somewhere.  This predicate should be moved to a shared location that is
722     // in target-independent code.
723     //
724     if (LSDASection->getKind().isWriteable() ||
725         Asm->TM.getRelocationModel() == Reloc::Static)
726       TTypeFormat = dwarf::DW_EH_PE_absptr;
727     else
728       TTypeFormat = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
729         dwarf::DW_EH_PE_sdata4;
730
731     TypeFormatSize = SizeOfEncodedValue(TTypeFormat);
732   }
733
734   // Begin the exception table.
735   Asm->OutStreamer.SwitchSection(LSDASection);
736   Asm->EmitAlignment(2, 0, 0, false);
737
738   O << "GCC_except_table" << SubprogramCount << ":\n";
739
740   // The type infos need to be aligned. GCC does this by inserting padding just
741   // before the type infos. However, this changes the size of the exception
742   // table, so you need to take this into account when you output the exception
743   // table size. However, the size is output using a variable length encoding.
744   // So by increasing the size by inserting padding, you may increase the number
745   // of bytes used for writing the size. If it increases, say by one byte, then
746   // you now need to output one less byte of padding to get the type infos
747   // aligned.  However this decreases the size of the exception table. This
748   // changes the value you have to output for the exception table size. Due to
749   // the variable length encoding, the number of bytes used for writing the
750   // length may decrease. If so, you then have to increase the amount of
751   // padding. And so on. If you look carefully at the GCC code you will see that
752   // it indeed does this in a loop, going on and on until the values stabilize.
753   // We chose another solution: don't output padding inside the table like GCC
754   // does, instead output it before the table.
755   unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
756   unsigned TyOffset = sizeof(int8_t) +          // Call site format
757     MCAsmInfo::getULEB128Size(SizeSites) +      // Call-site table length
758     SizeSites + SizeActions + SizeTypes;
759   unsigned TotalSize = sizeof(int8_t) +         // LPStart format
760                        sizeof(int8_t) +         // TType format
761     (HaveTTData ?
762      MCAsmInfo::getULEB128Size(TyOffset) : 0) + // TType base offset
763     TyOffset;
764   unsigned SizeAlign = (4 - TotalSize) & 3;
765
766   for (unsigned i = 0; i != SizeAlign; ++i) {
767     Asm->EmitInt8(0);
768     Asm->EOL("Padding");
769   }
770
771   EmitLabel("exception", SubprogramCount);
772
773   if (IsSJLJ) {
774     SmallString<16> LSDAName;
775     raw_svector_ostream(LSDAName) << MAI->getPrivateGlobalPrefix() <<
776       "_LSDA_" << Asm->getFunctionNumber();
777     O << LSDAName.str() << ":\n";
778   }
779
780   // Emit the header.
781   Asm->EmitInt8(dwarf::DW_EH_PE_omit);
782   Asm->EOL("@LPStart format", dwarf::DW_EH_PE_omit);
783
784   Asm->EmitInt8(TTypeFormat);
785   Asm->EOL("@TType format", TTypeFormat);
786
787   if (HaveTTData) {
788     Asm->EmitULEB128Bytes(TyOffset);
789     Asm->EOL("@TType base offset");
790   }
791
792   // SjLj Exception handling
793   if (IsSJLJ) {
794     Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
795     Asm->EOL("Call site format", dwarf::DW_EH_PE_udata4);
796     Asm->EmitULEB128Bytes(SizeSites);
797     Asm->EOL("Call site table length");
798
799     // Emit the landing pad site information.
800     unsigned idx = 0;
801     for (SmallVectorImpl<CallSiteEntry>::const_iterator
802          I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
803       const CallSiteEntry &S = *I;
804
805       // Offset of the landing pad, counted in 16-byte bundles relative to the
806       // @LPStart address.
807       Asm->EmitULEB128Bytes(idx);
808       Asm->EOL("Landing pad");
809
810       // Offset of the first associated action record, relative to the start of
811       // the action table. This value is biased by 1 (1 indicates the start of
812       // the action table), and 0 indicates that there are no actions.
813       Asm->EmitULEB128Bytes(S.Action);
814       Asm->EOL("Action");
815     }
816   } else {
817     // DWARF Exception handling
818     assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
819
820     // The call-site table is a list of all call sites that may throw an
821     // exception (including C++ 'throw' statements) in the procedure
822     // fragment. It immediately follows the LSDA header. Each entry indicates,
823     // for a given call, the first corresponding action record and corresponding
824     // landing pad.
825     //
826     // The table begins with the number of bytes, stored as an LEB128
827     // compressed, unsigned integer. The records immediately follow the record
828     // count. They are sorted in increasing call-site address. Each record
829     // indicates:
830     //
831     //   * The position of the call-site.
832     //   * The position of the landing pad.
833     //   * The first action record for that call site.
834     //
835     // A missing entry in the call-site table indicates that a call is not
836     // supposed to throw.
837
838     // Emit the landing pad call site table.
839     Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
840     Asm->EOL("Call site format", dwarf::DW_EH_PE_udata4);
841     Asm->EmitULEB128Bytes(SizeSites);
842     Asm->EOL("Call site table size");
843
844     for (SmallVectorImpl<CallSiteEntry>::const_iterator
845          I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
846       const CallSiteEntry &S = *I;
847       const char *BeginTag;
848       unsigned BeginNumber;
849
850       if (!S.BeginLabel) {
851         BeginTag = "eh_func_begin";
852         BeginNumber = SubprogramCount;
853       } else {
854         BeginTag = "label";
855         BeginNumber = S.BeginLabel;
856       }
857
858       // Offset of the call site relative to the previous call site, counted in
859       // number of 16-byte bundles. The first call site is counted relative to
860       // the start of the procedure fragment.
861       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
862                         true, true);
863       Asm->EOL("Region start");
864
865       if (!S.EndLabel)
866         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
867                        true);
868       else
869         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
870
871       Asm->EOL("Region length");
872
873       // Offset of the landing pad, counted in 16-byte bundles relative to the
874       // @LPStart address.
875       if (!S.PadLabel)
876         Asm->EmitInt32(0);
877       else
878         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
879                           true, true);
880
881       Asm->EOL("Landing pad");
882
883       // Offset of the first associated action record, relative to the start of
884       // the action table. This value is biased by 1 (1 indicates the start of
885       // the action table), and 0 indicates that there are no actions.
886       Asm->EmitULEB128Bytes(S.Action);
887       Asm->EOL("Action");
888     }
889   }
890
891   // Emit the Action Table.
892   for (SmallVectorImpl<ActionEntry>::const_iterator
893          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
894     const ActionEntry &Action = *I;
895
896     // Type Filter
897     //
898     //   Used by the runtime to match the type of the thrown exception to the
899     //   type of the catch clauses or the types in the exception specification.
900
901     Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
902     Asm->EOL("TypeInfo index");
903
904     // Action Record
905     //
906     //   Self-relative signed displacement in bytes of the next action record,
907     //   or 0 if there is no next action record.
908
909     Asm->EmitSLEB128Bytes(Action.NextAction);
910     Asm->EOL("Next action");
911   }
912
913   // Emit the Catch TypeInfos.
914   for (std::vector<GlobalVariable *>::const_reverse_iterator
915          I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
916     const GlobalVariable *GV = *I;
917     PrintRelDirective();
918
919     if (GV) {
920       O << Asm->Mang->getMangledName(GV);
921     } else {
922       O << "0x0";
923     }
924
925     Asm->EOL("TypeInfo");
926   }
927
928   // Emit the Exception Specifications.
929   for (std::vector<unsigned>::const_iterator
930          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
931     unsigned TypeID = *I;
932     Asm->EmitULEB128Bytes(TypeID);
933     if (TypeID != 0)
934       Asm->EOL("Exception specification");
935     else
936       Asm->EOL();
937   }
938
939   Asm->EmitAlignment(2, 0, 0, false);
940 }
941
942 /// EndModule - Emit all exception information that should come after the
943 /// content.
944 void DwarfException::EndModule() {
945   if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
946     return;
947
948   if (!shouldEmitMovesModule && !shouldEmitTableModule)
949     return;
950
951   if (TimePassesIsEnabled)
952     ExceptionTimer->startTimer();
953
954   const std::vector<Function *> Personalities = MMI->getPersonalities();
955
956   for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
957     EmitCIE(Personalities[I], I);
958
959   for (std::vector<FunctionEHFrameInfo>::iterator
960          I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
961     EmitFDE(*I);
962
963   if (TimePassesIsEnabled)
964     ExceptionTimer->stopTimer();
965 }
966
967 /// BeginFunction - Gather pre-function exception information. Assumes it's
968 /// being emitted immediately after the function entry point.
969 void DwarfException::BeginFunction(MachineFunction *MF) {
970   if (!MMI || !MAI->doesSupportExceptionHandling()) return;
971
972   if (TimePassesIsEnabled)
973     ExceptionTimer->startTimer();
974
975   this->MF = MF;
976   shouldEmitTable = shouldEmitMoves = false;
977
978   // Map all labels and get rid of any dead landing pads.
979   MMI->TidyLandingPads();
980
981   // If any landing pads survive, we need an EH table.
982   if (!MMI->getLandingPads().empty())
983     shouldEmitTable = true;
984
985   // See if we need frame move info.
986   if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
987     shouldEmitMoves = true;
988
989   if (shouldEmitMoves || shouldEmitTable)
990     // Assumes in correct section after the entry point.
991     EmitLabel("eh_func_begin", ++SubprogramCount);
992
993   shouldEmitTableModule |= shouldEmitTable;
994   shouldEmitMovesModule |= shouldEmitMoves;
995
996   if (TimePassesIsEnabled)
997     ExceptionTimer->stopTimer();
998 }
999
1000 /// EndFunction - Gather and emit post-function exception information.
1001 ///
1002 void DwarfException::EndFunction() {
1003   if (!shouldEmitMoves && !shouldEmitTable) return;
1004
1005   if (TimePassesIsEnabled)
1006     ExceptionTimer->startTimer();
1007
1008   EmitLabel("eh_func_end", SubprogramCount);
1009   EmitExceptionTable();
1010
1011   std::string FunctionEHName =
1012     Asm->Mang->getMangledName(MF->getFunction(), ".eh",
1013                               Asm->MAI->is_EHSymbolPrivate());
1014   
1015   // Save EH frame information
1016   EHFrames.push_back(FunctionEHFrameInfo(FunctionEHName, SubprogramCount,
1017                                          MMI->getPersonalityIndex(),
1018                                          MF->getFrameInfo()->hasCalls(),
1019                                          !MMI->getLandingPads().empty(),
1020                                          MMI->getFrameMoves(),
1021                                          MF->getFunction()));
1022
1023   // Record if this personality index uses a landing pad.
1024   UsesLSDA[MMI->getPersonalityIndex()] |= !MMI->getLandingPads().empty();
1025
1026   if (TimePassesIsEnabled)
1027     ExceptionTimer->stopTimer();
1028 }