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