1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/FoldingSet.h"
11 #include "llvm/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCDwarf.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCStreamer.h"
15 #include "llvm/MC/MCSymbol.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetAsmBackend.h"
25 #include "llvm/Target/TargetAsmInfo.h"
28 // Given a special op, return the address skip amount (in units of
29 // DWARF2_LINE_MIN_INSN_LENGTH.
30 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
32 // The maximum address skip amount that can be encoded with a special op.
33 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
35 // First special line opcode - leave room for the standard opcodes.
36 // Note: If you want to change this, you'll have to update the
37 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
38 #define DWARF2_LINE_OPCODE_BASE 13
40 // Minimum line offset in a special line info. opcode. This value
41 // was chosen to give a reasonable range of values.
42 #define DWARF2_LINE_BASE -5
44 // Range of line offsets in a special line info. opcode.
45 # define DWARF2_LINE_RANGE 14
47 // Define the architecture-dependent minimum instruction length (in bytes).
48 // This value should be rather too small than too big.
49 # define DWARF2_LINE_MIN_INSN_LENGTH 1
51 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
52 // this routine is a nop and will be optimized away.
53 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
54 if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
56 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
57 // TODO: report this error, but really only once.
60 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
64 // This is called when an instruction is assembled into the specified section
65 // and if there is information from the last .loc directive that has yet to have
66 // a line entry made for it is made.
68 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
69 if (!MCOS->getContext().getDwarfLocSeen())
72 // Create a symbol at in the current section for use in the line entry.
73 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
74 // Set the value of the symbol to use for the MCLineEntry.
75 MCOS->EmitLabel(LineSym);
77 // Get the current .loc info saved in the context.
78 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
80 // Create a (local) line entry with the symbol and the current .loc info.
81 MCLineEntry LineEntry(LineSym, DwarfLoc);
83 // clear DwarfLocSeen saying the current .loc info is now used.
84 MCOS->getContext().ClearDwarfLocSeen();
86 // Get the MCLineSection for this section, if one does not exist for this
88 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
89 MCOS->getContext().getMCLineSections();
90 MCLineSection *LineSection = MCLineSections.lookup(Section);
92 // Create a new MCLineSection. This will be deleted after the dwarf line
93 // table is created using it by iterating through the MCLineSections
95 LineSection = new MCLineSection;
96 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
97 MCOS->getContext().addMCLineSection(Section, LineSection);
100 // Add the line entry to this section's entries.
101 LineSection->addLineEntry(LineEntry);
105 // This helper routine returns an expression of End - Start + IntVal .
107 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
108 const MCSymbol &Start,
111 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
113 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
115 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
117 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
119 MCConstantExpr::Create(IntVal, MCOS.getContext());
121 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
126 // This emits the Dwarf line table for the specified section from the entries
127 // in the LineSection.
129 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
130 const MCSection *Section,
131 const MCLineSection *LineSection) {
132 unsigned FileNum = 1;
133 unsigned LastLine = 1;
135 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
137 MCSymbol *LastLabel = NULL;
139 // Loop through each MCLineEntry and encode the dwarf line number table.
140 for (MCLineSection::const_iterator
141 it = LineSection->getMCLineEntries()->begin(),
142 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
144 if (FileNum != it->getFileNum()) {
145 FileNum = it->getFileNum();
146 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
147 MCOS->EmitULEB128IntValue(FileNum);
149 if (Column != it->getColumn()) {
150 Column = it->getColumn();
151 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
152 MCOS->EmitULEB128IntValue(Column);
154 if (Isa != it->getIsa()) {
156 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
157 MCOS->EmitULEB128IntValue(Isa);
159 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
160 Flags = it->getFlags();
161 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
163 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
164 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
165 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
166 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
167 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
168 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
170 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
171 MCSymbol *Label = it->getLabel();
173 // At this point we want to emit/create the sequence to encode the delta in
174 // line numbers and the increment of the address from the previous Label
175 // and the current Label.
176 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label);
178 LastLine = it->getLine();
182 // Emit a DW_LNE_end_sequence for the end of the section.
183 // Using the pointer Section create a temporary label at the end of the
184 // section and use that and the LastLabel to compute the address delta
185 // and use INT64_MAX as the line delta which is the signal that this is
186 // actually a DW_LNE_end_sequence.
188 // Switch to the section to be able to create a symbol at its end.
189 MCOS->SwitchSection(Section);
191 MCContext &context = MCOS->getContext();
192 // Create a symbol at the end of the section.
193 MCSymbol *SectionEnd = context.CreateTempSymbol();
194 // Set the value of the symbol, as we are at the end of the section.
195 MCOS->EmitLabel(SectionEnd);
197 // Switch back the the dwarf line section.
198 MCOS->SwitchSection(context.getTargetAsmInfo().getDwarfLineSection());
200 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd);
204 // This emits the Dwarf file and the line tables.
206 void MCDwarfFileTable::Emit(MCStreamer *MCOS) {
207 MCContext &context = MCOS->getContext();
208 // Switch to the section where the table will be emitted into.
209 MCOS->SwitchSection(context.getTargetAsmInfo().getDwarfLineSection());
211 // Create a symbol at the beginning of this section.
212 MCSymbol *LineStartSym = context.CreateTempSymbol();
213 // Set the value of the symbol, as we are at the start of the section.
214 MCOS->EmitLabel(LineStartSym);
216 // Create a symbol for the end of the section (to be set when we get there).
217 MCSymbol *LineEndSym = context.CreateTempSymbol();
219 // The first 4 bytes is the total length of the information for this
220 // compilation unit (not including these 4 bytes for the length).
221 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
224 // Next 2 bytes is the Version, which is Dwarf 2.
225 MCOS->EmitIntValue(2, 2);
227 // Create a symbol for the end of the prologue (to be set when we get there).
228 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
230 // Length of the prologue, is the next 4 bytes. Which is the start of the
231 // section to the end of the prologue. Not including the 4 bytes for the
232 // total length, the 2 bytes for the version, and these 4 bytes for the
233 // length of the prologue.
234 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
238 // Parameters of the state machine, are next.
239 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
240 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
241 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
242 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
243 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
245 // Standard opcode lengths
246 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
247 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
248 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
249 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
250 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
251 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
252 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
253 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
254 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
255 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
256 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
257 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
259 // Put out the directory and file tables.
261 // First the directory table.
262 const std::vector<StringRef> &MCDwarfDirs =
263 context.getMCDwarfDirs();
264 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
265 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
266 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
268 MCOS->EmitIntValue(0, 1); // Terminate the directory list
270 // Second the file table.
271 const std::vector<MCDwarfFile *> &MCDwarfFiles =
272 MCOS->getContext().getMCDwarfFiles();
273 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
274 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
275 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
277 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
278 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
279 MCOS->EmitIntValue(0, 1); // filesize (always 0)
281 MCOS->EmitIntValue(0, 1); // Terminate the file list
283 // This is the end of the prologue, so set the value of the symbol at the
284 // end of the prologue (that was used in a previous expression).
285 MCOS->EmitLabel(ProEndSym);
287 // Put out the line tables.
288 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
289 MCOS->getContext().getMCLineSections();
290 const std::vector<const MCSection *> &MCLineSectionOrder =
291 MCOS->getContext().getMCLineSectionOrder();
292 for (std::vector<const MCSection*>::const_iterator it =
293 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
295 const MCSection *Sec = *it;
296 const MCLineSection *Line = MCLineSections.lookup(Sec);
297 EmitDwarfLineTable(MCOS, Sec, Line);
299 // Now delete the MCLineSections that were created in MCLineEntry::Make()
300 // and used to emit the line table.
304 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
305 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
306 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
308 // total_length >= prologue_length + 10
309 // We are 4 bytes short, since we have total_length = 51 and
310 // prologue_length = 45
312 // The regular end_sequence should be sufficient.
313 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
316 // This is the end of the section, so set the value of the symbol at the end
317 // of this section (that was used in a previous expression).
318 MCOS->EmitLabel(LineEndSym);
321 /// Utility function to write the encoding to an object writer.
322 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
323 uint64_t AddrDelta) {
324 SmallString<256> Tmp;
325 raw_svector_ostream OS(Tmp);
326 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
327 OW->WriteBytes(OS.str());
330 /// Utility function to emit the encoding to a streamer.
331 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
332 uint64_t AddrDelta) {
333 SmallString<256> Tmp;
334 raw_svector_ostream OS(Tmp);
335 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
336 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
339 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
340 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
342 uint64_t Temp, Opcode;
343 bool NeedCopy = false;
345 // Scale the address delta by the minimum instruction length.
346 AddrDelta = ScaleAddrDelta(AddrDelta);
348 // A LineDelta of INT64_MAX is a signal that this is actually a
349 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
350 // end_sequence to emit the matrix entry.
351 if (LineDelta == INT64_MAX) {
352 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
353 OS << char(dwarf::DW_LNS_const_add_pc);
355 OS << char(dwarf::DW_LNS_advance_pc);
356 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
358 OS << char(dwarf::DW_LNS_extended_op);
360 OS << char(dwarf::DW_LNE_end_sequence);
364 // Bias the line delta by the base.
365 Temp = LineDelta - DWARF2_LINE_BASE;
367 // If the line increment is out of range of a special opcode, we must encode
368 // it with DW_LNS_advance_line.
369 if (Temp >= DWARF2_LINE_RANGE) {
370 OS << char(dwarf::DW_LNS_advance_line);
372 raw_svector_ostream OSE(Tmp);
373 MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
377 Temp = 0 - DWARF2_LINE_BASE;
381 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
382 if (LineDelta == 0 && AddrDelta == 0) {
383 OS << char(dwarf::DW_LNS_copy);
387 // Bias the opcode by the special opcode base.
388 Temp += DWARF2_LINE_OPCODE_BASE;
390 // Avoid overflow when addr_delta is large.
391 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
392 // Try using a special opcode.
393 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
399 // Try using DW_LNS_const_add_pc followed by special op.
400 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
402 OS << char(dwarf::DW_LNS_const_add_pc);
408 // Otherwise use DW_LNS_advance_pc.
409 OS << char(dwarf::DW_LNS_advance_pc);
411 raw_svector_ostream OSE(Tmp);
412 MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
416 OS << char(dwarf::DW_LNS_copy);
421 void MCDwarfFile::print(raw_ostream &OS) const {
422 OS << '"' << getName() << '"';
425 void MCDwarfFile::dump() const {
429 static int getDataAlignmentFactor(MCStreamer &streamer) {
430 MCContext &context = streamer.getContext();
431 const TargetAsmInfo &asmInfo = context.getTargetAsmInfo();
432 int size = asmInfo.getPointerSize();
433 if (asmInfo.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
439 static unsigned getSizeForEncoding(MCStreamer &streamer,
440 unsigned symbolEncoding) {
441 MCContext &context = streamer.getContext();
442 const TargetAsmInfo &asmInfo = context.getTargetAsmInfo();
443 unsigned format = symbolEncoding & 0x0f;
446 assert(0 && "Unknown Encoding");
447 case dwarf::DW_EH_PE_absptr:
448 case dwarf::DW_EH_PE_signed:
449 return asmInfo.getPointerSize();
450 case dwarf::DW_EH_PE_udata2:
451 case dwarf::DW_EH_PE_sdata2:
453 case dwarf::DW_EH_PE_udata4:
454 case dwarf::DW_EH_PE_sdata4:
456 case dwarf::DW_EH_PE_udata8:
457 case dwarf::DW_EH_PE_sdata8:
462 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
463 unsigned symbolEncoding, const char *comment = 0) {
464 MCContext &context = streamer.getContext();
465 const MCAsmInfo &asmInfo = context.getAsmInfo();
466 const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
469 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
470 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
471 streamer.EmitAbsValue(v, size);
474 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
475 unsigned symbolEncoding) {
476 MCContext &context = streamer.getContext();
477 const MCAsmInfo &asmInfo = context.getAsmInfo();
478 const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
481 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
482 streamer.EmitValue(v, size);
485 static const MachineLocation TranslateMachineLocation(
486 const TargetAsmInfo &AsmInfo,
487 const MachineLocation &Loc) {
488 unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
489 MachineLocation::VirtualFP :
490 unsigned(AsmInfo.getDwarfRegNum(Loc.getReg(), true));
491 const MachineLocation &NewLoc = Loc.isReg() ?
492 MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
497 class FrameEmitterImpl {
502 const MCSymbol *SectionStart;
505 FrameEmitterImpl(bool usingCFI, bool isEH, const MCSymbol *sectionStart) :
506 CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
507 SectionStart(sectionStart) {
510 /// EmitCompactUnwind - Emit the unwind information in a compact way. If
511 /// we're successful, return 'true'. Otherwise, return 'false' and it will
512 /// emit the normal CIE and FDE.
513 bool EmitCompactUnwind(MCStreamer &streamer,
514 const MCDwarfFrameInfo &frame);
516 const MCSymbol &EmitCIE(MCStreamer &streamer,
517 const MCSymbol *personality,
518 unsigned personalityEncoding,
519 const MCSymbol *lsda,
520 unsigned lsdaEncoding);
521 MCSymbol *EmitFDE(MCStreamer &streamer,
522 const MCSymbol &cieStart,
523 const MCDwarfFrameInfo &frame);
524 void EmitCFIInstructions(MCStreamer &streamer,
525 const std::vector<MCCFIInstruction> &Instrs,
526 MCSymbol *BaseLabel);
527 void EmitCFIInstruction(MCStreamer &Streamer,
528 const MCCFIInstruction &Instr);
531 } // end anonymous namespace
533 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
535 if (Streamer.isVerboseAsm()) {
536 const char *EncStr = 0;
538 default: EncStr = "<unknown encoding>";
539 case dwarf::DW_EH_PE_absptr: EncStr = "absptr";
540 case dwarf::DW_EH_PE_omit: EncStr = "omit";
541 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel";
542 case dwarf::DW_EH_PE_udata4: EncStr = "udata4";
543 case dwarf::DW_EH_PE_udata8: EncStr = "udata8";
544 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4";
545 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8";
546 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: EncStr = "pcrel udata4";
547 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: EncStr = "pcrel sdata4";
548 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: EncStr = "pcrel udata8";
549 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: EncStr = "pcrel sdata8";
550 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
551 EncStr = "indirect pcrel udata4";
552 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
553 EncStr = "indirect pcrel sdata4";
554 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
555 EncStr = "indirect pcrel udata8";
556 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
557 EncStr = "indirect pcrel sdata8";
560 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
563 Streamer.EmitIntValue(Encoding, 1);
566 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
567 const MCCFIInstruction &Instr) {
568 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
569 bool VerboseAsm = Streamer.isVerboseAsm();
571 switch (Instr.getOperation()) {
572 case MCCFIInstruction::Move:
573 case MCCFIInstruction::RelMove: {
574 const MachineLocation &Dst = Instr.getDestination();
575 const MachineLocation &Src = Instr.getSource();
576 const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
579 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
580 if (Src.getReg() == MachineLocation::VirtualFP) {
581 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
582 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
584 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
585 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
586 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
587 Twine(Src.getReg()));
588 Streamer.EmitULEB128IntValue(Src.getReg());
592 CFAOffset += Src.getOffset();
594 CFAOffset = -Src.getOffset();
596 if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
597 Streamer.EmitULEB128IntValue(CFAOffset);
601 if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
602 assert(Dst.isReg() && "Machine move not supported yet.");
603 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
604 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
605 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
606 Streamer.EmitULEB128IntValue(Dst.getReg());
610 unsigned Reg = Src.getReg();
611 int Offset = Dst.getOffset();
614 Offset = Offset / dataAlignmentFactor;
617 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
618 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
619 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
620 Streamer.EmitULEB128IntValue(Reg);
621 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
622 Streamer.EmitSLEB128IntValue(Offset);
623 } else if (Reg < 64) {
624 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
626 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
627 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
628 Streamer.EmitULEB128IntValue(Offset);
630 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
631 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
632 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
633 Streamer.EmitULEB128IntValue(Reg);
634 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
635 Streamer.EmitULEB128IntValue(Offset);
639 case MCCFIInstruction::Remember:
640 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
641 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
643 case MCCFIInstruction::Restore:
644 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
645 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
647 case MCCFIInstruction::SameValue: {
648 unsigned Reg = Instr.getDestination().getReg();
649 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
650 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
651 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
652 Streamer.EmitULEB128IntValue(Reg);
656 llvm_unreachable("Unhandled case in switch");
659 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
661 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
662 const std::vector<MCCFIInstruction> &Instrs,
663 MCSymbol *BaseLabel) {
664 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
665 const MCCFIInstruction &Instr = Instrs[i];
666 MCSymbol *Label = Instr.getLabel();
667 // Throw out move if the label is invalid.
668 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
670 // Advance row if new location.
671 if (BaseLabel && Label) {
672 MCSymbol *ThisSym = Label;
673 if (ThisSym != BaseLabel) {
674 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
675 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
680 EmitCFIInstruction(streamer, Instr);
684 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
685 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
686 /// normal CIE and FDE.
687 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
688 const MCDwarfFrameInfo &Frame) {
692 MCContext &Context = Streamer.getContext();
693 const TargetAsmInfo &TAI = Context.getTargetAsmInfo();
694 bool VerboseAsm = Streamer.isVerboseAsm();
696 // range-start range-length compact-unwind-enc personality-func lsda
697 // _foo LfooEnd-_foo 0x00000023 0 0
698 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
700 // .section __LD,__compact_unwind,regular,debug
702 // # compact unwind for _foo
704 // .set L1,LfooEnd-_foo
710 // # compact unwind for _bar
712 // .set L2,LbarEnd-_bar
715 // .quad __gxx_personality
718 Streamer.SwitchSection(TAI.getCompactUnwindSection());
721 unsigned FDEEncoding = TAI.getFDEEncoding(UsingCFI);
722 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
723 if (VerboseAsm) Streamer.AddComment("Range Start");
724 Streamer.EmitSymbolValue(Frame.Function, Size);
727 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
729 if (VerboseAsm) Streamer.AddComment("Range Length");
730 Streamer.EmitAbsValue(Range, 4);
734 const std::vector<MachineMove> &Moves = TAI.getInitialFrameState();
735 uint32_t Encoding = 0;
736 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
737 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding");
738 Streamer.EmitIntValue(Encoding, Size);
740 // Personality Function
741 Size = getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
742 if (VerboseAsm) Streamer.AddComment("Personality Function");
743 if (Frame.Personality)
744 Streamer.EmitSymbolValue(Frame.Personality, Size);
746 Streamer.EmitIntValue(0, Size); // No personality fn
749 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
750 if (VerboseAsm) Streamer.AddComment("LSDA");
752 Streamer.EmitSymbolValue(Frame.Lsda, Size);
754 Streamer.EmitIntValue(0, Size); // No LSDA
760 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
761 const MCSymbol *personality,
762 unsigned personalityEncoding,
763 const MCSymbol *lsda,
764 unsigned lsdaEncoding) {
765 MCContext &context = streamer.getContext();
766 const TargetAsmInfo &asmInfo = context.getTargetAsmInfo();
767 bool verboseAsm = streamer.isVerboseAsm();
769 MCSymbol *sectionStart;
770 if (asmInfo.isFunctionEHFrameSymbolPrivate() || !IsEH)
771 sectionStart = context.CreateTempSymbol();
773 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
775 streamer.EmitLabel(sectionStart);
778 MCSymbol *sectionEnd = streamer.getContext().CreateTempSymbol();
781 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
783 if (verboseAsm) streamer.AddComment("CIE Length");
784 streamer.EmitAbsValue(Length, 4);
787 unsigned CIE_ID = IsEH ? 0 : -1;
788 if (verboseAsm) streamer.AddComment("CIE ID Tag");
789 streamer.EmitIntValue(CIE_ID, 4);
792 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
793 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
795 // Augmentation String
796 SmallString<8> Augmentation;
798 if (verboseAsm) streamer.AddComment("CIE Augmentation");
805 streamer.EmitBytes(Augmentation.str(), 0);
807 streamer.EmitIntValue(0, 1);
809 // Code Alignment Factor
810 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
811 streamer.EmitULEB128IntValue(1);
813 // Data Alignment Factor
814 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
815 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
817 // Return Address Register
818 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
819 streamer.EmitULEB128IntValue(asmInfo.getDwarfRARegNum(true));
821 // Augmentation Data Length (optional)
823 unsigned augmentationLength = 0;
826 // Personality Encoding
827 augmentationLength += 1;
829 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
832 augmentationLength += 1;
833 // Encoding of the FDE pointers
834 augmentationLength += 1;
836 if (verboseAsm) streamer.AddComment("Augmentation Size");
837 streamer.EmitULEB128IntValue(augmentationLength);
839 // Augmentation Data (optional)
841 // Personality Encoding
842 EmitEncodingByte(streamer, personalityEncoding,
843 "Personality Encoding");
845 if (verboseAsm) streamer.AddComment("Personality");
846 EmitPersonality(streamer, *personality, personalityEncoding);
850 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
852 // Encoding of the FDE pointers
853 EmitEncodingByte(streamer, asmInfo.getFDEEncoding(UsingCFI),
857 // Initial Instructions
859 const std::vector<MachineMove> &Moves = asmInfo.getInitialFrameState();
860 std::vector<MCCFIInstruction> Instructions;
862 for (int i = 0, n = Moves.size(); i != n; ++i) {
863 MCSymbol *Label = Moves[i].getLabel();
864 const MachineLocation &Dst =
865 TranslateMachineLocation(asmInfo, Moves[i].getDestination());
866 const MachineLocation &Src =
867 TranslateMachineLocation(asmInfo, Moves[i].getSource());
868 MCCFIInstruction Inst(Label, Dst, Src);
869 Instructions.push_back(Inst);
872 EmitCFIInstructions(streamer, Instructions, NULL);
875 streamer.EmitValueToAlignment(IsEH ? 4 : asmInfo.getPointerSize());
877 streamer.EmitLabel(sectionEnd);
878 return *sectionStart;
881 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
882 const MCSymbol &cieStart,
883 const MCDwarfFrameInfo &frame) {
884 MCContext &context = streamer.getContext();
885 MCSymbol *fdeStart = context.CreateTempSymbol();
886 MCSymbol *fdeEnd = context.CreateTempSymbol();
887 const TargetAsmInfo &TAsmInfo = context.getTargetAsmInfo();
888 bool verboseAsm = streamer.isVerboseAsm();
890 if (!TAsmInfo.isFunctionEHFrameSymbolPrivate() && IsEH) {
892 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
893 streamer.EmitEHSymAttributes(frame.Function, EHSym);
894 streamer.EmitLabel(EHSym);
898 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
899 if (verboseAsm) streamer.AddComment("FDE Length");
900 streamer.EmitAbsValue(Length, 4);
902 streamer.EmitLabel(fdeStart);
905 const MCAsmInfo &asmInfo = context.getAsmInfo();
907 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
909 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
910 streamer.EmitAbsValue(offset, 4);
911 } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
912 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
914 streamer.EmitAbsValue(offset, 4);
916 streamer.EmitSymbolValue(&cieStart, 4);
919 unsigned fdeEncoding = TAsmInfo.getFDEEncoding(UsingCFI);
920 unsigned size = getSizeForEncoding(streamer, fdeEncoding);
923 unsigned PCBeginEncoding = IsEH ? fdeEncoding :
924 (unsigned)dwarf::DW_EH_PE_absptr;
925 unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
926 EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
929 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
931 if (verboseAsm) streamer.AddComment("FDE address range");
932 streamer.EmitAbsValue(Range, size);
935 // Augmentation Data Length
936 unsigned augmentationLength = 0;
939 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
941 if (verboseAsm) streamer.AddComment("Augmentation size");
942 streamer.EmitULEB128IntValue(augmentationLength);
946 EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
947 "Language Specific Data Area");
950 // Call Frame Instructions
952 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
955 streamer.EmitValueToAlignment(PCBeginSize);
962 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
963 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
965 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
966 unsigned LsdaEncoding_) : Personality(Personality_),
967 PersonalityEncoding(PersonalityEncoding_),
968 LsdaEncoding(LsdaEncoding_) {
970 const MCSymbol* Personality;
971 unsigned PersonalityEncoding;
972 unsigned LsdaEncoding;
978 struct DenseMapInfo<CIEKey> {
979 static CIEKey getEmptyKey() {
980 return CIEKey::getEmptyKey();
982 static CIEKey getTombstoneKey() {
983 return CIEKey::getTombstoneKey();
985 static unsigned getHashValue(const CIEKey &Key) {
987 ID.AddPointer(Key.Personality);
988 ID.AddInteger(Key.PersonalityEncoding);
989 ID.AddInteger(Key.LsdaEncoding);
990 return ID.ComputeHash();
992 static bool isEqual(const CIEKey &LHS,
994 return LHS.Personality == RHS.Personality &&
995 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
996 LHS.LsdaEncoding == RHS.LsdaEncoding;
1001 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
1004 MCContext &Context = Streamer.getContext();
1005 const TargetAsmInfo &AsmInfo = Context.getTargetAsmInfo();
1006 const MCSection &Section = IsEH ? *AsmInfo.getEHFrameSection() :
1007 *AsmInfo.getDwarfFrameSection();
1008 Streamer.SwitchSection(&Section);
1009 MCSymbol *SectionStart = Context.CreateTempSymbol();
1010 Streamer.EmitLabel(SectionStart);
1012 MCSymbol *FDEEnd = NULL;
1013 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1014 FrameEmitterImpl Emitter(UsingCFI, IsEH, SectionStart);
1016 const MCSymbol *DummyDebugKey = NULL;
1017 for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
1018 const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
1019 if (IsEH && AsmInfo.getCompactUnwindSection() &&
1020 Emitter.EmitCompactUnwind(Streamer, Frame))
1023 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1024 Frame.LsdaEncoding);
1025 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1027 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1028 Frame.PersonalityEncoding, Frame.Lsda,
1029 Frame.LsdaEncoding);
1031 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1034 Streamer.EmitLabel(FDEEnd);
1037 Streamer.EmitValueToAlignment(AsmInfo.getPointerSize());
1039 Streamer.EmitLabel(FDEEnd);
1042 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1043 uint64_t AddrDelta) {
1044 SmallString<256> Tmp;
1045 raw_svector_ostream OS(Tmp);
1046 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
1047 Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
1050 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
1052 // FIXME: Assumes the code alignment factor is 1.
1053 if (AddrDelta == 0) {
1054 } else if (isUIntN(6, AddrDelta)) {
1055 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1057 } else if (isUInt<8>(AddrDelta)) {
1058 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1059 OS << uint8_t(AddrDelta);
1060 } else if (isUInt<16>(AddrDelta)) {
1061 // FIXME: check what is the correct behavior on a big endian machine.
1062 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1063 OS << uint8_t( AddrDelta & 0xff);
1064 OS << uint8_t((AddrDelta >> 8) & 0xff);
1066 // FIXME: check what is the correct behavior on a big endian machine.
1067 assert(isUInt<32>(AddrDelta));
1068 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1069 OS << uint8_t( AddrDelta & 0xff);
1070 OS << uint8_t((AddrDelta >> 8) & 0xff);
1071 OS << uint8_t((AddrDelta >> 16) & 0xff);
1072 OS << uint8_t((AddrDelta >> 24) & 0xff);