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/ADT/Hashing.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/Twine.h" 14 #include "llvm/Config/config.h" 15 #include "llvm/MC/MCAsmInfo.h" 16 #include "llvm/MC/MCContext.h" 17 #include "llvm/MC/MCExpr.h" 18 #include "llvm/MC/MCObjectFileInfo.h" 19 #include "llvm/MC/MCRegisterInfo.h" 20 #include "llvm/MC/MCStreamer.h" 21 #include "llvm/MC/MCSymbol.h" 22 #include "llvm/Support/Debug.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/Support/LEB128.h" 25 #include "llvm/Support/Path.h" 26 #include "llvm/Support/SourceMgr.h" 27 #include "llvm/Support/raw_ostream.h" 28 using namespace llvm; 29 30 // Given a special op, return the address skip amount (in units of 31 // DWARF2_LINE_MIN_INSN_LENGTH. 32 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE) 33 34 // The maximum address skip amount that can be encoded with a special op. 35 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255) 36 37 // First special line opcode - leave room for the standard opcodes. 38 // Note: If you want to change this, you'll have to update the 39 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit(). 40 #define DWARF2_LINE_OPCODE_BASE 13 41 42 // Minimum line offset in a special line info. opcode. This value 43 // was chosen to give a reasonable range of values. 44 #define DWARF2_LINE_BASE -5 45 46 // Range of line offsets in a special line info. opcode. 47 #define DWARF2_LINE_RANGE 14 48 49 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) { 50 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment(); 51 if (MinInsnLength == 1) 52 return AddrDelta; 53 if (AddrDelta % MinInsnLength != 0) { 54 // TODO: report this error, but really only once. 55 ; 56 } 57 return AddrDelta / MinInsnLength; 58 } 59 60 // 61 // This is called when an instruction is assembled into the specified section 62 // and if there is information from the last .loc directive that has yet to have 63 // a line entry made for it is made. 64 // 65 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) { 66 if (!MCOS->getContext().getDwarfLocSeen()) 67 return; 68 69 // Create a symbol at in the current section for use in the line entry. 70 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol(); 71 // Set the value of the symbol to use for the MCLineEntry. 72 MCOS->EmitLabel(LineSym); 73 74 // Get the current .loc info saved in the context. 75 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); 76 77 // Create a (local) line entry with the symbol and the current .loc info. 78 MCLineEntry LineEntry(LineSym, DwarfLoc); 79 80 // clear DwarfLocSeen saying the current .loc info is now used. 81 MCOS->getContext().ClearDwarfLocSeen(); 82 83 // Get the MCLineSection for this section, if one does not exist for this 84 // section create it. 85 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = 86 MCOS->getContext().getMCLineSections(); 87 MCLineSection *LineSection = MCLineSections.lookup(Section); 88 if (!LineSection) { 89 // Create a new MCLineSection. This will be deleted after the dwarf line 90 // table is created using it by iterating through the MCLineSections 91 // DenseMap. 92 LineSection = new MCLineSection; 93 // Save a pointer to the new LineSection into the MCLineSections DenseMap. 94 MCOS->getContext().addMCLineSection(Section, LineSection); 95 } 96 97 // Add the line entry to this section's entries. 98 LineSection->addLineEntry(LineEntry, 99 MCOS->getContext().getDwarfCompileUnitID()); 100 } 101 102 // 103 // This helper routine returns an expression of End - Start + IntVal . 104 // 105 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS, 106 const MCSymbol &Start, 107 const MCSymbol &End, 108 int IntVal) { 109 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 110 const MCExpr *Res = 111 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext()); 112 const MCExpr *RHS = 113 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext()); 114 const MCExpr *Res1 = 115 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext()); 116 const MCExpr *Res2 = 117 MCConstantExpr::Create(IntVal, MCOS.getContext()); 118 const MCExpr *Res3 = 119 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext()); 120 return Res3; 121 } 122 123 // 124 // This emits the Dwarf line table for the specified section from the entries 125 // in the LineSection. 126 // 127 static inline void EmitDwarfLineTable(MCStreamer *MCOS, 128 const MCSection *Section, 129 const MCLineSection *LineSection, 130 unsigned CUID) { 131 // This LineSection does not contain any LineEntry for the given Compile Unit. 132 if (!LineSection->containEntriesForID(CUID)) 133 return; 134 135 unsigned FileNum = 1; 136 unsigned LastLine = 1; 137 unsigned Column = 0; 138 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 139 unsigned Isa = 0; 140 unsigned Discriminator = 0; 141 MCSymbol *LastLabel = NULL; 142 143 // Loop through each MCLineEntry and encode the dwarf line number table. 144 for (MCLineSection::const_iterator 145 it = LineSection->getMCLineEntries(CUID).begin(), 146 ie = LineSection->getMCLineEntries(CUID).end(); it != ie; ++it) { 147 148 if (FileNum != it->getFileNum()) { 149 FileNum = it->getFileNum(); 150 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1); 151 MCOS->EmitULEB128IntValue(FileNum); 152 } 153 if (Column != it->getColumn()) { 154 Column = it->getColumn(); 155 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1); 156 MCOS->EmitULEB128IntValue(Column); 157 } 158 if (Discriminator != it->getDiscriminator()) { 159 Discriminator = it->getDiscriminator(); 160 unsigned Size = 161 MCOS->getContext().getAsmInfo()->getULEB128Size(Discriminator); 162 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1); 163 MCOS->EmitULEB128IntValue(Size + 1); 164 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1); 165 MCOS->EmitULEB128IntValue(Discriminator); 166 } 167 if (Isa != it->getIsa()) { 168 Isa = it->getIsa(); 169 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1); 170 MCOS->EmitULEB128IntValue(Isa); 171 } 172 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 173 Flags = it->getFlags(); 174 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1); 175 } 176 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK) 177 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1); 178 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END) 179 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1); 180 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 181 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); 182 183 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine; 184 MCSymbol *Label = it->getLabel(); 185 186 // At this point we want to emit/create the sequence to encode the delta in 187 // line numbers and the increment of the address from the previous Label 188 // and the current Label. 189 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo(); 190 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 191 asmInfo->getPointerSize()); 192 193 LastLine = it->getLine(); 194 LastLabel = Label; 195 } 196 197 // Emit a DW_LNE_end_sequence for the end of the section. 198 // Using the pointer Section create a temporary label at the end of the 199 // section and use that and the LastLabel to compute the address delta 200 // and use INT64_MAX as the line delta which is the signal that this is 201 // actually a DW_LNE_end_sequence. 202 203 // Switch to the section to be able to create a symbol at its end. 204 // TODO: keep track of the last subsection so that this symbol appears in the 205 // correct place. 206 MCOS->SwitchSection(Section); 207 208 MCContext &context = MCOS->getContext(); 209 // Create a symbol at the end of the section. 210 MCSymbol *SectionEnd = context.CreateTempSymbol(); 211 // Set the value of the symbol, as we are at the end of the section. 212 MCOS->EmitLabel(SectionEnd); 213 214 // Switch back the dwarf line section. 215 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); 216 217 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo(); 218 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd, 219 asmInfo->getPointerSize()); 220 } 221 222 // 223 // This emits the Dwarf file and the line tables. 224 // 225 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) { 226 MCContext &context = MCOS->getContext(); 227 // Switch to the section where the table will be emitted into. 228 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); 229 230 const DenseMap<unsigned, MCSymbol *> &MCLineTableSymbols = 231 MCOS->getContext().getMCLineTableSymbols(); 232 // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does 233 // not exist, CUID will be 0 and MCLineTableSymbols will be empty. 234 // Handle Compile Unit 0, the line table start symbol is the section symbol. 235 const MCSymbol *LineStartSym = EmitCU(MCOS, 0); 236 // Handle the rest of the Compile Units. 237 for (unsigned Is = 1, Ie = MCLineTableSymbols.size(); Is < Ie; Is++) 238 EmitCU(MCOS, Is); 239 240 // Now delete the MCLineSections that were created in MCLineEntry::Make() 241 // and used to emit the line table. 242 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = 243 MCOS->getContext().getMCLineSections(); 244 for (DenseMap<const MCSection *, MCLineSection *>::const_iterator it = 245 MCLineSections.begin(), ie = MCLineSections.end(); it != ie; 246 ++it) 247 delete it->second; 248 249 return LineStartSym; 250 } 251 252 const MCSymbol *MCDwarfFileTable::EmitCU(MCStreamer *MCOS, unsigned CUID) { 253 MCContext &context = MCOS->getContext(); 254 255 // Create a symbol at the beginning of the line table. 256 MCSymbol *LineStartSym = MCOS->getContext().getMCLineTableSymbol(CUID); 257 if (!LineStartSym) 258 LineStartSym = context.CreateTempSymbol(); 259 // Set the value of the symbol, as we are at the start of the line table. 260 MCOS->EmitLabel(LineStartSym); 261 262 // Create a symbol for the end of the section (to be set when we get there). 263 MCSymbol *LineEndSym = context.CreateTempSymbol(); 264 265 // The first 4 bytes is the total length of the information for this 266 // compilation unit (not including these 4 bytes for the length). 267 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4), 268 4); 269 270 // Next 2 bytes is the Version, which is Dwarf 2. 271 MCOS->EmitIntValue(2, 2); 272 273 // Create a symbol for the end of the prologue (to be set when we get there). 274 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end 275 276 // Length of the prologue, is the next 4 bytes. Which is the start of the 277 // section to the end of the prologue. Not including the 4 bytes for the 278 // total length, the 2 bytes for the version, and these 4 bytes for the 279 // length of the prologue. 280 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, 281 (4 + 2 + 4)), 4); 282 283 // Parameters of the state machine, are next. 284 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1); 285 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1); 286 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1); 287 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1); 288 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1); 289 290 // Standard opcode lengths 291 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy 292 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc 293 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line 294 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file 295 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column 296 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt 297 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block 298 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc 299 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc 300 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end 301 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin 302 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa 303 304 // Put out the directory and file tables. 305 306 // First the directory table. 307 const SmallVectorImpl<StringRef> &MCDwarfDirs = 308 context.getMCDwarfDirs(CUID); 309 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) { 310 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName 311 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string 312 } 313 MCOS->EmitIntValue(0, 1); // Terminate the directory list 314 315 // Second the file table. 316 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles = 317 MCOS->getContext().getMCDwarfFiles(CUID); 318 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { 319 MCOS->EmitBytes(MCDwarfFiles[i]->getName()); // FileName 320 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string 321 // the Directory num 322 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex()); 323 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0) 324 MCOS->EmitIntValue(0, 1); // filesize (always 0) 325 } 326 MCOS->EmitIntValue(0, 1); // Terminate the file list 327 328 // This is the end of the prologue, so set the value of the symbol at the 329 // end of the prologue (that was used in a previous expression). 330 MCOS->EmitLabel(ProEndSym); 331 332 // Put out the line tables. 333 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = 334 MCOS->getContext().getMCLineSections(); 335 const std::vector<const MCSection *> &MCLineSectionOrder = 336 MCOS->getContext().getMCLineSectionOrder(); 337 for (std::vector<const MCSection*>::const_iterator it = 338 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie; 339 ++it) { 340 const MCSection *Sec = *it; 341 const MCLineSection *Line = MCLineSections.lookup(Sec); 342 EmitDwarfLineTable(MCOS, Sec, Line, CUID); 343 } 344 345 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() 346 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) { 347 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures 348 // it requires: 349 // total_length >= prologue_length + 10 350 // We are 4 bytes short, since we have total_length = 51 and 351 // prologue_length = 45 352 353 // The regular end_sequence should be sufficient. 354 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0); 355 } 356 357 // This is the end of the section, so set the value of the symbol at the end 358 // of this section (that was used in a previous expression). 359 MCOS->EmitLabel(LineEndSym); 360 361 return LineStartSym; 362 } 363 364 /// Utility function to emit the encoding to a streamer. 365 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta, 366 uint64_t AddrDelta) { 367 MCContext &Context = MCOS->getContext(); 368 SmallString<256> Tmp; 369 raw_svector_ostream OS(Tmp); 370 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS); 371 MCOS->EmitBytes(OS.str()); 372 } 373 374 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. 375 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta, 376 uint64_t AddrDelta, raw_ostream &OS) { 377 uint64_t Temp, Opcode; 378 bool NeedCopy = false; 379 380 // Scale the address delta by the minimum instruction length. 381 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 382 383 // A LineDelta of INT64_MAX is a signal that this is actually a 384 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 385 // end_sequence to emit the matrix entry. 386 if (LineDelta == INT64_MAX) { 387 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA) 388 OS << char(dwarf::DW_LNS_const_add_pc); 389 else { 390 OS << char(dwarf::DW_LNS_advance_pc); 391 encodeULEB128(AddrDelta, OS); 392 } 393 OS << char(dwarf::DW_LNS_extended_op); 394 OS << char(1); 395 OS << char(dwarf::DW_LNE_end_sequence); 396 return; 397 } 398 399 // Bias the line delta by the base. 400 Temp = LineDelta - DWARF2_LINE_BASE; 401 402 // If the line increment is out of range of a special opcode, we must encode 403 // it with DW_LNS_advance_line. 404 if (Temp >= DWARF2_LINE_RANGE) { 405 OS << char(dwarf::DW_LNS_advance_line); 406 encodeSLEB128(LineDelta, OS); 407 408 LineDelta = 0; 409 Temp = 0 - DWARF2_LINE_BASE; 410 NeedCopy = true; 411 } 412 413 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. 414 if (LineDelta == 0 && AddrDelta == 0) { 415 OS << char(dwarf::DW_LNS_copy); 416 return; 417 } 418 419 // Bias the opcode by the special opcode base. 420 Temp += DWARF2_LINE_OPCODE_BASE; 421 422 // Avoid overflow when addr_delta is large. 423 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) { 424 // Try using a special opcode. 425 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE; 426 if (Opcode <= 255) { 427 OS << char(Opcode); 428 return; 429 } 430 431 // Try using DW_LNS_const_add_pc followed by special op. 432 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE; 433 if (Opcode <= 255) { 434 OS << char(dwarf::DW_LNS_const_add_pc); 435 OS << char(Opcode); 436 return; 437 } 438 } 439 440 // Otherwise use DW_LNS_advance_pc. 441 OS << char(dwarf::DW_LNS_advance_pc); 442 encodeULEB128(AddrDelta, OS); 443 444 if (NeedCopy) 445 OS << char(dwarf::DW_LNS_copy); 446 else 447 OS << char(Temp); 448 } 449 450 void MCDwarfFile::print(raw_ostream &OS) const { 451 OS << '"' << getName() << '"'; 452 } 453 454 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 455 void MCDwarfFile::dump() const { 456 print(dbgs()); 457 } 458 #endif 459 460 // Utility function to write a tuple for .debug_abbrev. 461 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { 462 MCOS->EmitULEB128IntValue(Name); 463 MCOS->EmitULEB128IntValue(Form); 464 } 465 466 // When generating dwarf for assembly source files this emits 467 // the data for .debug_abbrev section which contains three DIEs. 468 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { 469 MCContext &context = MCOS->getContext(); 470 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 471 472 // DW_TAG_compile_unit DIE abbrev (1). 473 MCOS->EmitULEB128IntValue(1); 474 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit); 475 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); 476 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4); 477 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 478 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); 479 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 480 if (!context.getCompilationDir().empty()) 481 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); 482 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 483 if (!DwarfDebugFlags.empty()) 484 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); 485 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); 486 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); 487 EmitAbbrev(MCOS, 0, 0); 488 489 // DW_TAG_label DIE abbrev (2). 490 MCOS->EmitULEB128IntValue(2); 491 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label); 492 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); 493 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 494 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); 495 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); 496 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 497 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag); 498 EmitAbbrev(MCOS, 0, 0); 499 500 // DW_TAG_unspecified_parameters DIE abbrev (3). 501 MCOS->EmitULEB128IntValue(3); 502 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters); 503 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1); 504 EmitAbbrev(MCOS, 0, 0); 505 506 // Terminate the abbreviations for this compilation unit. 507 MCOS->EmitIntValue(0, 1); 508 } 509 510 // When generating dwarf for assembly source files this emits the data for 511 // .debug_aranges section. Which contains a header and a table of pairs of 512 // PointerSize'ed values for the address and size of section(s) with line table 513 // entries (just the default .text in our case) and a terminating pair of zeros. 514 static void EmitGenDwarfAranges(MCStreamer *MCOS, 515 const MCSymbol *InfoSectionSymbol) { 516 MCContext &context = MCOS->getContext(); 517 518 // Create a symbol at the end of the section that we are creating the dwarf 519 // debugging info to use later in here as part of the expression to calculate 520 // the size of the section for the table. 521 MCOS->SwitchSection(context.getGenDwarfSection()); 522 MCSymbol *SectionEndSym = context.CreateTempSymbol(); 523 MCOS->EmitLabel(SectionEndSym); 524 context.setGenDwarfSectionEndSym(SectionEndSym); 525 526 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 527 528 // This will be the length of the .debug_aranges section, first account for 529 // the size of each item in the header (see below where we emit these items). 530 int Length = 4 + 2 + 4 + 1 + 1; 531 532 // Figure the padding after the header before the table of address and size 533 // pairs who's values are PointerSize'ed. 534 const MCAsmInfo *asmInfo = context.getAsmInfo(); 535 int AddrSize = asmInfo->getPointerSize(); 536 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); 537 if (Pad == 2 * AddrSize) 538 Pad = 0; 539 Length += Pad; 540 541 // Add the size of the pair of PointerSize'ed values for the address and size 542 // of the one default .text section we have in the table. 543 Length += 2 * AddrSize; 544 // And the pair of terminating zeros. 545 Length += 2 * AddrSize; 546 547 548 // Emit the header for this section. 549 // The 4 byte length not including the 4 byte value for the length. 550 MCOS->EmitIntValue(Length - 4, 4); 551 // The 2 byte version, which is 2. 552 MCOS->EmitIntValue(2, 2); 553 // The 4 byte offset to the compile unit in the .debug_info from the start 554 // of the .debug_info. 555 if (InfoSectionSymbol) 556 MCOS->EmitSymbolValue(InfoSectionSymbol, 4); 557 else 558 MCOS->EmitIntValue(0, 4); 559 // The 1 byte size of an address. 560 MCOS->EmitIntValue(AddrSize, 1); 561 // The 1 byte size of a segment descriptor, we use a value of zero. 562 MCOS->EmitIntValue(0, 1); 563 // Align the header with the padding if needed, before we put out the table. 564 for(int i = 0; i < Pad; i++) 565 MCOS->EmitIntValue(0, 1); 566 567 // Now emit the table of pairs of PointerSize'ed values for the section(s) 568 // address and size, in our case just the one default .text section. 569 const MCExpr *Addr = MCSymbolRefExpr::Create( 570 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context); 571 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS, 572 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0); 573 MCOS->EmitAbsValue(Addr, AddrSize); 574 MCOS->EmitAbsValue(Size, AddrSize); 575 576 // And finally the pair of terminating zeros. 577 MCOS->EmitIntValue(0, AddrSize); 578 MCOS->EmitIntValue(0, AddrSize); 579 } 580 581 // When generating dwarf for assembly source files this emits the data for 582 // .debug_info section which contains three parts. The header, the compile_unit 583 // DIE and a list of label DIEs. 584 static void EmitGenDwarfInfo(MCStreamer *MCOS, 585 const MCSymbol *AbbrevSectionSymbol, 586 const MCSymbol *LineSectionSymbol) { 587 MCContext &context = MCOS->getContext(); 588 589 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 590 591 // Create a symbol at the start and end of this section used in here for the 592 // expression to calculate the length in the header. 593 MCSymbol *InfoStart = context.CreateTempSymbol(); 594 MCOS->EmitLabel(InfoStart); 595 MCSymbol *InfoEnd = context.CreateTempSymbol(); 596 597 // First part: the header. 598 599 // The 4 byte total length of the information for this compilation unit, not 600 // including these 4 bytes. 601 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4); 602 MCOS->EmitAbsValue(Length, 4); 603 604 // The 2 byte DWARF version, which is 2. 605 MCOS->EmitIntValue(2, 2); 606 607 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev, 608 // it is at the start of that section so this is zero. 609 if (AbbrevSectionSymbol) { 610 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4); 611 } else { 612 MCOS->EmitIntValue(0, 4); 613 } 614 615 const MCAsmInfo *asmInfo = context.getAsmInfo(); 616 int AddrSize = asmInfo->getPointerSize(); 617 // The 1 byte size of an address. 618 MCOS->EmitIntValue(AddrSize, 1); 619 620 // Second part: the compile_unit DIE. 621 622 // The DW_TAG_compile_unit DIE abbrev (1). 623 MCOS->EmitULEB128IntValue(1); 624 625 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section, 626 // which is at the start of that section so this is zero. 627 if (LineSectionSymbol) { 628 MCOS->EmitSymbolValue(LineSectionSymbol, 4); 629 } else { 630 MCOS->EmitIntValue(0, 4); 631 } 632 633 // AT_low_pc, the first address of the default .text section. 634 const MCExpr *Start = MCSymbolRefExpr::Create( 635 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context); 636 MCOS->EmitAbsValue(Start, AddrSize); 637 638 // AT_high_pc, the last address of the default .text section. 639 const MCExpr *End = MCSymbolRefExpr::Create( 640 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context); 641 MCOS->EmitAbsValue(End, AddrSize); 642 643 // AT_name, the name of the source file. Reconstruct from the first directory 644 // and file table entries. 645 const SmallVectorImpl<StringRef> &MCDwarfDirs = 646 context.getMCDwarfDirs(); 647 if (MCDwarfDirs.size() > 0) { 648 MCOS->EmitBytes(MCDwarfDirs[0]); 649 MCOS->EmitBytes("/"); 650 } 651 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles = 652 MCOS->getContext().getMCDwarfFiles(); 653 MCOS->EmitBytes(MCDwarfFiles[1]->getName()); 654 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 655 656 // AT_comp_dir, the working directory the assembly was done in. 657 if (!context.getCompilationDir().empty()) { 658 MCOS->EmitBytes(context.getCompilationDir()); 659 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 660 } 661 662 // AT_APPLE_flags, the command line arguments of the assembler tool. 663 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 664 if (!DwarfDebugFlags.empty()){ 665 MCOS->EmitBytes(DwarfDebugFlags); 666 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 667 } 668 669 // AT_producer, the version of the assembler tool. 670 StringRef DwarfDebugProducer = context.getDwarfDebugProducer(); 671 if (!DwarfDebugProducer.empty()){ 672 MCOS->EmitBytes(DwarfDebugProducer); 673 } 674 else { 675 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM ")); 676 MCOS->EmitBytes(StringRef(PACKAGE_VERSION)); 677 MCOS->EmitBytes(StringRef(")")); 678 } 679 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 680 681 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 682 // draft has no standard code for assembler. 683 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2); 684 685 // Third part: the list of label DIEs. 686 687 // Loop on saved info for dwarf labels and create the DIEs for them. 688 const std::vector<const MCGenDwarfLabelEntry *> &Entries = 689 MCOS->getContext().getMCGenDwarfLabelEntries(); 690 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it = 691 Entries.begin(), ie = Entries.end(); it != ie; 692 ++it) { 693 const MCGenDwarfLabelEntry *Entry = *it; 694 695 // The DW_TAG_label DIE abbrev (2). 696 MCOS->EmitULEB128IntValue(2); 697 698 // AT_name, of the label without any leading underbar. 699 MCOS->EmitBytes(Entry->getName()); 700 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 701 702 // AT_decl_file, index into the file table. 703 MCOS->EmitIntValue(Entry->getFileNumber(), 4); 704 705 // AT_decl_line, source line number. 706 MCOS->EmitIntValue(Entry->getLineNumber(), 4); 707 708 // AT_low_pc, start address of the label. 709 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(), 710 MCSymbolRefExpr::VK_None, context); 711 MCOS->EmitAbsValue(AT_low_pc, AddrSize); 712 713 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype. 714 MCOS->EmitIntValue(0, 1); 715 716 // The DW_TAG_unspecified_parameters DIE abbrev (3). 717 MCOS->EmitULEB128IntValue(3); 718 719 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's. 720 MCOS->EmitIntValue(0, 1); 721 } 722 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info 723 // for the dwarf labels. 724 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it = 725 Entries.begin(), ie = Entries.end(); it != ie; 726 ++it) { 727 const MCGenDwarfLabelEntry *Entry = *it; 728 delete Entry; 729 } 730 731 // Add the NULL DIE terminating the Compile Unit DIE's. 732 MCOS->EmitIntValue(0, 1); 733 734 // Now set the value of the symbol at the end of the info section. 735 MCOS->EmitLabel(InfoEnd); 736 } 737 738 // 739 // When generating dwarf for assembly source files this emits the Dwarf 740 // sections. 741 // 742 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) { 743 // Create the dwarf sections in this order (.debug_line already created). 744 MCContext &context = MCOS->getContext(); 745 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 746 bool CreateDwarfSectionSymbols = 747 AsmInfo->doesDwarfUseRelocationsAcrossSections(); 748 if (!CreateDwarfSectionSymbols) 749 LineSectionSymbol = NULL; 750 MCSymbol *AbbrevSectionSymbol = NULL; 751 MCSymbol *InfoSectionSymbol = NULL; 752 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 753 if (CreateDwarfSectionSymbols) { 754 InfoSectionSymbol = context.CreateTempSymbol(); 755 MCOS->EmitLabel(InfoSectionSymbol); 756 } 757 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 758 if (CreateDwarfSectionSymbols) { 759 AbbrevSectionSymbol = context.CreateTempSymbol(); 760 MCOS->EmitLabel(AbbrevSectionSymbol); 761 } 762 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 763 764 // If there are no line table entries then do not emit any section contents. 765 if (context.getMCLineSections().empty()) 766 return; 767 768 // Output the data for .debug_aranges section. 769 EmitGenDwarfAranges(MCOS, InfoSectionSymbol); 770 771 // Output the data for .debug_abbrev section. 772 EmitGenDwarfAbbrev(MCOS); 773 774 // Output the data for .debug_info section. 775 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol); 776 } 777 778 // 779 // When generating dwarf for assembly source files this is called when symbol 780 // for a label is created. If this symbol is not a temporary and is in the 781 // section that dwarf is being generated for, save the needed info to create 782 // a dwarf label. 783 // 784 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, 785 SourceMgr &SrcMgr, SMLoc &Loc) { 786 // We won't create dwarf labels for temporary symbols or symbols not in 787 // the default text. 788 if (Symbol->isTemporary()) 789 return; 790 MCContext &context = MCOS->getContext(); 791 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first) 792 return; 793 794 // The dwarf label's name does not have the symbol name's leading 795 // underbar if any. 796 StringRef Name = Symbol->getName(); 797 if (Name.startswith("_")) 798 Name = Name.substr(1, Name.size()-1); 799 800 // Get the dwarf file number to be used for the dwarf label. 801 unsigned FileNumber = context.getGenDwarfFileNumber(); 802 803 // Finding the line number is the expensive part which is why we just don't 804 // pass it in as for some symbols we won't create a dwarf label. 805 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); 806 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); 807 808 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc 809 // values so that they don't have things like an ARM thumb bit from the 810 // original symbol. So when used they won't get a low bit set after 811 // relocation. 812 MCSymbol *Label = context.CreateTempSymbol(); 813 MCOS->EmitLabel(Label); 814 815 // Create and entry for the info and add it to the other entries. 816 MCGenDwarfLabelEntry *Entry = 817 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label); 818 MCOS->getContext().addMCGenDwarfLabelEntry(Entry); 819 } 820 821 static int getDataAlignmentFactor(MCStreamer &streamer) { 822 MCContext &context = streamer.getContext(); 823 const MCAsmInfo *asmInfo = context.getAsmInfo(); 824 int size = asmInfo->getCalleeSaveStackSlotSize(); 825 if (asmInfo->isStackGrowthDirectionUp()) 826 return size; 827 else 828 return -size; 829 } 830 831 static unsigned getSizeForEncoding(MCStreamer &streamer, 832 unsigned symbolEncoding) { 833 MCContext &context = streamer.getContext(); 834 unsigned format = symbolEncoding & 0x0f; 835 switch (format) { 836 default: llvm_unreachable("Unknown Encoding"); 837 case dwarf::DW_EH_PE_absptr: 838 case dwarf::DW_EH_PE_signed: 839 return context.getAsmInfo()->getPointerSize(); 840 case dwarf::DW_EH_PE_udata2: 841 case dwarf::DW_EH_PE_sdata2: 842 return 2; 843 case dwarf::DW_EH_PE_udata4: 844 case dwarf::DW_EH_PE_sdata4: 845 return 4; 846 case dwarf::DW_EH_PE_udata8: 847 case dwarf::DW_EH_PE_sdata8: 848 return 8; 849 } 850 } 851 852 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol, 853 unsigned symbolEncoding, bool isEH, 854 const char *comment = 0) { 855 MCContext &context = streamer.getContext(); 856 const MCAsmInfo *asmInfo = context.getAsmInfo(); 857 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol, 858 symbolEncoding, 859 streamer); 860 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 861 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment); 862 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH) 863 streamer.EmitAbsValue(v, size); 864 else 865 streamer.EmitValue(v, size); 866 } 867 868 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, 869 unsigned symbolEncoding) { 870 MCContext &context = streamer.getContext(); 871 const MCAsmInfo *asmInfo = context.getAsmInfo(); 872 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol, 873 symbolEncoding, 874 streamer); 875 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 876 streamer.EmitValue(v, size); 877 } 878 879 namespace { 880 class FrameEmitterImpl { 881 int CFAOffset; 882 int CIENum; 883 bool UsingCFI; 884 bool IsEH; 885 const MCSymbol *SectionStart; 886 public: 887 FrameEmitterImpl(bool usingCFI, bool isEH) 888 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH), 889 SectionStart(0) {} 890 891 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; } 892 893 /// EmitCompactUnwind - Emit the unwind information in a compact way. 894 void EmitCompactUnwind(MCStreamer &streamer, 895 const MCDwarfFrameInfo &frame); 896 897 const MCSymbol &EmitCIE(MCStreamer &streamer, 898 const MCSymbol *personality, 899 unsigned personalityEncoding, 900 const MCSymbol *lsda, 901 bool IsSignalFrame, 902 unsigned lsdaEncoding, 903 bool IsSimple); 904 MCSymbol *EmitFDE(MCStreamer &streamer, 905 const MCSymbol &cieStart, 906 const MCDwarfFrameInfo &frame); 907 void EmitCFIInstructions(MCStreamer &streamer, 908 ArrayRef<MCCFIInstruction> Instrs, 909 MCSymbol *BaseLabel); 910 void EmitCFIInstruction(MCStreamer &Streamer, 911 const MCCFIInstruction &Instr); 912 }; 913 914 } // end anonymous namespace 915 916 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding, 917 StringRef Prefix) { 918 if (Streamer.isVerboseAsm()) { 919 const char *EncStr; 920 switch (Encoding) { 921 default: EncStr = "<unknown encoding>"; break; 922 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break; 923 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break; 924 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break; 925 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break; 926 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break; 927 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break; 928 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break; 929 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: 930 EncStr = "pcrel udata4"; 931 break; 932 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: 933 EncStr = "pcrel sdata4"; 934 break; 935 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: 936 EncStr = "pcrel udata8"; 937 break; 938 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: 939 EncStr = "screl sdata8"; 940 break; 941 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4: 942 EncStr = "indirect pcrel udata4"; 943 break; 944 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4: 945 EncStr = "indirect pcrel sdata4"; 946 break; 947 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8: 948 EncStr = "indirect pcrel udata8"; 949 break; 950 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8: 951 EncStr = "indirect pcrel sdata8"; 952 break; 953 } 954 955 Streamer.AddComment(Twine(Prefix) + " = " + EncStr); 956 } 957 958 Streamer.EmitIntValue(Encoding, 1); 959 } 960 961 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer, 962 const MCCFIInstruction &Instr) { 963 int dataAlignmentFactor = getDataAlignmentFactor(Streamer); 964 bool VerboseAsm = Streamer.isVerboseAsm(); 965 966 switch (Instr.getOperation()) { 967 case MCCFIInstruction::OpRegister: { 968 unsigned Reg1 = Instr.getRegister(); 969 unsigned Reg2 = Instr.getRegister2(); 970 if (VerboseAsm) { 971 Streamer.AddComment("DW_CFA_register"); 972 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1)); 973 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2)); 974 } 975 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1); 976 Streamer.EmitULEB128IntValue(Reg1); 977 Streamer.EmitULEB128IntValue(Reg2); 978 return; 979 } 980 case MCCFIInstruction::OpWindowSave: { 981 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1); 982 return; 983 } 984 case MCCFIInstruction::OpUndefined: { 985 unsigned Reg = Instr.getRegister(); 986 if (VerboseAsm) { 987 Streamer.AddComment("DW_CFA_undefined"); 988 Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 989 } 990 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1); 991 Streamer.EmitULEB128IntValue(Reg); 992 return; 993 } 994 case MCCFIInstruction::OpAdjustCfaOffset: 995 case MCCFIInstruction::OpDefCfaOffset: { 996 const bool IsRelative = 997 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset; 998 999 if (VerboseAsm) 1000 Streamer.AddComment("DW_CFA_def_cfa_offset"); 1001 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1); 1002 1003 if (IsRelative) 1004 CFAOffset += Instr.getOffset(); 1005 else 1006 CFAOffset = -Instr.getOffset(); 1007 1008 if (VerboseAsm) 1009 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset))); 1010 Streamer.EmitULEB128IntValue(CFAOffset); 1011 1012 return; 1013 } 1014 case MCCFIInstruction::OpDefCfa: { 1015 if (VerboseAsm) 1016 Streamer.AddComment("DW_CFA_def_cfa"); 1017 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1); 1018 1019 if (VerboseAsm) 1020 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister())); 1021 Streamer.EmitULEB128IntValue(Instr.getRegister()); 1022 1023 CFAOffset = -Instr.getOffset(); 1024 1025 if (VerboseAsm) 1026 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset))); 1027 Streamer.EmitULEB128IntValue(CFAOffset); 1028 1029 return; 1030 } 1031 1032 case MCCFIInstruction::OpDefCfaRegister: { 1033 if (VerboseAsm) 1034 Streamer.AddComment("DW_CFA_def_cfa_register"); 1035 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1); 1036 1037 if (VerboseAsm) 1038 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister())); 1039 Streamer.EmitULEB128IntValue(Instr.getRegister()); 1040 1041 return; 1042 } 1043 1044 case MCCFIInstruction::OpOffset: 1045 case MCCFIInstruction::OpRelOffset: { 1046 const bool IsRelative = 1047 Instr.getOperation() == MCCFIInstruction::OpRelOffset; 1048 1049 unsigned Reg = Instr.getRegister(); 1050 int Offset = Instr.getOffset(); 1051 if (IsRelative) 1052 Offset -= CFAOffset; 1053 Offset = Offset / dataAlignmentFactor; 1054 1055 if (Offset < 0) { 1056 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf"); 1057 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1); 1058 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 1059 Streamer.EmitULEB128IntValue(Reg); 1060 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); 1061 Streamer.EmitSLEB128IntValue(Offset); 1062 } else if (Reg < 64) { 1063 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") + 1064 Twine(Reg) + ")"); 1065 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1); 1066 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); 1067 Streamer.EmitULEB128IntValue(Offset); 1068 } else { 1069 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended"); 1070 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1); 1071 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 1072 Streamer.EmitULEB128IntValue(Reg); 1073 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); 1074 Streamer.EmitULEB128IntValue(Offset); 1075 } 1076 return; 1077 } 1078 case MCCFIInstruction::OpRememberState: 1079 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state"); 1080 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1); 1081 return; 1082 case MCCFIInstruction::OpRestoreState: 1083 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state"); 1084 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1); 1085 return; 1086 case MCCFIInstruction::OpSameValue: { 1087 unsigned Reg = Instr.getRegister(); 1088 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value"); 1089 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1); 1090 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 1091 Streamer.EmitULEB128IntValue(Reg); 1092 return; 1093 } 1094 case MCCFIInstruction::OpRestore: { 1095 unsigned Reg = Instr.getRegister(); 1096 if (VerboseAsm) { 1097 Streamer.AddComment("DW_CFA_restore"); 1098 Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 1099 } 1100 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1); 1101 return; 1102 } 1103 case MCCFIInstruction::OpEscape: 1104 if (VerboseAsm) Streamer.AddComment("Escape bytes"); 1105 Streamer.EmitBytes(Instr.getValues()); 1106 return; 1107 } 1108 llvm_unreachable("Unhandled case in switch"); 1109 } 1110 1111 /// EmitFrameMoves - Emit frame instructions to describe the layout of the 1112 /// frame. 1113 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer, 1114 ArrayRef<MCCFIInstruction> Instrs, 1115 MCSymbol *BaseLabel) { 1116 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) { 1117 const MCCFIInstruction &Instr = Instrs[i]; 1118 MCSymbol *Label = Instr.getLabel(); 1119 // Throw out move if the label is invalid. 1120 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. 1121 1122 // Advance row if new location. 1123 if (BaseLabel && Label) { 1124 MCSymbol *ThisSym = Label; 1125 if (ThisSym != BaseLabel) { 1126 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4"); 1127 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); 1128 BaseLabel = ThisSym; 1129 } 1130 } 1131 1132 EmitCFIInstruction(streamer, Instr); 1133 } 1134 } 1135 1136 /// EmitCompactUnwind - Emit the unwind information in a compact way. 1137 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer, 1138 const MCDwarfFrameInfo &Frame) { 1139 MCContext &Context = Streamer.getContext(); 1140 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1141 bool VerboseAsm = Streamer.isVerboseAsm(); 1142 1143 // range-start range-length compact-unwind-enc personality-func lsda 1144 // _foo LfooEnd-_foo 0x00000023 0 0 1145 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 1146 // 1147 // .section __LD,__compact_unwind,regular,debug 1148 // 1149 // # compact unwind for _foo 1150 // .quad _foo 1151 // .set L1,LfooEnd-_foo 1152 // .long L1 1153 // .long 0x01010001 1154 // .quad 0 1155 // .quad 0 1156 // 1157 // # compact unwind for _bar 1158 // .quad _bar 1159 // .set L2,LbarEnd-_bar 1160 // .long L2 1161 // .long 0x01020011 1162 // .quad __gxx_personality 1163 // .quad except_tab1 1164 1165 uint32_t Encoding = Frame.CompactUnwindEncoding; 1166 if (!Encoding) return; 1167 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly()); 1168 1169 // The encoding needs to know we have an LSDA. 1170 if (!DwarfEHFrameOnly && Frame.Lsda) 1171 Encoding |= 0x40000000; 1172 1173 // Range Start 1174 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI); 1175 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); 1176 if (VerboseAsm) Streamer.AddComment("Range Start"); 1177 Streamer.EmitSymbolValue(Frame.Function, Size); 1178 1179 // Range Length 1180 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin, 1181 *Frame.End, 0); 1182 if (VerboseAsm) Streamer.AddComment("Range Length"); 1183 Streamer.EmitAbsValue(Range, 4); 1184 1185 // Compact Encoding 1186 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); 1187 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" + 1188 Twine::utohexstr(Encoding)); 1189 Streamer.EmitIntValue(Encoding, Size); 1190 1191 // Personality Function 1192 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); 1193 if (VerboseAsm) Streamer.AddComment("Personality Function"); 1194 if (!DwarfEHFrameOnly && Frame.Personality) 1195 Streamer.EmitSymbolValue(Frame.Personality, Size); 1196 else 1197 Streamer.EmitIntValue(0, Size); // No personality fn 1198 1199 // LSDA 1200 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); 1201 if (VerboseAsm) Streamer.AddComment("LSDA"); 1202 if (!DwarfEHFrameOnly && Frame.Lsda) 1203 Streamer.EmitSymbolValue(Frame.Lsda, Size); 1204 else 1205 Streamer.EmitIntValue(0, Size); // No LSDA 1206 } 1207 1208 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer, 1209 const MCSymbol *personality, 1210 unsigned personalityEncoding, 1211 const MCSymbol *lsda, 1212 bool IsSignalFrame, 1213 unsigned lsdaEncoding, 1214 bool IsSimple) { 1215 MCContext &context = streamer.getContext(); 1216 const MCRegisterInfo *MRI = context.getRegisterInfo(); 1217 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1218 bool verboseAsm = streamer.isVerboseAsm(); 1219 1220 MCSymbol *sectionStart; 1221 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH) 1222 sectionStart = context.CreateTempSymbol(); 1223 else 1224 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum)); 1225 1226 streamer.EmitLabel(sectionStart); 1227 CIENum++; 1228 1229 MCSymbol *sectionEnd = context.CreateTempSymbol(); 1230 1231 // Length 1232 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart, 1233 *sectionEnd, 4); 1234 if (verboseAsm) streamer.AddComment("CIE Length"); 1235 streamer.EmitAbsValue(Length, 4); 1236 1237 // CIE ID 1238 unsigned CIE_ID = IsEH ? 0 : -1; 1239 if (verboseAsm) streamer.AddComment("CIE ID Tag"); 1240 streamer.EmitIntValue(CIE_ID, 4); 1241 1242 // Version 1243 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION"); 1244 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1); 1245 1246 // Augmentation String 1247 SmallString<8> Augmentation; 1248 if (IsEH) { 1249 if (verboseAsm) streamer.AddComment("CIE Augmentation"); 1250 Augmentation += "z"; 1251 if (personality) 1252 Augmentation += "P"; 1253 if (lsda) 1254 Augmentation += "L"; 1255 Augmentation += "R"; 1256 if (IsSignalFrame) 1257 Augmentation += "S"; 1258 streamer.EmitBytes(Augmentation.str()); 1259 } 1260 streamer.EmitIntValue(0, 1); 1261 1262 // Code Alignment Factor 1263 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor"); 1264 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment()); 1265 1266 // Data Alignment Factor 1267 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor"); 1268 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer)); 1269 1270 // Return Address Register 1271 if (verboseAsm) streamer.AddComment("CIE Return Address Column"); 1272 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true)); 1273 1274 // Augmentation Data Length (optional) 1275 1276 unsigned augmentationLength = 0; 1277 if (IsEH) { 1278 if (personality) { 1279 // Personality Encoding 1280 augmentationLength += 1; 1281 // Personality 1282 augmentationLength += getSizeForEncoding(streamer, personalityEncoding); 1283 } 1284 if (lsda) 1285 augmentationLength += 1; 1286 // Encoding of the FDE pointers 1287 augmentationLength += 1; 1288 1289 if (verboseAsm) streamer.AddComment("Augmentation Size"); 1290 streamer.EmitULEB128IntValue(augmentationLength); 1291 1292 // Augmentation Data (optional) 1293 if (personality) { 1294 // Personality Encoding 1295 EmitEncodingByte(streamer, personalityEncoding, 1296 "Personality Encoding"); 1297 // Personality 1298 if (verboseAsm) streamer.AddComment("Personality"); 1299 EmitPersonality(streamer, *personality, personalityEncoding); 1300 } 1301 1302 if (lsda) 1303 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding"); 1304 1305 // Encoding of the FDE pointers 1306 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI), 1307 "FDE Encoding"); 1308 } 1309 1310 // Initial Instructions 1311 1312 const MCAsmInfo *MAI = context.getAsmInfo(); 1313 if (!IsSimple) { 1314 const std::vector<MCCFIInstruction> &Instructions = 1315 MAI->getInitialFrameState(); 1316 EmitCFIInstructions(streamer, Instructions, NULL); 1317 } 1318 1319 // Padding 1320 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize()); 1321 1322 streamer.EmitLabel(sectionEnd); 1323 return *sectionStart; 1324 } 1325 1326 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer, 1327 const MCSymbol &cieStart, 1328 const MCDwarfFrameInfo &frame) { 1329 MCContext &context = streamer.getContext(); 1330 MCSymbol *fdeStart = context.CreateTempSymbol(); 1331 MCSymbol *fdeEnd = context.CreateTempSymbol(); 1332 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1333 bool verboseAsm = streamer.isVerboseAsm(); 1334 1335 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) { 1336 MCSymbol *EHSym = 1337 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh")); 1338 streamer.EmitEHSymAttributes(frame.Function, EHSym); 1339 streamer.EmitLabel(EHSym); 1340 } 1341 1342 // Length 1343 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0); 1344 if (verboseAsm) streamer.AddComment("FDE Length"); 1345 streamer.EmitAbsValue(Length, 4); 1346 1347 streamer.EmitLabel(fdeStart); 1348 1349 // CIE Pointer 1350 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1351 if (IsEH) { 1352 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart, 1353 0); 1354 if (verboseAsm) streamer.AddComment("FDE CIE Offset"); 1355 streamer.EmitAbsValue(offset, 4); 1356 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) { 1357 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart, 1358 cieStart, 0); 1359 streamer.EmitAbsValue(offset, 4); 1360 } else { 1361 streamer.EmitSymbolValue(&cieStart, 4); 1362 } 1363 1364 // PC Begin 1365 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI) 1366 : (unsigned)dwarf::DW_EH_PE_absptr; 1367 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding); 1368 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location"); 1369 1370 // PC Range 1371 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin, 1372 *frame.End, 0); 1373 if (verboseAsm) streamer.AddComment("FDE address range"); 1374 streamer.EmitAbsValue(Range, PCSize); 1375 1376 if (IsEH) { 1377 // Augmentation Data Length 1378 unsigned augmentationLength = 0; 1379 1380 if (frame.Lsda) 1381 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding); 1382 1383 if (verboseAsm) streamer.AddComment("Augmentation size"); 1384 streamer.EmitULEB128IntValue(augmentationLength); 1385 1386 // Augmentation Data 1387 if (frame.Lsda) 1388 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true, 1389 "Language Specific Data Area"); 1390 } 1391 1392 // Call Frame Instructions 1393 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin); 1394 1395 // Padding 1396 streamer.EmitValueToAlignment(PCSize); 1397 1398 return fdeEnd; 1399 } 1400 1401 namespace { 1402 struct CIEKey { 1403 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); } 1404 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); } 1405 1406 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_, 1407 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) : 1408 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_), 1409 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_), 1410 IsSimple(IsSimple_) { 1411 } 1412 const MCSymbol* Personality; 1413 unsigned PersonalityEncoding; 1414 unsigned LsdaEncoding; 1415 bool IsSignalFrame; 1416 bool IsSimple; 1417 }; 1418 } 1419 1420 namespace llvm { 1421 template <> 1422 struct DenseMapInfo<CIEKey> { 1423 static CIEKey getEmptyKey() { 1424 return CIEKey::getEmptyKey(); 1425 } 1426 static CIEKey getTombstoneKey() { 1427 return CIEKey::getTombstoneKey(); 1428 } 1429 static unsigned getHashValue(const CIEKey &Key) { 1430 return static_cast<unsigned>(hash_combine(Key.Personality, 1431 Key.PersonalityEncoding, 1432 Key.LsdaEncoding, 1433 Key.IsSignalFrame, 1434 Key.IsSimple)); 1435 } 1436 static bool isEqual(const CIEKey &LHS, 1437 const CIEKey &RHS) { 1438 return LHS.Personality == RHS.Personality && 1439 LHS.PersonalityEncoding == RHS.PersonalityEncoding && 1440 LHS.LsdaEncoding == RHS.LsdaEncoding && 1441 LHS.IsSignalFrame == RHS.IsSignalFrame && 1442 LHS.IsSimple == RHS.IsSimple; 1443 } 1444 }; 1445 } 1446 1447 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB, 1448 bool UsingCFI, bool IsEH) { 1449 Streamer.generateCompactUnwindEncodings(MAB); 1450 1451 MCContext &Context = Streamer.getContext(); 1452 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1453 FrameEmitterImpl Emitter(UsingCFI, IsEH); 1454 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos(); 1455 1456 // Emit the compact unwind info if available. 1457 if (IsEH && MOFI->getCompactUnwindSection()) { 1458 bool SectionEmitted = false; 1459 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) { 1460 const MCDwarfFrameInfo &Frame = FrameArray[i]; 1461 if (Frame.CompactUnwindEncoding == 0) continue; 1462 if (!SectionEmitted) { 1463 Streamer.SwitchSection(MOFI->getCompactUnwindSection()); 1464 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize()); 1465 SectionEmitted = true; 1466 } 1467 Emitter.EmitCompactUnwind(Streamer, Frame); 1468 } 1469 } 1470 1471 const MCSection &Section = 1472 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() : 1473 *MOFI->getDwarfFrameSection(); 1474 Streamer.SwitchSection(&Section); 1475 MCSymbol *SectionStart = Context.CreateTempSymbol(); 1476 Streamer.EmitLabel(SectionStart); 1477 Emitter.setSectionStart(SectionStart); 1478 1479 MCSymbol *FDEEnd = NULL; 1480 DenseMap<CIEKey, const MCSymbol*> CIEStarts; 1481 1482 const MCSymbol *DummyDebugKey = NULL; 1483 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) { 1484 const MCDwarfFrameInfo &Frame = FrameArray[i]; 1485 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding, 1486 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple); 1487 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; 1488 if (!CIEStart) 1489 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality, 1490 Frame.PersonalityEncoding, Frame.Lsda, 1491 Frame.IsSignalFrame, 1492 Frame.LsdaEncoding, 1493 Frame.IsSimple); 1494 1495 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame); 1496 1497 if (i != n - 1) 1498 Streamer.EmitLabel(FDEEnd); 1499 } 1500 1501 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize()); 1502 if (FDEEnd) 1503 Streamer.EmitLabel(FDEEnd); 1504 } 1505 1506 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer, 1507 uint64_t AddrDelta) { 1508 MCContext &Context = Streamer.getContext(); 1509 SmallString<256> Tmp; 1510 raw_svector_ostream OS(Tmp); 1511 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS); 1512 Streamer.EmitBytes(OS.str()); 1513 } 1514 1515 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context, 1516 uint64_t AddrDelta, 1517 raw_ostream &OS) { 1518 // Scale the address delta by the minimum instruction length. 1519 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 1520 1521 if (AddrDelta == 0) { 1522 } else if (isUIntN(6, AddrDelta)) { 1523 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; 1524 OS << Opcode; 1525 } else if (isUInt<8>(AddrDelta)) { 1526 OS << uint8_t(dwarf::DW_CFA_advance_loc1); 1527 OS << uint8_t(AddrDelta); 1528 } else if (isUInt<16>(AddrDelta)) { 1529 // FIXME: check what is the correct behavior on a big endian machine. 1530 OS << uint8_t(dwarf::DW_CFA_advance_loc2); 1531 OS << uint8_t( AddrDelta & 0xff); 1532 OS << uint8_t((AddrDelta >> 8) & 0xff); 1533 } else { 1534 // FIXME: check what is the correct behavior on a big endian machine. 1535 assert(isUInt<32>(AddrDelta)); 1536 OS << uint8_t(dwarf::DW_CFA_advance_loc4); 1537 OS << uint8_t( AddrDelta & 0xff); 1538 OS << uint8_t((AddrDelta >> 8) & 0xff); 1539 OS << uint8_t((AddrDelta >> 16) & 0xff); 1540 OS << uint8_t((AddrDelta >> 24) & 0xff); 1541 1542 } 1543 } 1544