Stupid error: If the LSDA and Personality functions aren't there, emit 0 instead
[oota-llvm.git] / lib / MC / MCDwarf.cpp
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/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"
26 using namespace llvm;
27
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)
31
32 // The maximum address skip amount that can be encoded with a special op.
33 #define MAX_SPECIAL_ADDR_DELTA          SPECIAL_ADDR(255)
34
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
39
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
43
44 // Range of line offsets in a special line info. opcode.
45 # define DWARF2_LINE_RANGE              14
46
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
50
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)
55     return AddrDelta;
56   if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
57     // TODO: report this error, but really only once.
58     ;
59   }
60   return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
61 }
62
63 //
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.
67 //
68 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
69   if (!MCOS->getContext().getDwarfLocSeen())
70     return;
71
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);
76
77   // Get the current .loc info saved in the context.
78   const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
79
80   // Create a (local) line entry with the symbol and the current .loc info.
81   MCLineEntry LineEntry(LineSym, DwarfLoc);
82
83   // clear DwarfLocSeen saying the current .loc info is now used.
84   MCOS->getContext().ClearDwarfLocSeen();
85
86   // Get the MCLineSection for this section, if one does not exist for this
87   // section create it.
88   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
89     MCOS->getContext().getMCLineSections();
90   MCLineSection *LineSection = MCLineSections.lookup(Section);
91   if (!LineSection) {
92     // Create a new MCLineSection.  This will be deleted after the dwarf line
93     // table is created using it by iterating through the MCLineSections
94     // DenseMap.
95     LineSection = new MCLineSection;
96     // Save a pointer to the new LineSection into the MCLineSections DenseMap.
97     MCOS->getContext().addMCLineSection(Section, LineSection);
98   }
99
100   // Add the line entry to this section's entries.
101   LineSection->addLineEntry(LineEntry);
102 }
103
104 //
105 // This helper routine returns an expression of End - Start + IntVal .
106 // 
107 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
108                                                   const MCSymbol &Start,
109                                                   const MCSymbol &End,
110                                                   int IntVal) {
111   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
112   const MCExpr *Res =
113     MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
114   const MCExpr *RHS =
115     MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
116   const MCExpr *Res1 =
117     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
118   const MCExpr *Res2 =
119     MCConstantExpr::Create(IntVal, MCOS.getContext());
120   const MCExpr *Res3 =
121     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
122   return Res3;
123 }
124
125 //
126 // This emits the Dwarf line table for the specified section from the entries
127 // in the LineSection.
128 //
129 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
130                                       const MCSection *Section,
131                                       const MCLineSection *LineSection) {
132   unsigned FileNum = 1;
133   unsigned LastLine = 1;
134   unsigned Column = 0;
135   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
136   unsigned Isa = 0;
137   MCSymbol *LastLabel = NULL;
138
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) {
143
144     if (FileNum != it->getFileNum()) {
145       FileNum = it->getFileNum();
146       MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
147       MCOS->EmitULEB128IntValue(FileNum);
148     }
149     if (Column != it->getColumn()) {
150       Column = it->getColumn();
151       MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
152       MCOS->EmitULEB128IntValue(Column);
153     }
154     if (Isa != it->getIsa()) {
155       Isa = it->getIsa();
156       MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
157       MCOS->EmitULEB128IntValue(Isa);
158     }
159     if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
160       Flags = it->getFlags();
161       MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
162     }
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);
169
170     int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
171     MCSymbol *Label = it->getLabel();
172
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);
177
178     LastLine = it->getLine();
179     LastLabel = Label;
180   }
181
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.
187
188   // Switch to the section to be able to create a symbol at its end.
189   MCOS->SwitchSection(Section);
190
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);
196
197   // Switch back the the dwarf line section.
198   MCOS->SwitchSection(context.getTargetAsmInfo().getDwarfLineSection());
199
200   MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd);
201 }
202
203 //
204 // This emits the Dwarf file and the line tables.
205 //
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());
210
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);
215
216   // Create a symbol for the end of the section (to be set when we get there).
217   MCSymbol *LineEndSym = context.CreateTempSymbol();
218
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),
222                      4);
223
224   // Next 2 bytes is the Version, which is Dwarf 2.
225   MCOS->EmitIntValue(2, 2);
226
227   // Create a symbol for the end of the prologue (to be set when we get there).
228   MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
229
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,
235                                         (4 + 2 + 4)),
236                   4, 0);
237
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);
244
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
258
259   // Put out the directory and file tables.
260
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
267   }
268   MCOS->EmitIntValue(0, 1); // Terminate the directory list
269
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
276     // the Directory num
277     MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
278     MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
279     MCOS->EmitIntValue(0, 1); // filesize (always 0)
280   }
281   MCOS->EmitIntValue(0, 1); // Terminate the file list
282
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);
286
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;
294        ++it) {
295     const MCSection *Sec = *it;
296     const MCLineSection *Line = MCLineSections.lookup(Sec);
297     EmitDwarfLineTable(MCOS, Sec, Line);
298
299     // Now delete the MCLineSections that were created in MCLineEntry::Make()
300     // and used to emit the line table.
301     delete Line;
302   }
303
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
307     // it requires:  
308     // total_length >= prologue_length + 10
309     // We are 4 bytes short, since we have total_length = 51 and
310     // prologue_length = 45
311
312     // The regular end_sequence should be sufficient.
313     MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
314   }
315
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);
319 }
320
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());
328 }
329
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);
337 }
338
339 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
340 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
341                              raw_ostream &OS) {
342   uint64_t Temp, Opcode;
343   bool NeedCopy = false;
344
345   // Scale the address delta by the minimum instruction length.
346   AddrDelta = ScaleAddrDelta(AddrDelta);
347
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);
354     else {
355       OS << char(dwarf::DW_LNS_advance_pc);
356       MCObjectWriter::EncodeULEB128(AddrDelta, OS);
357     }
358     OS << char(dwarf::DW_LNS_extended_op);
359     OS << char(1);
360     OS << char(dwarf::DW_LNE_end_sequence);
361     return;
362   }
363
364   // Bias the line delta by the base.
365   Temp = LineDelta - DWARF2_LINE_BASE;
366
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);
371     SmallString<32> Tmp;
372     raw_svector_ostream OSE(Tmp);
373     MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
374     OS << OSE.str();
375
376     LineDelta = 0;
377     Temp = 0 - DWARF2_LINE_BASE;
378     NeedCopy = true;
379   }
380
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);
384     return;
385   }
386
387   // Bias the opcode by the special opcode base.
388   Temp += DWARF2_LINE_OPCODE_BASE;
389
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;
394     if (Opcode <= 255) {
395       OS << char(Opcode);
396       return;
397     }
398
399     // Try using DW_LNS_const_add_pc followed by special op.
400     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
401     if (Opcode <= 255) {
402       OS << char(dwarf::DW_LNS_const_add_pc);
403       OS << char(Opcode);
404       return;
405     }
406   }
407
408   // Otherwise use DW_LNS_advance_pc.
409   OS << char(dwarf::DW_LNS_advance_pc);
410   SmallString<32> Tmp;
411   raw_svector_ostream OSE(Tmp);
412   MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
413   OS << OSE.str();
414
415   if (NeedCopy)
416     OS << char(dwarf::DW_LNS_copy);
417   else
418     OS << char(Temp);
419 }
420
421 void MCDwarfFile::print(raw_ostream &OS) const {
422   OS << '"' << getName() << '"';
423 }
424
425 void MCDwarfFile::dump() const {
426   print(dbgs());
427 }
428
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)
434     return size;
435  else
436    return -size;
437 }
438
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;
444   switch (format) {
445   default:
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:
452     return 2;
453   case dwarf::DW_EH_PE_udata4:
454   case dwarf::DW_EH_PE_sdata4:
455     return 4;
456   case dwarf::DW_EH_PE_udata8:
457   case dwarf::DW_EH_PE_sdata8:
458     return 8;
459   }
460 }
461
462 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
463                        unsigned symbolEncoding) {
464   MCContext &context = streamer.getContext();
465   const MCAsmInfo &asmInfo = context.getAsmInfo();
466   const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
467                                                 symbolEncoding,
468                                                 streamer);
469   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
470   streamer.EmitAbsValue(v, size);
471 }
472
473 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
474                             unsigned symbolEncoding) {
475   MCContext &context = streamer.getContext();
476   const MCAsmInfo &asmInfo = context.getAsmInfo();
477   const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
478                                                         symbolEncoding,
479                                                         streamer);
480   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
481   streamer.EmitValue(v, size);
482 }
483
484 static const MachineLocation TranslateMachineLocation(
485                                                   const TargetAsmInfo &AsmInfo,
486                                                   const MachineLocation &Loc) {
487   unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
488     MachineLocation::VirtualFP :
489     unsigned(AsmInfo.getDwarfRegNum(Loc.getReg(), true));
490   const MachineLocation &NewLoc = Loc.isReg() ?
491     MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
492   return NewLoc;
493 }
494
495 namespace {
496   class FrameEmitterImpl {
497     int CFAOffset;
498     int CIENum;
499     bool UsingCFI;
500     bool IsEH;
501     const MCSymbol *SectionStart;
502
503   public:
504     FrameEmitterImpl(bool usingCFI, bool isEH, const MCSymbol *sectionStart) :
505       CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
506       SectionStart(sectionStart) {
507     }
508
509     /// EmitCompactUnwind - Emit the unwind information in a compact way. If
510     /// we're successful, return 'true'. Otherwise, return 'false' and it will
511     /// emit the normal CIE and FDE.
512     bool EmitCompactUnwind(MCStreamer &streamer,
513                            const MCDwarfFrameInfo &frame);
514
515     const MCSymbol &EmitCIE(MCStreamer &streamer,
516                             const MCSymbol *personality,
517                             unsigned personalityEncoding,
518                             const MCSymbol *lsda,
519                             unsigned lsdaEncoding);
520     MCSymbol *EmitFDE(MCStreamer &streamer,
521                       const MCSymbol &cieStart,
522                       const MCDwarfFrameInfo &frame);
523     void EmitCFIInstructions(MCStreamer &streamer,
524                              const std::vector<MCCFIInstruction> &Instrs,
525                              MCSymbol *BaseLabel);
526     void EmitCFIInstruction(MCStreamer &Streamer,
527                             const MCCFIInstruction &Instr);
528   };
529 }
530
531 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
532                                           const MCCFIInstruction &Instr) {
533   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
534
535   switch (Instr.getOperation()) {
536   case MCCFIInstruction::Move:
537   case MCCFIInstruction::RelMove: {
538     const MachineLocation &Dst = Instr.getDestination();
539     const MachineLocation &Src = Instr.getSource();
540     const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
541
542     // If advancing cfa.
543     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
544       if (Src.getReg() == MachineLocation::VirtualFP) {
545         Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
546       } else {
547         Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
548         Streamer.EmitULEB128IntValue(Src.getReg());
549       }
550
551       if (IsRelative)
552         CFAOffset += Src.getOffset();
553       else
554         CFAOffset = -Src.getOffset();
555
556       Streamer.EmitULEB128IntValue(CFAOffset);
557       return;
558     }
559
560     if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
561       assert(Dst.isReg() && "Machine move not supported yet.");
562       Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
563       Streamer.EmitULEB128IntValue(Dst.getReg());
564       return;
565     }
566
567     unsigned Reg = Src.getReg();
568
569     int Offset = Dst.getOffset();
570     if (IsRelative)
571       Offset -= CFAOffset;
572     Offset = Offset / dataAlignmentFactor;
573
574     if (Offset < 0) {
575       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
576       Streamer.EmitULEB128IntValue(Reg);
577       Streamer.EmitSLEB128IntValue(Offset);
578     } else if (Reg < 64) {
579       Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
580       Streamer.EmitULEB128IntValue(Offset);
581     } else {
582       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
583       Streamer.EmitULEB128IntValue(Reg);
584       Streamer.EmitULEB128IntValue(Offset);
585     }
586     return;
587   }
588   case MCCFIInstruction::Remember:
589     Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
590     return;
591   case MCCFIInstruction::Restore:
592     Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
593     return;
594   case MCCFIInstruction::SameValue: {
595     unsigned Reg = Instr.getDestination().getReg();
596     Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
597     Streamer.EmitULEB128IntValue(Reg);
598     return;
599   }
600   }
601   llvm_unreachable("Unhandled case in switch");
602 }
603
604 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
605 /// frame.
606 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
607                                     const std::vector<MCCFIInstruction> &Instrs,
608                                            MCSymbol *BaseLabel) {
609   for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
610     const MCCFIInstruction &Instr = Instrs[i];
611     MCSymbol *Label = Instr.getLabel();
612     // Throw out move if the label is invalid.
613     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
614
615     // Advance row if new location.
616     if (BaseLabel && Label) {
617       MCSymbol *ThisSym = Label;
618       if (ThisSym != BaseLabel) {
619         streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
620         BaseLabel = ThisSym;
621       }
622     }
623
624     EmitCFIInstruction(streamer, Instr);
625   }
626 }
627
628 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
629 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
630 /// normal CIE and FDE.
631 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
632                                          const MCDwarfFrameInfo &Frame) {
633 #if 1
634   return false;
635 #else
636   MCContext &Context = Streamer.getContext();
637   const TargetAsmInfo &TAI = Context.getTargetAsmInfo();
638   Streamer.SwitchSection(TAI.getCompactUnwindSection());
639
640   // range-start range-length  compact-unwind-enc personality-func   lsda
641   //  _foo       LfooEnd-_foo  0x00000023          0                 0
642   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
643   //
644   //   .section __LD,__compact_unwind,regular,debug
645   //
646   //   # compact unwind for _foo
647   //   .quad _foo
648   //   .set L1,LfooEnd-_foo
649   //   .long L1
650   //   .long 0x01010001
651   //   .quad 0
652   //   .quad 0
653   //
654   //   # compact unwind for _bar
655   //   .quad _bar
656   //   .set L2,LbarEnd-_bar
657   //   .long L2
658   //   .long 0x01020011
659   //   .quad __gxx_personality
660   //   .quad except_tab1
661
662   // Range Start
663   unsigned FDEEncoding = TAI.getFDEEncoding(UsingCFI);
664   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
665   Streamer.EmitSymbolValue(Frame.Function, Size);
666
667   // Range Length
668   const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
669                                               *Frame.End, 0);
670   Streamer.EmitAbsValue(Range, Size);
671
672   // Personality Function
673   Size = getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
674   if (Frame.Personality)
675     Streamer.EmitSymbolValue(Frame.Personality, Size);
676   else
677     Streamer.EmitIntValue(0, Size); // No personality fn
678
679   // LSDA
680   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
681   if (Frame.Lsda)
682     Streamer.EmitSymbolValue(Frame.Lsda, Size);
683   else
684     Streamer.EmitIntValue(0, Size); // No LSDA
685
686   return true;
687 #endif
688 }
689
690 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
691                                           const MCSymbol *personality,
692                                           unsigned personalityEncoding,
693                                           const MCSymbol *lsda,
694                                           unsigned lsdaEncoding) {
695   MCContext &context = streamer.getContext();
696   const TargetAsmInfo &asmInfo = context.getTargetAsmInfo();
697
698   MCSymbol *sectionStart;
699   if (asmInfo.isFunctionEHFrameSymbolPrivate() || !IsEH)
700     sectionStart = context.CreateTempSymbol();
701   else
702     sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
703
704   CIENum++;
705
706   MCSymbol *sectionEnd = streamer.getContext().CreateTempSymbol();
707
708   // Length
709   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
710                                                *sectionEnd, 4);
711   streamer.EmitLabel(sectionStart);
712   streamer.EmitAbsValue(Length, 4);
713
714   // CIE ID
715   unsigned CIE_ID = IsEH ? 0 : -1;
716   streamer.EmitIntValue(CIE_ID, 4);
717
718   // Version
719   streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
720
721   // Augmentation String
722   SmallString<8> Augmentation;
723   if (IsEH) {
724     Augmentation += "z";
725     if (personality)
726       Augmentation += "P";
727     if (lsda)
728       Augmentation += "L";
729     Augmentation += "R";
730     streamer.EmitBytes(Augmentation.str(), 0);
731   }
732   streamer.EmitIntValue(0, 1);
733
734   // Code Alignment Factor
735   streamer.EmitULEB128IntValue(1);
736
737   // Data Alignment Factor
738   streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
739
740   // Return Address Register
741   streamer.EmitULEB128IntValue(asmInfo.getDwarfRARegNum(true));
742
743   // Augmentation Data Length (optional)
744
745   unsigned augmentationLength = 0;
746   if (IsEH) {
747     if (personality) {
748       // Personality Encoding
749       augmentationLength += 1;
750       // Personality
751       augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
752     }
753     if (lsda)
754       augmentationLength += 1;
755     // Encoding of the FDE pointers
756     augmentationLength += 1;
757
758     streamer.EmitULEB128IntValue(augmentationLength);
759
760     // Augmentation Data (optional)
761     if (personality) {
762       // Personality Encoding
763       streamer.EmitIntValue(personalityEncoding, 1);
764       // Personality
765       EmitPersonality(streamer, *personality, personalityEncoding);
766     }
767     if (lsda)
768       streamer.EmitIntValue(lsdaEncoding, 1); // LSDA Encoding
769     // Encoding of the FDE pointers
770     streamer.EmitIntValue(asmInfo.getFDEEncoding(UsingCFI), 1);
771   }
772
773   // Initial Instructions
774
775   const std::vector<MachineMove> &Moves = asmInfo.getInitialFrameState();
776   std::vector<MCCFIInstruction> Instructions;
777
778   for (int i = 0, n = Moves.size(); i != n; ++i) {
779     MCSymbol *Label = Moves[i].getLabel();
780     const MachineLocation &Dst =
781       TranslateMachineLocation(asmInfo, Moves[i].getDestination());
782     const MachineLocation &Src =
783       TranslateMachineLocation(asmInfo, Moves[i].getSource());
784     MCCFIInstruction Inst(Label, Dst, Src);
785     Instructions.push_back(Inst);
786   }
787
788   EmitCFIInstructions(streamer, Instructions, NULL);
789
790   // Padding
791   streamer.EmitValueToAlignment(IsEH ? 4 : asmInfo.getPointerSize());
792
793   streamer.EmitLabel(sectionEnd);
794   return *sectionStart;
795 }
796
797 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
798                                     const MCSymbol &cieStart,
799                                     const MCDwarfFrameInfo &frame) {
800   MCContext &context = streamer.getContext();
801   MCSymbol *fdeStart = context.CreateTempSymbol();
802   MCSymbol *fdeEnd = context.CreateTempSymbol();
803   const TargetAsmInfo &TAsmInfo = context.getTargetAsmInfo();
804
805   if (!TAsmInfo.isFunctionEHFrameSymbolPrivate() && IsEH) {
806     MCSymbol *EHSym = context.GetOrCreateSymbol(
807       frame.Function->getName() + Twine(".eh"));
808     streamer.EmitEHSymAttributes(frame.Function, EHSym);
809     streamer.EmitLabel(EHSym);
810   }
811
812   // Length
813   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
814   streamer.EmitAbsValue(Length, 4);
815
816   streamer.EmitLabel(fdeStart);
817
818   // CIE Pointer
819   const MCAsmInfo &asmInfo = context.getAsmInfo();
820   if (IsEH) {
821     const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
822                                                  0);
823     streamer.EmitAbsValue(offset, 4);
824   } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
825     const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
826                                                  cieStart, 0);
827     streamer.EmitAbsValue(offset, 4);
828   } else {
829     streamer.EmitSymbolValue(&cieStart, 4);
830   }
831   unsigned fdeEncoding = TAsmInfo.getFDEEncoding(UsingCFI);
832   unsigned size = getSizeForEncoding(streamer, fdeEncoding);
833
834   // PC Begin
835   unsigned PCBeginEncoding = IsEH ? fdeEncoding :
836     (unsigned)dwarf::DW_EH_PE_absptr;
837   unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
838   EmitSymbol(streamer, *frame.Begin, PCBeginEncoding);
839
840   // PC Range
841   const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
842                                               *frame.End, 0);
843   streamer.EmitAbsValue(Range, size);
844
845   if (IsEH) {
846     // Augmentation Data Length
847     unsigned augmentationLength = 0;
848
849     if (frame.Lsda)
850       augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
851
852     streamer.EmitULEB128IntValue(augmentationLength);
853
854     // Augmentation Data
855     if (frame.Lsda)
856       EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding);
857   }
858
859   // Call Frame Instructions
860
861   EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
862
863   // Padding
864   streamer.EmitValueToAlignment(PCBeginSize);
865
866   return fdeEnd;
867 }
868
869 namespace {
870   struct CIEKey {
871     static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
872     static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
873
874     CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
875            unsigned LsdaEncoding_) : Personality(Personality_),
876                                      PersonalityEncoding(PersonalityEncoding_),
877                                      LsdaEncoding(LsdaEncoding_) {
878     }
879     const MCSymbol* Personality;
880     unsigned PersonalityEncoding;
881     unsigned LsdaEncoding;
882   };
883 }
884
885 namespace llvm {
886   template <>
887   struct DenseMapInfo<CIEKey> {
888     static CIEKey getEmptyKey() {
889       return CIEKey::getEmptyKey();
890     }
891     static CIEKey getTombstoneKey() {
892       return CIEKey::getTombstoneKey();
893     }
894     static unsigned getHashValue(const CIEKey &Key) {
895       FoldingSetNodeID ID;
896       ID.AddPointer(Key.Personality);
897       ID.AddInteger(Key.PersonalityEncoding);
898       ID.AddInteger(Key.LsdaEncoding);
899       return ID.ComputeHash();
900     }
901     static bool isEqual(const CIEKey &LHS,
902                         const CIEKey &RHS) {
903       return LHS.Personality == RHS.Personality &&
904         LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
905         LHS.LsdaEncoding == RHS.LsdaEncoding;
906     }
907   };
908 }
909
910 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
911                                bool UsingCFI,
912                                bool IsEH) {
913   MCContext &Context = Streamer.getContext();
914   const TargetAsmInfo &AsmInfo = Context.getTargetAsmInfo();
915   const MCSection &Section = IsEH ? *AsmInfo.getEHFrameSection() :
916                                     *AsmInfo.getDwarfFrameSection();
917   Streamer.SwitchSection(&Section);
918   MCSymbol *SectionStart = Context.CreateTempSymbol();
919   Streamer.EmitLabel(SectionStart);
920
921   MCSymbol *FDEEnd = NULL;
922   DenseMap<CIEKey, const MCSymbol*> CIEStarts;
923   FrameEmitterImpl Emitter(UsingCFI, IsEH, SectionStart);
924
925   const MCSymbol *DummyDebugKey = NULL;
926   for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
927     const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
928     if (IsEH && AsmInfo.getCompactUnwindSection() &&
929         Emitter.EmitCompactUnwind(Streamer, Frame))
930       continue;
931
932     CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
933                Frame.LsdaEncoding);
934     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
935     if (!CIEStart)
936       CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
937                                   Frame.PersonalityEncoding, Frame.Lsda,
938                                   Frame.LsdaEncoding);
939
940     FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
941
942     if (i != n - 1)
943       Streamer.EmitLabel(FDEEnd);
944   }
945
946   Streamer.EmitValueToAlignment(AsmInfo.getPointerSize());
947   if (FDEEnd)
948     Streamer.EmitLabel(FDEEnd);
949 }
950
951 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
952                                          uint64_t AddrDelta) {
953   SmallString<256> Tmp;
954   raw_svector_ostream OS(Tmp);
955   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
956   Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
957 }
958
959 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
960                                            raw_ostream &OS) {
961   // FIXME: Assumes the code alignment factor is 1.
962   if (AddrDelta == 0) {
963   } else if (isUIntN(6, AddrDelta)) {
964     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
965     OS << Opcode;
966   } else if (isUInt<8>(AddrDelta)) {
967     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
968     OS << uint8_t(AddrDelta);
969   } else if (isUInt<16>(AddrDelta)) {
970     // FIXME: check what is the correct behavior on a big endian machine.
971     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
972     OS << uint8_t( AddrDelta       & 0xff);
973     OS << uint8_t((AddrDelta >> 8) & 0xff);
974   } else {
975     // FIXME: check what is the correct behavior on a big endian machine.
976     assert(isUInt<32>(AddrDelta));
977     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
978     OS << uint8_t( AddrDelta        & 0xff);
979     OS << uint8_t((AddrDelta >> 8)  & 0xff);
980     OS << uint8_t((AddrDelta >> 16) & 0xff);
981     OS << uint8_t((AddrDelta >> 24) & 0xff);
982
983   }
984 }