LLVM API Documentation

EHStreamer.cpp
Go to the documentation of this file.
00001 //===-- CodeGen/AsmPrinter/EHStreamer.cpp - Exception Directive Streamer --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains support for writing exception info into assembly files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "EHStreamer.h"
00015 #include "llvm/CodeGen/AsmPrinter.h"
00016 #include "llvm/CodeGen/MachineFunction.h"
00017 #include "llvm/CodeGen/MachineInstr.h"
00018 #include "llvm/CodeGen/MachineModuleInfo.h"
00019 #include "llvm/IR/Function.h"
00020 #include "llvm/MC/MCAsmInfo.h"
00021 #include "llvm/MC/MCStreamer.h"
00022 #include "llvm/MC/MCSymbol.h"
00023 #include "llvm/Support/LEB128.h"
00024 #include "llvm/Target/TargetLoweringObjectFile.h"
00025 
00026 using namespace llvm;
00027 
00028 EHStreamer::EHStreamer(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
00029 
00030 EHStreamer::~EHStreamer() {}
00031 
00032 /// How many leading type ids two landing pads have in common.
00033 unsigned EHStreamer::sharedTypeIDs(const LandingPadInfo *L,
00034                                    const LandingPadInfo *R) {
00035   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
00036   unsigned LSize = LIds.size(), RSize = RIds.size();
00037   unsigned MinSize = LSize < RSize ? LSize : RSize;
00038   unsigned Count = 0;
00039 
00040   for (; Count != MinSize; ++Count)
00041     if (LIds[Count] != RIds[Count])
00042       return Count;
00043 
00044   return Count;
00045 }
00046 
00047 /// Compute the actions table and gather the first action index for each landing
00048 /// pad site.
00049 unsigned EHStreamer::
00050 computeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
00051                     SmallVectorImpl<ActionEntry> &Actions,
00052                     SmallVectorImpl<unsigned> &FirstActions) {
00053 
00054   // The action table follows the call-site table in the LSDA. The individual
00055   // records are of two types:
00056   //
00057   //   * Catch clause
00058   //   * Exception specification
00059   //
00060   // The two record kinds have the same format, with only small differences.
00061   // They are distinguished by the "switch value" field: Catch clauses
00062   // (TypeInfos) have strictly positive switch values, and exception
00063   // specifications (FilterIds) have strictly negative switch values. Value 0
00064   // indicates a catch-all clause.
00065   //
00066   // Negative type IDs index into FilterIds. Positive type IDs index into
00067   // TypeInfos.  The value written for a positive type ID is just the type ID
00068   // itself.  For a negative type ID, however, the value written is the
00069   // (negative) byte offset of the corresponding FilterIds entry.  The byte
00070   // offset is usually equal to the type ID (because the FilterIds entries are
00071   // written using a variable width encoding, which outputs one byte per entry
00072   // as long as the value written is not too large) but can differ.  This kind
00073   // of complication does not occur for positive type IDs because type infos are
00074   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
00075   // offset corresponding to FilterIds[i].
00076 
00077   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
00078   SmallVector<int, 16> FilterOffsets;
00079   FilterOffsets.reserve(FilterIds.size());
00080   int Offset = -1;
00081 
00082   for (std::vector<unsigned>::const_iterator
00083          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
00084     FilterOffsets.push_back(Offset);
00085     Offset -= getULEB128Size(*I);
00086   }
00087 
00088   FirstActions.reserve(LandingPads.size());
00089 
00090   int FirstAction = 0;
00091   unsigned SizeActions = 0;
00092   const LandingPadInfo *PrevLPI = nullptr;
00093 
00094   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
00095          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
00096     const LandingPadInfo *LPI = *I;
00097     const std::vector<int> &TypeIds = LPI->TypeIds;
00098     unsigned NumShared = PrevLPI ? sharedTypeIDs(LPI, PrevLPI) : 0;
00099     unsigned SizeSiteActions = 0;
00100 
00101     if (NumShared < TypeIds.size()) {
00102       unsigned SizeAction = 0;
00103       unsigned PrevAction = (unsigned)-1;
00104 
00105       if (NumShared) {
00106         unsigned SizePrevIds = PrevLPI->TypeIds.size();
00107         assert(Actions.size());
00108         PrevAction = Actions.size() - 1;
00109         SizeAction = getSLEB128Size(Actions[PrevAction].NextAction) +
00110                      getSLEB128Size(Actions[PrevAction].ValueForTypeID);
00111 
00112         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
00113           assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
00114           SizeAction -= getSLEB128Size(Actions[PrevAction].ValueForTypeID);
00115           SizeAction += -Actions[PrevAction].NextAction;
00116           PrevAction = Actions[PrevAction].Previous;
00117         }
00118       }
00119 
00120       // Compute the actions.
00121       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
00122         int TypeID = TypeIds[J];
00123         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
00124         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
00125         unsigned SizeTypeID = getSLEB128Size(ValueForTypeID);
00126 
00127         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
00128         SizeAction = SizeTypeID + getSLEB128Size(NextAction);
00129         SizeSiteActions += SizeAction;
00130 
00131         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
00132         Actions.push_back(Action);
00133         PrevAction = Actions.size() - 1;
00134       }
00135 
00136       // Record the first action of the landing pad site.
00137       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
00138     } // else identical - re-use previous FirstAction
00139 
00140     // Information used when created the call-site table. The action record
00141     // field of the call site record is the offset of the first associated
00142     // action record, relative to the start of the actions table. This value is
00143     // biased by 1 (1 indicating the start of the actions table), and 0
00144     // indicates that there are no actions.
00145     FirstActions.push_back(FirstAction);
00146 
00147     // Compute this sites contribution to size.
00148     SizeActions += SizeSiteActions;
00149 
00150     PrevLPI = LPI;
00151   }
00152 
00153   return SizeActions;
00154 }
00155 
00156 /// Return `true' if this is a call to a function marked `nounwind'. Return
00157 /// `false' otherwise.
00158 bool EHStreamer::callToNoUnwindFunction(const MachineInstr *MI) {
00159   assert(MI->isCall() && "This should be a call instruction!");
00160 
00161   bool MarkedNoUnwind = false;
00162   bool SawFunc = false;
00163 
00164   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
00165     const MachineOperand &MO = MI->getOperand(I);
00166 
00167     if (!MO.isGlobal()) continue;
00168 
00169     const Function *F = dyn_cast<Function>(MO.getGlobal());
00170     if (!F) continue;
00171 
00172     if (SawFunc) {
00173       // Be conservative. If we have more than one function operand for this
00174       // call, then we can't make the assumption that it's the callee and
00175       // not a parameter to the call.
00176       //
00177       // FIXME: Determine if there's a way to say that `F' is the callee or
00178       // parameter.
00179       MarkedNoUnwind = false;
00180       break;
00181     }
00182 
00183     MarkedNoUnwind = F->doesNotThrow();
00184     SawFunc = true;
00185   }
00186 
00187   return MarkedNoUnwind;
00188 }
00189 
00190 /// Compute the call-site table.  The entry for an invoke has a try-range
00191 /// containing the call, a non-zero landing pad, and an appropriate action.  The
00192 /// entry for an ordinary call has a try-range containing the call and zero for
00193 /// the landing pad and the action.  Calls marked 'nounwind' have no entry and
00194 /// must not be contained in the try-range of any entry - they form gaps in the
00195 /// table.  Entries must be ordered by try-range address.
00196 void EHStreamer::
00197 computeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
00198                      const RangeMapType &PadMap,
00199                      const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
00200                      const SmallVectorImpl<unsigned> &FirstActions) {
00201   // The end label of the previous invoke or nounwind try-range.
00202   MCSymbol *LastLabel = nullptr;
00203 
00204   // Whether there is a potentially throwing instruction (currently this means
00205   // an ordinary call) between the end of the previous try-range and now.
00206   bool SawPotentiallyThrowing = false;
00207 
00208   // Whether the last CallSite entry was for an invoke.
00209   bool PreviousIsInvoke = false;
00210 
00211   // Visit all instructions in order of address.
00212   for (const auto &MBB : *Asm->MF) {
00213     for (const auto &MI : MBB) {
00214       if (!MI.isEHLabel()) {
00215         if (MI.isCall())
00216           SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
00217         continue;
00218       }
00219 
00220       // End of the previous try-range?
00221       MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
00222       if (BeginLabel == LastLabel)
00223         SawPotentiallyThrowing = false;
00224 
00225       // Beginning of a new try-range?
00226       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
00227       if (L == PadMap.end())
00228         // Nope, it was just some random label.
00229         continue;
00230 
00231       const PadRange &P = L->second;
00232       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
00233       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
00234              "Inconsistent landing pad map!");
00235 
00236       // For Dwarf exception handling (SjLj handling doesn't use this). If some
00237       // instruction between the previous try-range and this one may throw,
00238       // create a call-site entry with no landing pad for the region between the
00239       // try-ranges.
00240       if (SawPotentiallyThrowing && Asm->MAI->isExceptionHandlingDwarf()) {
00241         CallSiteEntry Site = { LastLabel, BeginLabel, nullptr, 0 };
00242         CallSites.push_back(Site);
00243         PreviousIsInvoke = false;
00244       }
00245 
00246       LastLabel = LandingPad->EndLabels[P.RangeIndex];
00247       assert(BeginLabel && LastLabel && "Invalid landing pad!");
00248 
00249       if (!LandingPad->LandingPadLabel) {
00250         // Create a gap.
00251         PreviousIsInvoke = false;
00252       } else {
00253         // This try-range is for an invoke.
00254         CallSiteEntry Site = {
00255           BeginLabel,
00256           LastLabel,
00257           LandingPad->LandingPadLabel,
00258           FirstActions[P.PadIndex]
00259         };
00260 
00261         // Try to merge with the previous call-site. SJLJ doesn't do this
00262         if (PreviousIsInvoke && Asm->MAI->isExceptionHandlingDwarf()) {
00263           CallSiteEntry &Prev = CallSites.back();
00264           if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
00265             // Extend the range of the previous entry.
00266             Prev.EndLabel = Site.EndLabel;
00267             continue;
00268           }
00269         }
00270 
00271         // Otherwise, create a new call-site.
00272         if (Asm->MAI->isExceptionHandlingDwarf())
00273           CallSites.push_back(Site);
00274         else {
00275           // SjLj EH must maintain the call sites in the order assigned
00276           // to them by the SjLjPrepare pass.
00277           unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
00278           if (CallSites.size() < SiteNo)
00279             CallSites.resize(SiteNo);
00280           CallSites[SiteNo - 1] = Site;
00281         }
00282         PreviousIsInvoke = true;
00283       }
00284     }
00285   }
00286 
00287   // If some instruction between the previous try-range and the end of the
00288   // function may throw, create a call-site entry with no landing pad for the
00289   // region following the try-range.
00290   if (SawPotentiallyThrowing && Asm->MAI->isExceptionHandlingDwarf()) {
00291     CallSiteEntry Site = { LastLabel, nullptr, nullptr, 0 };
00292     CallSites.push_back(Site);
00293   }
00294 }
00295 
00296 /// Emit landing pads and actions.
00297 ///
00298 /// The general organization of the table is complex, but the basic concepts are
00299 /// easy.  First there is a header which describes the location and organization
00300 /// of the three components that follow.
00301 ///
00302 ///  1. The landing pad site information describes the range of code covered by
00303 ///     the try.  In our case it's an accumulation of the ranges covered by the
00304 ///     invokes in the try.  There is also a reference to the landing pad that
00305 ///     handles the exception once processed.  Finally an index into the actions
00306 ///     table.
00307 ///  2. The action table, in our case, is composed of pairs of type IDs and next
00308 ///     action offset.  Starting with the action index from the landing pad
00309 ///     site, each type ID is checked for a match to the current exception.  If
00310 ///     it matches then the exception and type id are passed on to the landing
00311 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
00312 ///     with a next action of zero.  If no type id is found then the frame is
00313 ///     unwound and handling continues.
00314 ///  3. Type ID table contains references to all the C++ typeinfo for all
00315 ///     catches in the function.  This tables is reverse indexed base 1.
00316 void EHStreamer::emitExceptionTable() {
00317   const std::vector<const GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
00318   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
00319   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
00320 
00321   // Sort the landing pads in order of their type ids.  This is used to fold
00322   // duplicate actions.
00323   SmallVector<const LandingPadInfo *, 64> LandingPads;
00324   LandingPads.reserve(PadInfos.size());
00325 
00326   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
00327     LandingPads.push_back(&PadInfos[i]);
00328 
00329   // Order landing pads lexicographically by type id.
00330   std::sort(LandingPads.begin(), LandingPads.end(),
00331             [](const LandingPadInfo *L,
00332                const LandingPadInfo *R) { return L->TypeIds < R->TypeIds; });
00333 
00334   // Compute the actions table and gather the first action index for each
00335   // landing pad site.
00336   SmallVector<ActionEntry, 32> Actions;
00337   SmallVector<unsigned, 64> FirstActions;
00338   unsigned SizeActions =
00339     computeActionsTable(LandingPads, Actions, FirstActions);
00340 
00341   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
00342   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
00343   // try-ranges for them need be deduced when using DWARF exception handling.
00344   RangeMapType PadMap;
00345   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
00346     const LandingPadInfo *LandingPad = LandingPads[i];
00347     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
00348       MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
00349       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
00350       PadRange P = { i, j };
00351       PadMap[BeginLabel] = P;
00352     }
00353   }
00354 
00355   // Compute the call-site table.
00356   SmallVector<CallSiteEntry, 64> CallSites;
00357   computeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
00358 
00359   // Final tallies.
00360 
00361   // Call sites.
00362   bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
00363   bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
00364 
00365   unsigned CallSiteTableLength;
00366   if (IsSJLJ)
00367     CallSiteTableLength = 0;
00368   else {
00369     unsigned SiteStartSize  = 4; // dwarf::DW_EH_PE_udata4
00370     unsigned SiteLengthSize = 4; // dwarf::DW_EH_PE_udata4
00371     unsigned LandingPadSize = 4; // dwarf::DW_EH_PE_udata4
00372     CallSiteTableLength =
00373       CallSites.size() * (SiteStartSize + SiteLengthSize + LandingPadSize);
00374   }
00375 
00376   for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
00377     CallSiteTableLength += getULEB128Size(CallSites[i].Action);
00378     if (IsSJLJ)
00379       CallSiteTableLength += getULEB128Size(i);
00380   }
00381 
00382   // Type infos.
00383   const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
00384   unsigned TTypeEncoding;
00385   unsigned TypeFormatSize;
00386 
00387   if (!HaveTTData) {
00388     // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
00389     // that we're omitting that bit.
00390     TTypeEncoding = dwarf::DW_EH_PE_omit;
00391     // dwarf::DW_EH_PE_absptr
00392     TypeFormatSize = Asm->getDataLayout().getPointerSize();
00393   } else {
00394     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
00395     // pick a type encoding for them.  We're about to emit a list of pointers to
00396     // typeinfo objects at the end of the LSDA.  However, unless we're in static
00397     // mode, this reference will require a relocation by the dynamic linker.
00398     //
00399     // Because of this, we have a couple of options:
00400     //
00401     //   1) If we are in -static mode, we can always use an absolute reference
00402     //      from the LSDA, because the static linker will resolve it.
00403     //
00404     //   2) Otherwise, if the LSDA section is writable, we can output the direct
00405     //      reference to the typeinfo and allow the dynamic linker to relocate
00406     //      it.  Since it is in a writable section, the dynamic linker won't
00407     //      have a problem.
00408     //
00409     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
00410     //      we need to use some form of indirection.  For example, on Darwin,
00411     //      we can output a statically-relocatable reference to a dyld stub. The
00412     //      offset to the stub is constant, but the contents are in a section
00413     //      that is updated by the dynamic linker.  This is easy enough, but we
00414     //      need to tell the personality function of the unwinder to indirect
00415     //      through the dyld stub.
00416     //
00417     // FIXME: When (3) is actually implemented, we'll have to emit the stubs
00418     // somewhere.  This predicate should be moved to a shared location that is
00419     // in target-independent code.
00420     //
00421     TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
00422     TypeFormatSize = Asm->GetSizeOfEncodedValue(TTypeEncoding);
00423   }
00424 
00425   // Begin the exception table.
00426   // Sometimes we want not to emit the data into separate section (e.g. ARM
00427   // EHABI). In this case LSDASection will be NULL.
00428   if (LSDASection)
00429     Asm->OutStreamer.SwitchSection(LSDASection);
00430   Asm->EmitAlignment(2);
00431 
00432   // Emit the LSDA.
00433   MCSymbol *GCCETSym =
00434     Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
00435                                       Twine(Asm->getFunctionNumber()));
00436   Asm->OutStreamer.EmitLabel(GCCETSym);
00437   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("exception",
00438                                                 Asm->getFunctionNumber()));
00439 
00440   if (IsSJLJ)
00441     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("_LSDA_",
00442                                                   Asm->getFunctionNumber()));
00443 
00444   // Emit the LSDA header.
00445   Asm->EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
00446   Asm->EmitEncodingByte(TTypeEncoding, "@TType");
00447 
00448   // The type infos need to be aligned. GCC does this by inserting padding just
00449   // before the type infos. However, this changes the size of the exception
00450   // table, so you need to take this into account when you output the exception
00451   // table size. However, the size is output using a variable length encoding.
00452   // So by increasing the size by inserting padding, you may increase the number
00453   // of bytes used for writing the size. If it increases, say by one byte, then
00454   // you now need to output one less byte of padding to get the type infos
00455   // aligned. However this decreases the size of the exception table. This
00456   // changes the value you have to output for the exception table size. Due to
00457   // the variable length encoding, the number of bytes used for writing the
00458   // length may decrease. If so, you then have to increase the amount of
00459   // padding. And so on. If you look carefully at the GCC code you will see that
00460   // it indeed does this in a loop, going on and on until the values stabilize.
00461   // We chose another solution: don't output padding inside the table like GCC
00462   // does, instead output it before the table.
00463   unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
00464   unsigned CallSiteTableLengthSize = getULEB128Size(CallSiteTableLength);
00465   unsigned TTypeBaseOffset =
00466     sizeof(int8_t) +                            // Call site format
00467     CallSiteTableLengthSize +                   // Call site table length size
00468     CallSiteTableLength +                       // Call site table length
00469     SizeActions +                               // Actions size
00470     SizeTypes;
00471   unsigned TTypeBaseOffsetSize = getULEB128Size(TTypeBaseOffset);
00472   unsigned TotalSize =
00473     sizeof(int8_t) +                            // LPStart format
00474     sizeof(int8_t) +                            // TType format
00475     (HaveTTData ? TTypeBaseOffsetSize : 0) +    // TType base offset size
00476     TTypeBaseOffset;                            // TType base offset
00477   unsigned SizeAlign = (4 - TotalSize) & 3;
00478 
00479   if (HaveTTData) {
00480     // Account for any extra padding that will be added to the call site table
00481     // length.
00482     Asm->EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
00483     SizeAlign = 0;
00484   }
00485 
00486   bool VerboseAsm = Asm->OutStreamer.isVerboseAsm();
00487 
00488   // SjLj Exception handling
00489   if (IsSJLJ) {
00490     Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
00491 
00492     // Add extra padding if it wasn't added to the TType base offset.
00493     Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
00494 
00495     // Emit the landing pad site information.
00496     unsigned idx = 0;
00497     for (SmallVectorImpl<CallSiteEntry>::const_iterator
00498          I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
00499       const CallSiteEntry &S = *I;
00500 
00501       // Offset of the landing pad, counted in 16-byte bundles relative to the
00502       // @LPStart address.
00503       if (VerboseAsm) {
00504         Asm->OutStreamer.AddComment(">> Call Site " + Twine(idx) + " <<");
00505         Asm->OutStreamer.AddComment("  On exception at call site "+Twine(idx));
00506       }
00507       Asm->EmitULEB128(idx);
00508 
00509       // Offset of the first associated action record, relative to the start of
00510       // the action table. This value is biased by 1 (1 indicates the start of
00511       // the action table), and 0 indicates that there are no actions.
00512       if (VerboseAsm) {
00513         if (S.Action == 0)
00514           Asm->OutStreamer.AddComment("  Action: cleanup");
00515         else
00516           Asm->OutStreamer.AddComment("  Action: " +
00517                                       Twine((S.Action - 1) / 2 + 1));
00518       }
00519       Asm->EmitULEB128(S.Action);
00520     }
00521   } else {
00522     // DWARF Exception handling
00523     assert(Asm->MAI->isExceptionHandlingDwarf());
00524 
00525     // The call-site table is a list of all call sites that may throw an
00526     // exception (including C++ 'throw' statements) in the procedure
00527     // fragment. It immediately follows the LSDA header. Each entry indicates,
00528     // for a given call, the first corresponding action record and corresponding
00529     // landing pad.
00530     //
00531     // The table begins with the number of bytes, stored as an LEB128
00532     // compressed, unsigned integer. The records immediately follow the record
00533     // count. They are sorted in increasing call-site address. Each record
00534     // indicates:
00535     //
00536     //   * The position of the call-site.
00537     //   * The position of the landing pad.
00538     //   * The first action record for that call site.
00539     //
00540     // A missing entry in the call-site table indicates that a call is not
00541     // supposed to throw.
00542 
00543     // Emit the landing pad call site table.
00544     Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
00545 
00546     // Add extra padding if it wasn't added to the TType base offset.
00547     Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
00548 
00549     unsigned Entry = 0;
00550     for (SmallVectorImpl<CallSiteEntry>::const_iterator
00551          I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
00552       const CallSiteEntry &S = *I;
00553 
00554       MCSymbol *EHFuncBeginSym =
00555         Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber());
00556 
00557       MCSymbol *BeginLabel = S.BeginLabel;
00558       if (!BeginLabel)
00559         BeginLabel = EHFuncBeginSym;
00560       MCSymbol *EndLabel = S.EndLabel;
00561       if (!EndLabel)
00562         EndLabel = Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber());
00563 
00564 
00565       // Offset of the call site relative to the previous call site, counted in
00566       // number of 16-byte bundles. The first call site is counted relative to
00567       // the start of the procedure fragment.
00568       if (VerboseAsm)
00569         Asm->OutStreamer.AddComment(">> Call Site " + Twine(++Entry) + " <<");
00570       Asm->EmitLabelDifference(BeginLabel, EHFuncBeginSym, 4);
00571       if (VerboseAsm)
00572         Asm->OutStreamer.AddComment(Twine("  Call between ") +
00573                                     BeginLabel->getName() + " and " +
00574                                     EndLabel->getName());
00575       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
00576 
00577       // Offset of the landing pad, counted in 16-byte bundles relative to the
00578       // @LPStart address.
00579       if (!S.PadLabel) {
00580         if (VerboseAsm)
00581           Asm->OutStreamer.AddComment("    has no landing pad");
00582         Asm->OutStreamer.EmitIntValue(0, 4/*size*/);
00583       } else {
00584         if (VerboseAsm)
00585           Asm->OutStreamer.AddComment(Twine("    jumps to ") +
00586                                       S.PadLabel->getName());
00587         Asm->EmitLabelDifference(S.PadLabel, EHFuncBeginSym, 4);
00588       }
00589 
00590       // Offset of the first associated action record, relative to the start of
00591       // the action table. This value is biased by 1 (1 indicates the start of
00592       // the action table), and 0 indicates that there are no actions.
00593       if (VerboseAsm) {
00594         if (S.Action == 0)
00595           Asm->OutStreamer.AddComment("  On action: cleanup");
00596         else
00597           Asm->OutStreamer.AddComment("  On action: " +
00598                                       Twine((S.Action - 1) / 2 + 1));
00599       }
00600       Asm->EmitULEB128(S.Action);
00601     }
00602   }
00603 
00604   // Emit the Action Table.
00605   int Entry = 0;
00606   for (SmallVectorImpl<ActionEntry>::const_iterator
00607          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
00608     const ActionEntry &Action = *I;
00609 
00610     if (VerboseAsm) {
00611       // Emit comments that decode the action table.
00612       Asm->OutStreamer.AddComment(">> Action Record " + Twine(++Entry) + " <<");
00613     }
00614 
00615     // Type Filter
00616     //
00617     //   Used by the runtime to match the type of the thrown exception to the
00618     //   type of the catch clauses or the types in the exception specification.
00619     if (VerboseAsm) {
00620       if (Action.ValueForTypeID > 0)
00621         Asm->OutStreamer.AddComment("  Catch TypeInfo " +
00622                                     Twine(Action.ValueForTypeID));
00623       else if (Action.ValueForTypeID < 0)
00624         Asm->OutStreamer.AddComment("  Filter TypeInfo " +
00625                                     Twine(Action.ValueForTypeID));
00626       else
00627         Asm->OutStreamer.AddComment("  Cleanup");
00628     }
00629     Asm->EmitSLEB128(Action.ValueForTypeID);
00630 
00631     // Action Record
00632     //
00633     //   Self-relative signed displacement in bytes of the next action record,
00634     //   or 0 if there is no next action record.
00635     if (VerboseAsm) {
00636       if (Action.NextAction == 0) {
00637         Asm->OutStreamer.AddComment("  No further actions");
00638       } else {
00639         unsigned NextAction = Entry + (Action.NextAction + 1) / 2;
00640         Asm->OutStreamer.AddComment("  Continue to action "+Twine(NextAction));
00641       }
00642     }
00643     Asm->EmitSLEB128(Action.NextAction);
00644   }
00645 
00646   emitTypeInfos(TTypeEncoding);
00647 
00648   Asm->EmitAlignment(2);
00649 }
00650 
00651 void EHStreamer::emitTypeInfos(unsigned TTypeEncoding) {
00652   const std::vector<const GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
00653   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
00654 
00655   bool VerboseAsm = Asm->OutStreamer.isVerboseAsm();
00656 
00657   int Entry = 0;
00658   // Emit the Catch TypeInfos.
00659   if (VerboseAsm && !TypeInfos.empty()) {
00660     Asm->OutStreamer.AddComment(">> Catch TypeInfos <<");
00661     Asm->OutStreamer.AddBlankLine();
00662     Entry = TypeInfos.size();
00663   }
00664 
00665   for (std::vector<const GlobalVariable *>::const_reverse_iterator
00666          I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
00667     const GlobalVariable *GV = *I;
00668     if (VerboseAsm)
00669       Asm->OutStreamer.AddComment("TypeInfo " + Twine(Entry--));
00670     Asm->EmitTTypeReference(GV, TTypeEncoding);
00671   }
00672 
00673   // Emit the Exception Specifications.
00674   if (VerboseAsm && !FilterIds.empty()) {
00675     Asm->OutStreamer.AddComment(">> Filter TypeInfos <<");
00676     Asm->OutStreamer.AddBlankLine();
00677     Entry = 0;
00678   }
00679   for (std::vector<unsigned>::const_iterator
00680          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
00681     unsigned TypeID = *I;
00682     if (VerboseAsm) {
00683       --Entry;
00684       if (TypeID != 0)
00685         Asm->OutStreamer.AddComment("FilterInfo " + Twine(Entry));
00686     }
00687 
00688     Asm->EmitULEB128(TypeID);
00689   }
00690 }
00691 
00692 /// Emit all exception information that should come after the content.
00693 void EHStreamer::endModule() {
00694   llvm_unreachable("Should be implemented");
00695 }
00696 
00697 /// Gather pre-function exception information. Assumes it's being emitted
00698 /// immediately after the function entry point.
00699 void EHStreamer::beginFunction(const MachineFunction *MF) {
00700   llvm_unreachable("Should be implemented");
00701 }
00702 
00703 /// Gather and emit post-function exception information.
00704 void EHStreamer::endFunction(const MachineFunction *) {
00705   llvm_unreachable("Should be implemented");
00706 }