Home | History | Annotate | Download | only in MC
      1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
      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 #include "llvm/MC/MCDwarf.h"
     11 #include "llvm/MC/MCAsmInfo.h"
     12 #include "llvm/MC/MCContext.h"
     13 #include "llvm/MC/MCObjectFileInfo.h"
     14 #include "llvm/MC/MCObjectWriter.h"
     15 #include "llvm/MC/MCRegisterInfo.h"
     16 #include "llvm/MC/MCStreamer.h"
     17 #include "llvm/MC/MCSymbol.h"
     18 #include "llvm/MC/MCExpr.h"
     19 #include "llvm/Support/Debug.h"
     20 #include "llvm/Support/ErrorHandling.h"
     21 #include "llvm/Support/raw_ostream.h"
     22 #include "llvm/Target/TargetAsmInfo.h"
     23 #include "llvm/ADT/FoldingSet.h"
     24 #include "llvm/ADT/SmallString.h"
     25 #include "llvm/ADT/StringExtras.h"
     26 #include "llvm/ADT/Twine.h"
     27 using namespace llvm;
     28 
     29 // Given a special op, return the address skip amount (in units of
     30 // DWARF2_LINE_MIN_INSN_LENGTH.
     31 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
     32 
     33 // The maximum address skip amount that can be encoded with a special op.
     34 #define MAX_SPECIAL_ADDR_DELTA         SPECIAL_ADDR(255)
     35 
     36 // First special line opcode - leave room for the standard opcodes.
     37 // Note: If you want to change this, you'll have to update the
     38 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
     39 #define DWARF2_LINE_OPCODE_BASE         13
     40 
     41 // Minimum line offset in a special line info. opcode.  This value
     42 // was chosen to give a reasonable range of values.
     43 #define DWARF2_LINE_BASE                -5
     44 
     45 // Range of line offsets in a special line info. opcode.
     46 #define DWARF2_LINE_RANGE               14
     47 
     48 // Define the architecture-dependent minimum instruction length (in bytes).
     49 // This value should be rather too small than too big.
     50 #define DWARF2_LINE_MIN_INSN_LENGTH     1
     51 
     52 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
     53 // this routine is a nop and will be optimized away.
     54 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
     55   if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
     56     return AddrDelta;
     57   if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
     58     // TODO: report this error, but really only once.
     59     ;
     60   }
     61   return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
     62 }
     63 
     64 //
     65 // This is called when an instruction is assembled into the specified section
     66 // and if there is information from the last .loc directive that has yet to have
     67 // a line entry made for it is made.
     68 //
     69 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
     70   if (!MCOS->getContext().getDwarfLocSeen())
     71     return;
     72 
     73   // Create a symbol at in the current section for use in the line entry.
     74   MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
     75   // Set the value of the symbol to use for the MCLineEntry.
     76   MCOS->EmitLabel(LineSym);
     77 
     78   // Get the current .loc info saved in the context.
     79   const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
     80 
     81   // Create a (local) line entry with the symbol and the current .loc info.
     82   MCLineEntry LineEntry(LineSym, DwarfLoc);
     83 
     84   // clear DwarfLocSeen saying the current .loc info is now used.
     85   MCOS->getContext().ClearDwarfLocSeen();
     86 
     87   // Get the MCLineSection for this section, if one does not exist for this
     88   // section create it.
     89   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
     90     MCOS->getContext().getMCLineSections();
     91   MCLineSection *LineSection = MCLineSections.lookup(Section);
     92   if (!LineSection) {
     93     // Create a new MCLineSection.  This will be deleted after the dwarf line
     94     // table is created using it by iterating through the MCLineSections
     95     // DenseMap.
     96     LineSection = new MCLineSection;
     97     // Save a pointer to the new LineSection into the MCLineSections DenseMap.
     98     MCOS->getContext().addMCLineSection(Section, LineSection);
     99   }
    100 
    101   // Add the line entry to this section's entries.
    102   LineSection->addLineEntry(LineEntry);
    103 }
    104 
    105 //
    106 // This helper routine returns an expression of End - Start + IntVal .
    107 //
    108 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
    109                                                   const MCSymbol &Start,
    110                                                   const MCSymbol &End,
    111                                                   int IntVal) {
    112   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
    113   const MCExpr *Res =
    114     MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
    115   const MCExpr *RHS =
    116     MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
    117   const MCExpr *Res1 =
    118     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
    119   const MCExpr *Res2 =
    120     MCConstantExpr::Create(IntVal, MCOS.getContext());
    121   const MCExpr *Res3 =
    122     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
    123   return Res3;
    124 }
    125 
    126 //
    127 // This emits the Dwarf line table for the specified section from the entries
    128 // in the LineSection.
    129 //
    130 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
    131                                       const MCSection *Section,
    132                                       const MCLineSection *LineSection) {
    133   unsigned FileNum = 1;
    134   unsigned LastLine = 1;
    135   unsigned Column = 0;
    136   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
    137   unsigned Isa = 0;
    138   MCSymbol *LastLabel = NULL;
    139 
    140   // Loop through each MCLineEntry and encode the dwarf line number table.
    141   for (MCLineSection::const_iterator
    142          it = LineSection->getMCLineEntries()->begin(),
    143          ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
    144 
    145     if (FileNum != it->getFileNum()) {
    146       FileNum = it->getFileNum();
    147       MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
    148       MCOS->EmitULEB128IntValue(FileNum);
    149     }
    150     if (Column != it->getColumn()) {
    151       Column = it->getColumn();
    152       MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
    153       MCOS->EmitULEB128IntValue(Column);
    154     }
    155     if (Isa != it->getIsa()) {
    156       Isa = it->getIsa();
    157       MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
    158       MCOS->EmitULEB128IntValue(Isa);
    159     }
    160     if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
    161       Flags = it->getFlags();
    162       MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
    163     }
    164     if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
    165       MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
    166     if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
    167       MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
    168     if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
    169       MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
    170 
    171     int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
    172     MCSymbol *Label = it->getLabel();
    173 
    174     // At this point we want to emit/create the sequence to encode the delta in
    175     // line numbers and the increment of the address from the previous Label
    176     // and the current Label.
    177     const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
    178     MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
    179                                    asmInfo.getPointerSize());
    180 
    181     LastLine = it->getLine();
    182     LastLabel = Label;
    183   }
    184 
    185   // Emit a DW_LNE_end_sequence for the end of the section.
    186   // Using the pointer Section create a temporary label at the end of the
    187   // section and use that and the LastLabel to compute the address delta
    188   // and use INT64_MAX as the line delta which is the signal that this is
    189   // actually a DW_LNE_end_sequence.
    190 
    191   // Switch to the section to be able to create a symbol at its end.
    192   MCOS->SwitchSection(Section);
    193 
    194   MCContext &context = MCOS->getContext();
    195   // Create a symbol at the end of the section.
    196   MCSymbol *SectionEnd = context.CreateTempSymbol();
    197   // Set the value of the symbol, as we are at the end of the section.
    198   MCOS->EmitLabel(SectionEnd);
    199 
    200   // Switch back the the dwarf line section.
    201   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
    202 
    203   const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
    204   MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
    205                                  asmInfo.getPointerSize());
    206 }
    207 
    208 //
    209 // This emits the Dwarf file and the line tables.
    210 //
    211 void MCDwarfFileTable::Emit(MCStreamer *MCOS) {
    212   MCContext &context = MCOS->getContext();
    213   // Switch to the section where the table will be emitted into.
    214   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
    215 
    216   // Create a symbol at the beginning of this section.
    217   MCSymbol *LineStartSym = context.CreateTempSymbol();
    218   // Set the value of the symbol, as we are at the start of the section.
    219   MCOS->EmitLabel(LineStartSym);
    220 
    221   // Create a symbol for the end of the section (to be set when we get there).
    222   MCSymbol *LineEndSym = context.CreateTempSymbol();
    223 
    224   // The first 4 bytes is the total length of the information for this
    225   // compilation unit (not including these 4 bytes for the length).
    226   MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
    227                      4);
    228 
    229   // Next 2 bytes is the Version, which is Dwarf 2.
    230   MCOS->EmitIntValue(2, 2);
    231 
    232   // Create a symbol for the end of the prologue (to be set when we get there).
    233   MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
    234 
    235   // Length of the prologue, is the next 4 bytes.  Which is the start of the
    236   // section to the end of the prologue.  Not including the 4 bytes for the
    237   // total length, the 2 bytes for the version, and these 4 bytes for the
    238   // length of the prologue.
    239   MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
    240                                         (4 + 2 + 4)),
    241                   4, 0);
    242 
    243   // Parameters of the state machine, are next.
    244   MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
    245   MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
    246   MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
    247   MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
    248   MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
    249 
    250   // Standard opcode lengths
    251   MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
    252   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
    253   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
    254   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
    255   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
    256   MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
    257   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
    258   MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
    259   MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
    260   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
    261   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
    262   MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
    263 
    264   // Put out the directory and file tables.
    265 
    266   // First the directory table.
    267   const std::vector<StringRef> &MCDwarfDirs =
    268     context.getMCDwarfDirs();
    269   for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
    270     MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
    271     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
    272   }
    273   MCOS->EmitIntValue(0, 1); // Terminate the directory list
    274 
    275   // Second the file table.
    276   const std::vector<MCDwarfFile *> &MCDwarfFiles =
    277     MCOS->getContext().getMCDwarfFiles();
    278   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
    279     MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
    280     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
    281     // the Directory num
    282     MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
    283     MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
    284     MCOS->EmitIntValue(0, 1); // filesize (always 0)
    285   }
    286   MCOS->EmitIntValue(0, 1); // Terminate the file list
    287 
    288   // This is the end of the prologue, so set the value of the symbol at the
    289   // end of the prologue (that was used in a previous expression).
    290   MCOS->EmitLabel(ProEndSym);
    291 
    292   // Put out the line tables.
    293   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
    294     MCOS->getContext().getMCLineSections();
    295   const std::vector<const MCSection *> &MCLineSectionOrder =
    296     MCOS->getContext().getMCLineSectionOrder();
    297   for (std::vector<const MCSection*>::const_iterator it =
    298          MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
    299        ++it) {
    300     const MCSection *Sec = *it;
    301     const MCLineSection *Line = MCLineSections.lookup(Sec);
    302     EmitDwarfLineTable(MCOS, Sec, Line);
    303 
    304     // Now delete the MCLineSections that were created in MCLineEntry::Make()
    305     // and used to emit the line table.
    306     delete Line;
    307   }
    308 
    309   if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
    310       && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
    311     // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
    312     // it requires:
    313     // total_length >= prologue_length + 10
    314     // We are 4 bytes short, since we have total_length = 51 and
    315     // prologue_length = 45
    316 
    317     // The regular end_sequence should be sufficient.
    318     MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
    319   }
    320 
    321   // This is the end of the section, so set the value of the symbol at the end
    322   // of this section (that was used in a previous expression).
    323   MCOS->EmitLabel(LineEndSym);
    324 }
    325 
    326 /// Utility function to write the encoding to an object writer.
    327 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
    328                             uint64_t AddrDelta) {
    329   SmallString<256> Tmp;
    330   raw_svector_ostream OS(Tmp);
    331   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
    332   OW->WriteBytes(OS.str());
    333 }
    334 
    335 /// Utility function to emit the encoding to a streamer.
    336 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
    337                            uint64_t AddrDelta) {
    338   SmallString<256> Tmp;
    339   raw_svector_ostream OS(Tmp);
    340   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
    341   MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
    342 }
    343 
    344 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
    345 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
    346                              raw_ostream &OS) {
    347   uint64_t Temp, Opcode;
    348   bool NeedCopy = false;
    349 
    350   // Scale the address delta by the minimum instruction length.
    351   AddrDelta = ScaleAddrDelta(AddrDelta);
    352 
    353   // A LineDelta of INT64_MAX is a signal that this is actually a
    354   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
    355   // end_sequence to emit the matrix entry.
    356   if (LineDelta == INT64_MAX) {
    357     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
    358       OS << char(dwarf::DW_LNS_const_add_pc);
    359     else {
    360       OS << char(dwarf::DW_LNS_advance_pc);
    361       MCObjectWriter::EncodeULEB128(AddrDelta, OS);
    362     }
    363     OS << char(dwarf::DW_LNS_extended_op);
    364     OS << char(1);
    365     OS << char(dwarf::DW_LNE_end_sequence);
    366     return;
    367   }
    368 
    369   // Bias the line delta by the base.
    370   Temp = LineDelta - DWARF2_LINE_BASE;
    371 
    372   // If the line increment is out of range of a special opcode, we must encode
    373   // it with DW_LNS_advance_line.
    374   if (Temp >= DWARF2_LINE_RANGE) {
    375     OS << char(dwarf::DW_LNS_advance_line);
    376     SmallString<32> Tmp;
    377     raw_svector_ostream OSE(Tmp);
    378     MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
    379     OS << OSE.str();
    380 
    381     LineDelta = 0;
    382     Temp = 0 - DWARF2_LINE_BASE;
    383     NeedCopy = true;
    384   }
    385 
    386   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
    387   if (LineDelta == 0 && AddrDelta == 0) {
    388     OS << char(dwarf::DW_LNS_copy);
    389     return;
    390   }
    391 
    392   // Bias the opcode by the special opcode base.
    393   Temp += DWARF2_LINE_OPCODE_BASE;
    394 
    395   // Avoid overflow when addr_delta is large.
    396   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
    397     // Try using a special opcode.
    398     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
    399     if (Opcode <= 255) {
    400       OS << char(Opcode);
    401       return;
    402     }
    403 
    404     // Try using DW_LNS_const_add_pc followed by special op.
    405     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
    406     if (Opcode <= 255) {
    407       OS << char(dwarf::DW_LNS_const_add_pc);
    408       OS << char(Opcode);
    409       return;
    410     }
    411   }
    412 
    413   // Otherwise use DW_LNS_advance_pc.
    414   OS << char(dwarf::DW_LNS_advance_pc);
    415   SmallString<32> Tmp;
    416   raw_svector_ostream OSE(Tmp);
    417   MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
    418   OS << OSE.str();
    419 
    420   if (NeedCopy)
    421     OS << char(dwarf::DW_LNS_copy);
    422   else
    423     OS << char(Temp);
    424 }
    425 
    426 void MCDwarfFile::print(raw_ostream &OS) const {
    427   OS << '"' << getName() << '"';
    428 }
    429 
    430 void MCDwarfFile::dump() const {
    431   print(dbgs());
    432 }
    433 
    434 static int getDataAlignmentFactor(MCStreamer &streamer) {
    435   MCContext &context = streamer.getContext();
    436   const MCAsmInfo &asmInfo = context.getAsmInfo();
    437   int size = asmInfo.getPointerSize();
    438   if (asmInfo.isStackGrowthDirectionUp())
    439     return size;
    440   else
    441     return -size;
    442 }
    443 
    444 static unsigned getSizeForEncoding(MCStreamer &streamer,
    445                                    unsigned symbolEncoding) {
    446   MCContext &context = streamer.getContext();
    447   unsigned format = symbolEncoding & 0x0f;
    448   switch (format) {
    449   default:
    450     assert(0 && "Unknown Encoding");
    451   case dwarf::DW_EH_PE_absptr:
    452   case dwarf::DW_EH_PE_signed:
    453     return context.getAsmInfo().getPointerSize();
    454   case dwarf::DW_EH_PE_udata2:
    455   case dwarf::DW_EH_PE_sdata2:
    456     return 2;
    457   case dwarf::DW_EH_PE_udata4:
    458   case dwarf::DW_EH_PE_sdata4:
    459     return 4;
    460   case dwarf::DW_EH_PE_udata8:
    461   case dwarf::DW_EH_PE_sdata8:
    462     return 8;
    463   }
    464 }
    465 
    466 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
    467                        unsigned symbolEncoding, const char *comment = 0) {
    468   MCContext &context = streamer.getContext();
    469   const MCAsmInfo &asmInfo = context.getAsmInfo();
    470   const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
    471                                                 symbolEncoding,
    472                                                 streamer);
    473   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
    474   if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
    475   streamer.EmitAbsValue(v, size);
    476 }
    477 
    478 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
    479                             unsigned symbolEncoding) {
    480   MCContext &context = streamer.getContext();
    481   const MCAsmInfo &asmInfo = context.getAsmInfo();
    482   const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
    483                                                         symbolEncoding,
    484                                                         streamer);
    485   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
    486   streamer.EmitValue(v, size);
    487 }
    488 
    489 static const MachineLocation TranslateMachineLocation(
    490                                                   const MCRegisterInfo &MRI,
    491                                                   const MachineLocation &Loc) {
    492   unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
    493     MachineLocation::VirtualFP :
    494     unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
    495   const MachineLocation &NewLoc = Loc.isReg() ?
    496     MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
    497   return NewLoc;
    498 }
    499 
    500 namespace {
    501   class FrameEmitterImpl {
    502     int CFAOffset;
    503     int CIENum;
    504     bool UsingCFI;
    505     bool IsEH;
    506     const MCSymbol *SectionStart;
    507   public:
    508     FrameEmitterImpl(bool usingCFI, bool isEH, const MCSymbol *sectionStart) :
    509       CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
    510       SectionStart(sectionStart) {
    511     }
    512 
    513     /// EmitCompactUnwind - Emit the unwind information in a compact way. If
    514     /// we're successful, return 'true'. Otherwise, return 'false' and it will
    515     /// emit the normal CIE and FDE.
    516     bool EmitCompactUnwind(MCStreamer &streamer,
    517                            const MCDwarfFrameInfo &frame);
    518 
    519     const MCSymbol &EmitCIE(MCStreamer &streamer,
    520                             const MCSymbol *personality,
    521                             unsigned personalityEncoding,
    522                             const MCSymbol *lsda,
    523                             unsigned lsdaEncoding);
    524     MCSymbol *EmitFDE(MCStreamer &streamer,
    525                       const MCSymbol &cieStart,
    526                       const MCDwarfFrameInfo &frame);
    527     void EmitCFIInstructions(MCStreamer &streamer,
    528                              const std::vector<MCCFIInstruction> &Instrs,
    529                              MCSymbol *BaseLabel);
    530     void EmitCFIInstruction(MCStreamer &Streamer,
    531                             const MCCFIInstruction &Instr);
    532   };
    533 
    534 } // end anonymous namespace
    535 
    536 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
    537                              StringRef Prefix) {
    538   if (Streamer.isVerboseAsm()) {
    539     const char *EncStr = 0;
    540     switch (Encoding) {
    541     default: EncStr = "<unknown encoding>";
    542     case dwarf::DW_EH_PE_absptr: EncStr = "absptr";
    543     case dwarf::DW_EH_PE_omit:   EncStr = "omit";
    544     case dwarf::DW_EH_PE_pcrel:  EncStr = "pcrel";
    545     case dwarf::DW_EH_PE_udata4: EncStr = "udata4";
    546     case dwarf::DW_EH_PE_udata8: EncStr = "udata8";
    547     case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4";
    548     case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8";
    549     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: EncStr = "pcrel udata4";
    550     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: EncStr = "pcrel sdata4";
    551     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: EncStr = "pcrel udata8";
    552     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: EncStr = "pcrel sdata8";
    553     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
    554       EncStr = "indirect pcrel udata4";
    555     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
    556       EncStr = "indirect pcrel sdata4";
    557     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
    558       EncStr = "indirect pcrel udata8";
    559     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
    560       EncStr = "indirect pcrel sdata8";
    561     }
    562 
    563     Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
    564   }
    565 
    566   Streamer.EmitIntValue(Encoding, 1);
    567 }
    568 
    569 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
    570                                           const MCCFIInstruction &Instr) {
    571   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
    572   bool VerboseAsm = Streamer.isVerboseAsm();
    573 
    574   switch (Instr.getOperation()) {
    575   case MCCFIInstruction::Move:
    576   case MCCFIInstruction::RelMove: {
    577     const MachineLocation &Dst = Instr.getDestination();
    578     const MachineLocation &Src = Instr.getSource();
    579     const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
    580 
    581     // If advancing cfa.
    582     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
    583       if (Src.getReg() == MachineLocation::VirtualFP) {
    584         if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
    585         Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
    586       } else {
    587         if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
    588         Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
    589         if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
    590                                             Twine(Src.getReg()));
    591         Streamer.EmitULEB128IntValue(Src.getReg());
    592       }
    593 
    594       if (IsRelative)
    595         CFAOffset += Src.getOffset();
    596       else
    597         CFAOffset = -Src.getOffset();
    598 
    599       if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
    600       Streamer.EmitULEB128IntValue(CFAOffset);
    601       return;
    602     }
    603 
    604     if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
    605       assert(Dst.isReg() && "Machine move not supported yet.");
    606       if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
    607       Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
    608       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
    609       Streamer.EmitULEB128IntValue(Dst.getReg());
    610       return;
    611     }
    612 
    613     unsigned Reg = Src.getReg();
    614     int Offset = Dst.getOffset();
    615     if (IsRelative)
    616       Offset -= CFAOffset;
    617     Offset = Offset / dataAlignmentFactor;
    618 
    619     if (Offset < 0) {
    620       if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
    621       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
    622       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
    623       Streamer.EmitULEB128IntValue(Reg);
    624       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
    625       Streamer.EmitSLEB128IntValue(Offset);
    626     } else if (Reg < 64) {
    627       if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
    628                                           Twine(Reg) + ")");
    629       Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
    630       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
    631       Streamer.EmitULEB128IntValue(Offset);
    632     } else {
    633       if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
    634       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
    635       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
    636       Streamer.EmitULEB128IntValue(Reg);
    637       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
    638       Streamer.EmitULEB128IntValue(Offset);
    639     }
    640     return;
    641   }
    642   case MCCFIInstruction::Remember:
    643     if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
    644     Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
    645     return;
    646   case MCCFIInstruction::Restore:
    647     if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
    648     Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
    649     return;
    650   case MCCFIInstruction::SameValue: {
    651     unsigned Reg = Instr.getDestination().getReg();
    652     if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
    653     Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
    654     if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
    655     Streamer.EmitULEB128IntValue(Reg);
    656     return;
    657   }
    658   }
    659   llvm_unreachable("Unhandled case in switch");
    660 }
    661 
    662 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
    663 /// frame.
    664 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
    665                                     const std::vector<MCCFIInstruction> &Instrs,
    666                                            MCSymbol *BaseLabel) {
    667   for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
    668     const MCCFIInstruction &Instr = Instrs[i];
    669     MCSymbol *Label = Instr.getLabel();
    670     // Throw out move if the label is invalid.
    671     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
    672 
    673     // Advance row if new location.
    674     if (BaseLabel && Label) {
    675       MCSymbol *ThisSym = Label;
    676       if (ThisSym != BaseLabel) {
    677         if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
    678         streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
    679         BaseLabel = ThisSym;
    680       }
    681     }
    682 
    683     EmitCFIInstruction(streamer, Instr);
    684   }
    685 }
    686 
    687 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
    688 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
    689 /// normal CIE and FDE.
    690 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
    691                                          const MCDwarfFrameInfo &Frame) {
    692   MCContext &Context = Streamer.getContext();
    693   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
    694   const TargetAsmInfo &TAI = Context.getTargetAsmInfo();
    695   bool VerboseAsm = Streamer.isVerboseAsm();
    696 
    697   // range-start range-length  compact-unwind-enc personality-func   lsda
    698   //  _foo       LfooEnd-_foo  0x00000023          0                 0
    699   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
    700   //
    701   //   .section __LD,__compact_unwind,regular,debug
    702   //
    703   //   # compact unwind for _foo
    704   //   .quad _foo
    705   //   .set L1,LfooEnd-_foo
    706   //   .long L1
    707   //   .long 0x01010001
    708   //   .quad 0
    709   //   .quad 0
    710   //
    711   //   # compact unwind for _bar
    712   //   .quad _bar
    713   //   .set L2,LbarEnd-_bar
    714   //   .long L2
    715   //   .long 0x01020011
    716   //   .quad __gxx_personality
    717   //   .quad except_tab1
    718 
    719   uint32_t Encoding = Frame.CompactUnwindEncoding;
    720   if (!Encoding) return false;
    721 
    722   // The encoding needs to know we have an LSDA.
    723   if (Frame.Lsda)
    724     Encoding |= 0x40000000;
    725 
    726   Streamer.SwitchSection(MOFI->getCompactUnwindSection());
    727 
    728   // Range Start
    729   unsigned FDEEncoding = TAI.getFDEEncoding(UsingCFI);
    730   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
    731   if (VerboseAsm) Streamer.AddComment("Range Start");
    732   Streamer.EmitSymbolValue(Frame.Function, Size);
    733 
    734   // Range Length
    735   const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
    736                                               *Frame.End, 0);
    737   if (VerboseAsm) Streamer.AddComment("Range Length");
    738   Streamer.EmitAbsValue(Range, 4);
    739 
    740   // Compact Encoding
    741   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
    742   if (VerboseAsm) Streamer.AddComment(Twine("Compact Unwind Encoding: 0x") +
    743                                       Twine(llvm::utohexstr(Encoding)));
    744   Streamer.EmitIntValue(Encoding, Size);
    745 
    746 
    747   // Personality Function
    748   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
    749   if (VerboseAsm) Streamer.AddComment("Personality Function");
    750   if (Frame.Personality)
    751     Streamer.EmitSymbolValue(Frame.Personality, Size);
    752   else
    753     Streamer.EmitIntValue(0, Size); // No personality fn
    754 
    755   // LSDA
    756   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
    757   if (VerboseAsm) Streamer.AddComment("LSDA");
    758   if (Frame.Lsda)
    759     Streamer.EmitSymbolValue(Frame.Lsda, Size);
    760   else
    761     Streamer.EmitIntValue(0, Size); // No LSDA
    762 
    763   return true;
    764 }
    765 
    766 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
    767                                           const MCSymbol *personality,
    768                                           unsigned personalityEncoding,
    769                                           const MCSymbol *lsda,
    770                                           unsigned lsdaEncoding) {
    771   MCContext &context = streamer.getContext();
    772   const MCRegisterInfo &MRI = context.getRegisterInfo();
    773   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
    774   const TargetAsmInfo &TAI = context.getTargetAsmInfo();
    775   bool verboseAsm = streamer.isVerboseAsm();
    776 
    777   MCSymbol *sectionStart;
    778   if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
    779     sectionStart = context.CreateTempSymbol();
    780   else
    781     sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
    782 
    783   streamer.EmitLabel(sectionStart);
    784   CIENum++;
    785 
    786   MCSymbol *sectionEnd = context.CreateTempSymbol();
    787 
    788   // Length
    789   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
    790                                                *sectionEnd, 4);
    791   if (verboseAsm) streamer.AddComment("CIE Length");
    792   streamer.EmitAbsValue(Length, 4);
    793 
    794   // CIE ID
    795   unsigned CIE_ID = IsEH ? 0 : -1;
    796   if (verboseAsm) streamer.AddComment("CIE ID Tag");
    797   streamer.EmitIntValue(CIE_ID, 4);
    798 
    799   // Version
    800   if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
    801   streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
    802 
    803   // Augmentation String
    804   SmallString<8> Augmentation;
    805   if (IsEH) {
    806     if (verboseAsm) streamer.AddComment("CIE Augmentation");
    807     Augmentation += "z";
    808     if (personality)
    809       Augmentation += "P";
    810     if (lsda)
    811       Augmentation += "L";
    812     Augmentation += "R";
    813     streamer.EmitBytes(Augmentation.str(), 0);
    814   }
    815   streamer.EmitIntValue(0, 1);
    816 
    817   // Code Alignment Factor
    818   if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
    819   streamer.EmitULEB128IntValue(1);
    820 
    821   // Data Alignment Factor
    822   if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
    823   streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
    824 
    825   // Return Address Register
    826   if (verboseAsm) streamer.AddComment("CIE Return Address Column");
    827   streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
    828 
    829   // Augmentation Data Length (optional)
    830 
    831   unsigned augmentationLength = 0;
    832   if (IsEH) {
    833     if (personality) {
    834       // Personality Encoding
    835       augmentationLength += 1;
    836       // Personality
    837       augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
    838     }
    839     if (lsda)
    840       augmentationLength += 1;
    841     // Encoding of the FDE pointers
    842     augmentationLength += 1;
    843 
    844     if (verboseAsm) streamer.AddComment("Augmentation Size");
    845     streamer.EmitULEB128IntValue(augmentationLength);
    846 
    847     // Augmentation Data (optional)
    848     if (personality) {
    849       // Personality Encoding
    850       EmitEncodingByte(streamer, personalityEncoding,
    851                        "Personality Encoding");
    852       // Personality
    853       if (verboseAsm) streamer.AddComment("Personality");
    854       EmitPersonality(streamer, *personality, personalityEncoding);
    855     }
    856 
    857     if (lsda)
    858       EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
    859 
    860     // Encoding of the FDE pointers
    861     EmitEncodingByte(streamer, TAI.getFDEEncoding(UsingCFI),
    862                      "FDE Encoding");
    863   }
    864 
    865   // Initial Instructions
    866 
    867   const MCAsmInfo &MAI = context.getAsmInfo();
    868   const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
    869   std::vector<MCCFIInstruction> Instructions;
    870 
    871   for (int i = 0, n = Moves.size(); i != n; ++i) {
    872     MCSymbol *Label = Moves[i].getLabel();
    873     const MachineLocation &Dst =
    874       TranslateMachineLocation(MRI, Moves[i].getDestination());
    875     const MachineLocation &Src =
    876       TranslateMachineLocation(MRI, Moves[i].getSource());
    877     MCCFIInstruction Inst(Label, Dst, Src);
    878     Instructions.push_back(Inst);
    879   }
    880 
    881   EmitCFIInstructions(streamer, Instructions, NULL);
    882 
    883   // Padding
    884   streamer.EmitValueToAlignment(IsEH
    885                                 ? 4 : context.getAsmInfo().getPointerSize());
    886 
    887   streamer.EmitLabel(sectionEnd);
    888   return *sectionStart;
    889 }
    890 
    891 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
    892                                     const MCSymbol &cieStart,
    893                                     const MCDwarfFrameInfo &frame) {
    894   MCContext &context = streamer.getContext();
    895   MCSymbol *fdeStart = context.CreateTempSymbol();
    896   MCSymbol *fdeEnd = context.CreateTempSymbol();
    897   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
    898   const TargetAsmInfo &TAI = context.getTargetAsmInfo();
    899   bool verboseAsm = streamer.isVerboseAsm();
    900 
    901   if (!MOFI->isFunctionEHFrameSymbolPrivate() && IsEH) {
    902     MCSymbol *EHSym =
    903       context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
    904     streamer.EmitEHSymAttributes(frame.Function, EHSym);
    905     streamer.EmitLabel(EHSym);
    906   }
    907 
    908   // Length
    909   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
    910   if (verboseAsm) streamer.AddComment("FDE Length");
    911   streamer.EmitAbsValue(Length, 4);
    912 
    913   streamer.EmitLabel(fdeStart);
    914 
    915   // CIE Pointer
    916   const MCAsmInfo &asmInfo = context.getAsmInfo();
    917   if (IsEH) {
    918     const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
    919                                                  0);
    920     if (verboseAsm) streamer.AddComment("FDE CIE Offset");
    921     streamer.EmitAbsValue(offset, 4);
    922   } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
    923     const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
    924                                                  cieStart, 0);
    925     streamer.EmitAbsValue(offset, 4);
    926   } else {
    927     streamer.EmitSymbolValue(&cieStart, 4);
    928   }
    929 
    930   unsigned fdeEncoding = TAI.getFDEEncoding(UsingCFI);
    931   unsigned size = getSizeForEncoding(streamer, fdeEncoding);
    932 
    933   // PC Begin
    934   unsigned PCBeginEncoding = IsEH ? fdeEncoding :
    935     (unsigned)dwarf::DW_EH_PE_absptr;
    936   unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
    937   EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
    938 
    939   // PC Range
    940   const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
    941                                               *frame.End, 0);
    942   if (verboseAsm) streamer.AddComment("FDE address range");
    943   streamer.EmitAbsValue(Range, size);
    944 
    945   if (IsEH) {
    946     // Augmentation Data Length
    947     unsigned augmentationLength = 0;
    948 
    949     if (frame.Lsda)
    950       augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
    951 
    952     if (verboseAsm) streamer.AddComment("Augmentation size");
    953     streamer.EmitULEB128IntValue(augmentationLength);
    954 
    955     // Augmentation Data
    956     if (frame.Lsda)
    957       EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
    958                  "Language Specific Data Area");
    959   }
    960 
    961   // Call Frame Instructions
    962 
    963   EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
    964 
    965   // Padding
    966   streamer.EmitValueToAlignment(PCBeginSize);
    967 
    968   return fdeEnd;
    969 }
    970 
    971 namespace {
    972   struct CIEKey {
    973     static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
    974     static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
    975 
    976     CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
    977            unsigned LsdaEncoding_) : Personality(Personality_),
    978                                      PersonalityEncoding(PersonalityEncoding_),
    979                                      LsdaEncoding(LsdaEncoding_) {
    980     }
    981     const MCSymbol* Personality;
    982     unsigned PersonalityEncoding;
    983     unsigned LsdaEncoding;
    984   };
    985 }
    986 
    987 namespace llvm {
    988   template <>
    989   struct DenseMapInfo<CIEKey> {
    990     static CIEKey getEmptyKey() {
    991       return CIEKey::getEmptyKey();
    992     }
    993     static CIEKey getTombstoneKey() {
    994       return CIEKey::getTombstoneKey();
    995     }
    996     static unsigned getHashValue(const CIEKey &Key) {
    997       FoldingSetNodeID ID;
    998       ID.AddPointer(Key.Personality);
    999       ID.AddInteger(Key.PersonalityEncoding);
   1000       ID.AddInteger(Key.LsdaEncoding);
   1001       return ID.ComputeHash();
   1002     }
   1003     static bool isEqual(const CIEKey &LHS,
   1004                         const CIEKey &RHS) {
   1005       return LHS.Personality == RHS.Personality &&
   1006         LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
   1007         LHS.LsdaEncoding == RHS.LsdaEncoding;
   1008     }
   1009   };
   1010 }
   1011 
   1012 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
   1013                                bool UsingCFI,
   1014                                bool IsEH) {
   1015   MCContext &Context = Streamer.getContext();
   1016   MCObjectFileInfo *MOFI =
   1017     const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
   1018   const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
   1019                                     *MOFI->getDwarfFrameSection();
   1020   Streamer.SwitchSection(&Section);
   1021   MCSymbol *SectionStart = Context.CreateTempSymbol();
   1022   Streamer.EmitLabel(SectionStart);
   1023 
   1024   MCSymbol *FDEEnd = NULL;
   1025   DenseMap<CIEKey, const MCSymbol*> CIEStarts;
   1026   FrameEmitterImpl Emitter(UsingCFI, IsEH, SectionStart);
   1027 
   1028   const MCSymbol *DummyDebugKey = NULL;
   1029   for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
   1030     const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
   1031     if (IsEH && MOFI->getCompactUnwindSection() &&
   1032         Frame.CompactUnwindEncoding &&
   1033         Emitter.EmitCompactUnwind(Streamer, Frame)) {
   1034       FDEEnd = NULL;
   1035       continue;
   1036     }
   1037 
   1038     CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
   1039                Frame.LsdaEncoding);
   1040     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
   1041     if (!CIEStart)
   1042       CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
   1043                                   Frame.PersonalityEncoding, Frame.Lsda,
   1044                                   Frame.LsdaEncoding);
   1045 
   1046     FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
   1047 
   1048     if (i != n - 1)
   1049       Streamer.EmitLabel(FDEEnd);
   1050   }
   1051 
   1052   Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
   1053   if (FDEEnd)
   1054     Streamer.EmitLabel(FDEEnd);
   1055 }
   1056 
   1057 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
   1058                                          uint64_t AddrDelta) {
   1059   SmallString<256> Tmp;
   1060   raw_svector_ostream OS(Tmp);
   1061   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
   1062   Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
   1063 }
   1064 
   1065 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
   1066                                            raw_ostream &OS) {
   1067   // FIXME: Assumes the code alignment factor is 1.
   1068   if (AddrDelta == 0) {
   1069   } else if (isUIntN(6, AddrDelta)) {
   1070     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
   1071     OS << Opcode;
   1072   } else if (isUInt<8>(AddrDelta)) {
   1073     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
   1074     OS << uint8_t(AddrDelta);
   1075   } else if (isUInt<16>(AddrDelta)) {
   1076     // FIXME: check what is the correct behavior on a big endian machine.
   1077     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
   1078     OS << uint8_t( AddrDelta       & 0xff);
   1079     OS << uint8_t((AddrDelta >> 8) & 0xff);
   1080   } else {
   1081     // FIXME: check what is the correct behavior on a big endian machine.
   1082     assert(isUInt<32>(AddrDelta));
   1083     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
   1084     OS << uint8_t( AddrDelta        & 0xff);
   1085     OS << uint8_t((AddrDelta >> 8)  & 0xff);
   1086     OS << uint8_t((AddrDelta >> 16) & 0xff);
   1087     OS << uint8_t((AddrDelta >> 24) & 0xff);
   1088 
   1089   }
   1090 }
   1091