Second try at making direct object emission produce the same results
[llvm.git] / lib / MC / MCDwarf.cpp
blob3e10f9502dbe8dd47b5126d27eea2f962038e398
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 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCAsmInfo.h"
11 #include "llvm/MC/MCDwarf.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCStreamer.h"
14 #include "llvm/MC/MCSymbol.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Target/TargetAsmBackend.h"
22 using namespace llvm;
24 // Given a special op, return the address skip amount (in units of
25 // DWARF2_LINE_MIN_INSN_LENGTH.
26 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
28 // The maximum address skip amount that can be encoded with a special op.
29 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
31 // First special line opcode - leave room for the standard opcodes.
32 // Note: If you want to change this, you'll have to update the
33 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
34 #define DWARF2_LINE_OPCODE_BASE 13
36 // Minimum line offset in a special line info. opcode. This value
37 // was chosen to give a reasonable range of values.
38 #define DWARF2_LINE_BASE -5
40 // Range of line offsets in a special line info. opcode.
41 # define DWARF2_LINE_RANGE 14
43 // Define the architecture-dependent minimum instruction length (in bytes).
44 // This value should be rather too small than too big.
45 # define DWARF2_LINE_MIN_INSN_LENGTH 1
47 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
48 // this routine is a nop and will be optimized away.
49 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta)
51 if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
52 return AddrDelta;
53 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
54 // TODO: report this error, but really only once.
57 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
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.
65 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
66 if (!MCOS->getContext().getDwarfLocSeen())
67 return;
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);
74 // Get the current .loc info saved in the context.
75 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
77 // Create a (local) line entry with the symbol and the current .loc info.
78 MCLineEntry LineEntry(LineSym, DwarfLoc);
80 // clear DwarfLocSeen saying the current .loc info is now used.
81 MCOS->getContext().ClearDwarfLocSeen();
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);
97 // Add the line entry to this section's entries.
98 LineSection->addLineEntry(LineEntry);
102 // This helper routine returns an expression of End - Start + IntVal .
104 static inline const MCExpr *MakeStartMinusEndExpr(MCStreamer *MCOS,
105 MCSymbol *Start,
106 MCSymbol *End, int IntVal) {
107 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
108 const MCExpr *Res =
109 MCSymbolRefExpr::Create(End, Variant, MCOS->getContext());
110 const MCExpr *RHS =
111 MCSymbolRefExpr::Create(Start, Variant, MCOS->getContext());
112 const MCExpr *Res1 =
113 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS->getContext());
114 const MCExpr *Res2 =
115 MCConstantExpr::Create(IntVal, MCOS->getContext());
116 const MCExpr *Res3 =
117 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS->getContext());
118 return Res3;
122 // This emits the Dwarf line table for the specified section from the entries
123 // in the LineSection.
125 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
126 const MCSection *Section,
127 const MCLineSection *LineSection,
128 const MCSection *DwarfLineSection) {
129 unsigned FileNum = 1;
130 unsigned LastLine = 1;
131 unsigned Column = 0;
132 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
133 unsigned Isa = 0;
134 MCSymbol *LastLabel = NULL;
136 // Loop through each MCLineEntry and encode the dwarf line number table.
137 for (MCLineSection::const_iterator
138 it = LineSection->getMCLineEntries()->begin(),
139 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
141 if (FileNum != it->getFileNum()) {
142 FileNum = it->getFileNum();
143 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
144 MCOS->EmitULEB128IntValue(FileNum);
146 if (Column != it->getColumn()) {
147 Column = it->getColumn();
148 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
149 MCOS->EmitULEB128IntValue(Column);
151 if (Isa != it->getIsa()) {
152 Isa = it->getIsa();
153 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
154 MCOS->EmitULEB128IntValue(Isa);
156 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
157 Flags = it->getFlags();
158 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
160 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
161 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
162 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
164 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
165 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
167 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
168 MCSymbol *Label = it->getLabel();
170 // At this point we want to emit/create the sequence to encode the delta in
171 // line numbers and the increment of the address from the previous Label
172 // and the current Label.
173 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label);
175 LastLine = it->getLine();
176 LastLabel = Label;
179 // Emit a DW_LNE_end_sequence for the end of the section.
180 // Using the pointer Section create a temporary label at the end of the
181 // section and use that and the LastLabel to compute the address delta
182 // and use INT64_MAX as the line delta which is the signal that this is
183 // actually a DW_LNE_end_sequence.
185 // Switch to the section to be able to create a symbol at its end.
186 MCOS->SwitchSection(Section);
187 // Create a symbol at the end of the section.
188 MCSymbol *SectionEnd = MCOS->getContext().CreateTempSymbol();
189 // Set the value of the symbol, as we are at the end of the section.
190 MCOS->EmitLabel(SectionEnd);
192 // Switch back the the dwarf line section.
193 MCOS->SwitchSection(DwarfLineSection);
195 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd);
199 // This emits the Dwarf file and the line tables.
201 void MCDwarfFileTable::Emit(MCStreamer *MCOS,
202 const MCSection *DwarfLineSection) {
203 // Switch to the section where the table will be emitted into.
204 MCOS->SwitchSection(DwarfLineSection);
206 // Create a symbol at the beginning of this section.
207 MCSymbol *LineStartSym = MCOS->getContext().CreateTempSymbol();
208 // Set the value of the symbol, as we are at the start of the section.
209 MCOS->EmitLabel(LineStartSym);
211 // Create a symbol for the end of the section (to be set when we get there).
212 MCSymbol *LineEndSym = MCOS->getContext().CreateTempSymbol();
214 // The first 4 bytes is the total length of the information for this
215 // compilation unit (not including these 4 bytes for the length).
216 MCOS->EmitAbsValue(MakeStartMinusEndExpr(MCOS, LineStartSym, LineEndSym,4),
219 // Next 2 bytes is the Version, which is Dwarf 2.
220 MCOS->EmitIntValue(2, 2);
222 // Create a symbol for the end of the prologue (to be set when we get there).
223 MCSymbol *ProEndSym = MCOS->getContext().CreateTempSymbol(); // Lprologue_end
225 // Length of the prologue, is the next 4 bytes. Which is the start of the
226 // section to the end of the prologue. Not including the 4 bytes for the
227 // total length, the 2 bytes for the version, and these 4 bytes for the
228 // length of the prologue.
229 MCOS->EmitAbsValue(MakeStartMinusEndExpr(MCOS, LineStartSym, ProEndSym,
230 (4 + 2 + 4)),
231 4, 0);
233 // Parameters of the state machine, are next.
234 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
235 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
236 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
237 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
238 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
240 // Standard opcode lengths
241 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
242 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
243 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
244 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
245 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
246 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
247 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
248 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
249 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
250 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
251 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
252 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
254 // Put out the directory and file tables.
256 // First the directory table.
257 const std::vector<StringRef> &MCDwarfDirs =
258 MCOS->getContext().getMCDwarfDirs();
259 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
260 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
261 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
263 MCOS->EmitIntValue(0, 1); // Terminate the directory list
265 // Second the file table.
266 const std::vector<MCDwarfFile *> &MCDwarfFiles =
267 MCOS->getContext().getMCDwarfFiles();
268 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
269 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
270 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
271 // the Directory num
272 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
273 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
274 MCOS->EmitIntValue(0, 1); // filesize (always 0)
276 MCOS->EmitIntValue(0, 1); // Terminate the file list
278 // This is the end of the prologue, so set the value of the symbol at the
279 // end of the prologue (that was used in a previous expression).
280 MCOS->EmitLabel(ProEndSym);
282 // Put out the line tables.
283 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
284 MCOS->getContext().getMCLineSections();
285 const std::vector<const MCSection *> &MCLineSectionOrder =
286 MCOS->getContext().getMCLineSectionOrder();
287 for (std::vector<const MCSection*>::const_iterator it =
288 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
289 ++it) {
290 const MCSection *Sec = *it;
291 const MCLineSection *Line = MCLineSections.lookup(Sec);
292 EmitDwarfLineTable(MCOS, Sec, Line, DwarfLineSection);
294 // Now delete the MCLineSections that were created in MCLineEntry::Make()
295 // and used to emit the line table.
296 delete Line;
299 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
300 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
301 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
302 // it requires:
303 // total_length >= prologue_length + 10
304 // We are 4 bytes short, since we have total_length = 51 and
305 // prologue_length = 45
307 // The regular end_sequence should be sufficient.
308 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
311 // This is the end of the section, so set the value of the symbol at the end
312 // of this section (that was used in a previous expression).
313 MCOS->EmitLabel(LineEndSym);
316 /// Utility function to write the encoding to an object writer.
317 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
318 uint64_t AddrDelta) {
319 SmallString<256> Tmp;
320 raw_svector_ostream OS(Tmp);
321 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
322 OW->WriteBytes(OS.str());
325 /// Utility function to emit the encoding to a streamer.
326 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
327 uint64_t AddrDelta) {
328 SmallString<256> Tmp;
329 raw_svector_ostream OS(Tmp);
330 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
331 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
334 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
335 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
336 raw_ostream &OS) {
337 uint64_t Temp, Opcode;
338 bool NeedCopy = false;
340 // Scale the address delta by the minimum instruction length.
341 AddrDelta = ScaleAddrDelta(AddrDelta);
343 // A LineDelta of INT64_MAX is a signal that this is actually a
344 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
345 // end_sequence to emit the matrix entry.
346 if (LineDelta == INT64_MAX) {
347 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
348 OS << char(dwarf::DW_LNS_const_add_pc);
349 else {
350 OS << char(dwarf::DW_LNS_advance_pc);
351 SmallString<32> Tmp;
352 raw_svector_ostream OSE(Tmp);
353 MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
354 OS << OSE.str();
356 OS << char(dwarf::DW_LNS_extended_op);
357 OS << char(1);
358 OS << char(dwarf::DW_LNE_end_sequence);
359 return;
362 // Bias the line delta by the base.
363 Temp = LineDelta - DWARF2_LINE_BASE;
365 // If the line increment is out of range of a special opcode, we must encode
366 // it with DW_LNS_advance_line.
367 if (Temp >= DWARF2_LINE_RANGE) {
368 OS << char(dwarf::DW_LNS_advance_line);
369 SmallString<32> Tmp;
370 raw_svector_ostream OSE(Tmp);
371 MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
372 OS << OSE.str();
374 LineDelta = 0;
375 Temp = 0 - DWARF2_LINE_BASE;
376 NeedCopy = true;
379 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
380 if (LineDelta == 0 && AddrDelta == 0) {
381 OS << char(dwarf::DW_LNS_copy);
382 return;
385 // Bias the opcode by the special opcode base.
386 Temp += DWARF2_LINE_OPCODE_BASE;
388 // Avoid overflow when addr_delta is large.
389 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
390 // Try using a special opcode.
391 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
392 if (Opcode <= 255) {
393 OS << char(Opcode);
394 return;
397 // Try using DW_LNS_const_add_pc followed by special op.
398 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
399 if (Opcode <= 255) {
400 OS << char(dwarf::DW_LNS_const_add_pc);
401 OS << char(Opcode);
402 return;
406 // Otherwise use DW_LNS_advance_pc.
407 OS << char(dwarf::DW_LNS_advance_pc);
408 SmallString<32> Tmp;
409 raw_svector_ostream OSE(Tmp);
410 MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
411 OS << OSE.str();
413 if (NeedCopy)
414 OS << char(dwarf::DW_LNS_copy);
415 else
416 OS << char(Temp);
419 void MCDwarfFile::print(raw_ostream &OS) const {
420 OS << '"' << getName() << '"';
423 void MCDwarfFile::dump() const {
424 print(dbgs());