AsmPrinter.cpp revision 8d2970ba91fc2161bf5fc3d073a59cd4f3dc45a6
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
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// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
15#include "llvm/CodeGen/AsmPrinter.h"
16#include "llvm/Assembly/Writer.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Constants.h"
19#include "llvm/Module.h"
20#include "llvm/CodeGen/DwarfWriter.h"
21#include "llvm/CodeGen/GCMetadataPrinter.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineJumpTableInfo.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/Analysis/DebugInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/MC/MCExpr.h"
31#include "llvm/MC/MCInst.h"
32#include "llvm/MC/MCSection.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
35#include "llvm/MC/MCAsmInfo.h"
36#include "llvm/Target/Mangler.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetLowering.h"
40#include "llvm/Target/TargetLoweringObjectFile.h"
41#include "llvm/Target/TargetOptions.h"
42#include "llvm/Target/TargetRegisterInfo.h"
43#include "llvm/ADT/SmallPtrSet.h"
44#include "llvm/ADT/SmallString.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/Format.h"
50#include "llvm/Support/FormattedStream.h"
51#include <cerrno>
52using namespace llvm;
53
54STATISTIC(EmittedInsts, "Number of machine instrs printed");
55
56char AsmPrinter::ID = 0;
57AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
58                       MCContext &Ctx, MCStreamer &Streamer,
59                       const MCAsmInfo *T)
60  : MachineFunctionPass(&ID), O(o),
61    TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
62    OutContext(Ctx), OutStreamer(Streamer),
63    LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
64  DW = 0; MMI = 0;
65  VerboseAsm = Streamer.isVerboseAsm();
66}
67
68AsmPrinter::~AsmPrinter() {
69  for (gcp_iterator I = GCMetadataPrinters.begin(),
70                    E = GCMetadataPrinters.end(); I != E; ++I)
71    delete I->second;
72
73  delete &OutStreamer;
74  delete &OutContext;
75}
76
77/// getFunctionNumber - Return a unique ID for the current function.
78///
79unsigned AsmPrinter::getFunctionNumber() const {
80  return MF->getFunctionNumber();
81}
82
83TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
84  return TM.getTargetLowering()->getObjFileLowering();
85}
86
87/// getCurrentSection() - Return the current section we are emitting to.
88const MCSection *AsmPrinter::getCurrentSection() const {
89  return OutStreamer.getCurrentSection();
90}
91
92
93void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
94  AU.setPreservesAll();
95  MachineFunctionPass::getAnalysisUsage(AU);
96  AU.addRequired<GCModuleInfo>();
97  if (VerboseAsm)
98    AU.addRequired<MachineLoopInfo>();
99}
100
101bool AsmPrinter::doInitialization(Module &M) {
102  // Initialize TargetLoweringObjectFile.
103  const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
104    .Initialize(OutContext, TM);
105
106  Mang = new Mangler(*MAI);
107
108  // Allow the target to emit any magic that it wants at the start of the file.
109  EmitStartOfAsmFile(M);
110
111  // Very minimal debug info. It is ignored if we emit actual debug info. If we
112  // don't, this at least helps the user find where a global came from.
113  if (MAI->hasSingleParameterDotFile()) {
114    // .file "foo.c"
115    OutStreamer.EmitFileDirective(M.getModuleIdentifier());
116  }
117
118  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
119  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
120  for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
121    if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
122      MP->beginAssembly(O, *this, *MAI);
123
124  if (!M.getModuleInlineAsm().empty())
125    O << MAI->getCommentString() << " Start of file scope inline assembly\n"
126      << M.getModuleInlineAsm()
127      << '\n' << MAI->getCommentString()
128      << " End of file scope inline assembly\n";
129
130  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
131  if (MMI)
132    MMI->AnalyzeModule(M);
133  DW = getAnalysisIfAvailable<DwarfWriter>();
134  if (DW)
135    DW->BeginModule(&M, MMI, O, this, MAI);
136
137  return false;
138}
139
140void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
141  switch ((GlobalValue::LinkageTypes)Linkage) {
142  case GlobalValue::CommonLinkage:
143  case GlobalValue::LinkOnceAnyLinkage:
144  case GlobalValue::LinkOnceODRLinkage:
145  case GlobalValue::WeakAnyLinkage:
146  case GlobalValue::WeakODRLinkage:
147  case GlobalValue::LinkerPrivateLinkage:
148    if (MAI->getWeakDefDirective() != 0) {
149      // .globl _foo
150      OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
151      // .weak_definition _foo
152      OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
153    } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
154      // .globl _foo
155      OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
156      // FIXME: linkonce should be a section attribute, handled by COFF Section
157      // assignment.
158      // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
159      // .linkonce discard
160      // FIXME: It would be nice to use .linkonce samesize for non-common
161      // globals.
162      O << LinkOnce;
163    } else {
164      // .weak _foo
165      OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
166    }
167    break;
168  case GlobalValue::DLLExportLinkage:
169  case GlobalValue::AppendingLinkage:
170    // FIXME: appending linkage variables should go into a section of
171    // their name or something.  For now, just emit them as external.
172  case GlobalValue::ExternalLinkage:
173    // If external or appending, declare as a global symbol.
174    // .globl _foo
175    OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
176    break;
177  case GlobalValue::PrivateLinkage:
178  case GlobalValue::InternalLinkage:
179    break;
180  default:
181    llvm_unreachable("Unknown linkage type!");
182  }
183}
184
185
186/// EmitGlobalVariable - Emit the specified global variable to the .s file.
187void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
188  if (!GV->hasInitializer())   // External globals require no code.
189    return;
190
191  // Check to see if this is a special global used by LLVM, if so, emit it.
192  if (EmitSpecialLLVMGlobal(GV))
193    return;
194
195  MCSymbol *GVSym = GetGlobalValueSymbol(GV);
196  EmitVisibility(GVSym, GV->getVisibility());
197
198  if (MAI->hasDotTypeDotSizeDirective())
199    OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
200
201  SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
202
203  const TargetData *TD = TM.getTargetData();
204  unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
205  unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
206
207  // Handle common and BSS local symbols (.lcomm).
208  if (GVKind.isCommon() || GVKind.isBSSLocal()) {
209    if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
210
211    if (VerboseAsm) {
212      WriteAsOperand(OutStreamer.GetCommentOS(), GV,
213                     /*PrintType=*/false, GV->getParent());
214      OutStreamer.GetCommentOS() << '\n';
215    }
216
217    // Handle common symbols.
218    if (GVKind.isCommon()) {
219      // .comm _foo, 42, 4
220      OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
221      return;
222    }
223
224    // Handle local BSS symbols.
225    if (MAI->hasMachoZeroFillDirective()) {
226      const MCSection *TheSection =
227        getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
228      // .zerofill __DATA, __bss, _foo, 400, 5
229      OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
230      return;
231    }
232
233    if (MAI->hasLCOMMDirective()) {
234      // .lcomm _foo, 42
235      OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
236      return;
237    }
238
239    // .local _foo
240    OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
241    // .comm _foo, 42, 4
242    OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
243    return;
244  }
245
246  const MCSection *TheSection =
247    getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
248
249  // Handle the zerofill directive on darwin, which is a special form of BSS
250  // emission.
251  if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
252    // .globl _foo
253    OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
254    // .zerofill __DATA, __common, _foo, 400, 5
255    OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
256    return;
257  }
258
259  OutStreamer.SwitchSection(TheSection);
260
261  EmitLinkage(GV->getLinkage(), GVSym);
262  EmitAlignment(AlignLog, GV);
263
264  if (VerboseAsm) {
265    WriteAsOperand(OutStreamer.GetCommentOS(), GV,
266                   /*PrintType=*/false, GV->getParent());
267    OutStreamer.GetCommentOS() << '\n';
268  }
269  OutStreamer.EmitLabel(GVSym);
270
271  EmitGlobalConstant(GV->getInitializer());
272
273  if (MAI->hasDotTypeDotSizeDirective())
274    // .size foo, 42
275    OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
276
277  OutStreamer.AddBlankLine();
278}
279
280/// EmitFunctionHeader - This method emits the header for the current
281/// function.
282void AsmPrinter::EmitFunctionHeader() {
283  // Print out constants referenced by the function
284  EmitConstantPool();
285
286  // Print the 'header' of function.
287  const Function *F = MF->getFunction();
288
289  OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
290  EmitVisibility(CurrentFnSym, F->getVisibility());
291
292  EmitLinkage(F->getLinkage(), CurrentFnSym);
293  EmitAlignment(MF->getAlignment(), F);
294
295  if (MAI->hasDotTypeDotSizeDirective())
296    OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
297
298  if (VerboseAsm) {
299    WriteAsOperand(OutStreamer.GetCommentOS(), F,
300                   /*PrintType=*/false, F->getParent());
301    OutStreamer.GetCommentOS() << '\n';
302  }
303
304  // Emit the CurrentFnSym.  This is is a virtual function to allow targets to
305  // do their wild and crazy things as required.
306  EmitFunctionEntryLabel();
307
308  // Add some workaround for linkonce linkage on Cygwin\MinGW.
309  if (MAI->getLinkOnceDirective() != 0 &&
310      (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
311    // FIXME: What is this?
312    O << "Lllvm$workaround$fake$stub$" << *CurrentFnSym << ":\n";
313
314  // Emit pre-function debug and/or EH information.
315  if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
316    DW->BeginFunction(MF);
317}
318
319/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
320/// function.  This can be overridden by targets as required to do custom stuff.
321void AsmPrinter::EmitFunctionEntryLabel() {
322  OutStreamer.EmitLabel(CurrentFnSym);
323}
324
325
326/// EmitFunctionBody - This method emits the body and trailer for a
327/// function.
328void AsmPrinter::EmitFunctionBody() {
329  // Emit target-specific gunk before the function body.
330  EmitFunctionBodyStart();
331
332  // Print out code for the function.
333  bool HasAnyRealCode = false;
334  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
335       I != E; ++I) {
336    // Print a label for the basic block.
337    EmitBasicBlockStart(I);
338    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
339         II != IE; ++II) {
340      // Print the assembly for the instruction.
341      if (!II->isLabel())
342        HasAnyRealCode = true;
343
344      ++EmittedInsts;
345
346      // FIXME: Clean up processDebugLoc.
347      processDebugLoc(II, true);
348
349      EmitInstruction(II);
350
351      if (VerboseAsm)
352        EmitComments(*II);
353      O << '\n';
354
355      // FIXME: Clean up processDebugLoc.
356      processDebugLoc(II, false);
357    }
358  }
359
360  // If the function is empty and the object file uses .subsections_via_symbols,
361  // then we need to emit *something* to the function body to prevent the
362  // labels from collapsing together.  Just emit a 0 byte.
363  if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)
364    OutStreamer.EmitIntValue(0, 1, 0/*addrspace*/);
365
366  // Emit target-specific gunk after the function body.
367  EmitFunctionBodyEnd();
368
369  if (MAI->hasDotTypeDotSizeDirective())
370    O << "\t.size\t" << *CurrentFnSym << ", .-" << *CurrentFnSym << '\n';
371
372  // Emit post-function debug information.
373  if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
374    DW->EndFunction(MF);
375
376  // Print out jump tables referenced by the function.
377  EmitJumpTableInfo();
378}
379
380
381bool AsmPrinter::doFinalization(Module &M) {
382  // Emit global variables.
383  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
384       I != E; ++I)
385    EmitGlobalVariable(I);
386
387  // Emit final debug information.
388  if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
389    DW->EndModule();
390
391  // If the target wants to know about weak references, print them all.
392  if (MAI->getWeakRefDirective()) {
393    // FIXME: This is not lazy, it would be nice to only print weak references
394    // to stuff that is actually used.  Note that doing so would require targets
395    // to notice uses in operands (due to constant exprs etc).  This should
396    // happen with the MC stuff eventually.
397
398    // Print out module-level global variables here.
399    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
400         I != E; ++I) {
401      if (!I->hasExternalWeakLinkage()) continue;
402      OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
403                                      MCSA_WeakReference);
404    }
405
406    for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
407      if (!I->hasExternalWeakLinkage()) continue;
408      OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
409                                      MCSA_WeakReference);
410    }
411  }
412
413  if (MAI->hasSetDirective()) {
414    OutStreamer.AddBlankLine();
415    for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
416         I != E; ++I) {
417      MCSymbol *Name = GetGlobalValueSymbol(I);
418
419      const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
420      MCSymbol *Target = GetGlobalValueSymbol(GV);
421
422      if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
423        OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
424      else if (I->hasWeakLinkage())
425        OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
426      else
427        assert(I->hasLocalLinkage() && "Invalid alias linkage");
428
429      EmitVisibility(Name, I->getVisibility());
430
431      // Emit the directives as assignments aka .set:
432      OutStreamer.EmitAssignment(Name,
433                                 MCSymbolRefExpr::Create(Target, OutContext));
434    }
435  }
436
437  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
438  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
439  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
440    if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
441      MP->finishAssembly(O, *this, *MAI);
442
443  // If we don't have any trampolines, then we don't require stack memory
444  // to be executable. Some targets have a directive to declare this.
445  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
446  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
447    if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
448      OutStreamer.SwitchSection(S);
449
450  // Allow the target to emit any magic that it wants at the end of the file,
451  // after everything else has gone out.
452  EmitEndOfAsmFile(M);
453
454  delete Mang; Mang = 0;
455  DW = 0; MMI = 0;
456
457  OutStreamer.Finish();
458  return false;
459}
460
461void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
462  this->MF = &MF;
463  // Get the function symbol.
464  CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
465
466  if (VerboseAsm)
467    LI = &getAnalysis<MachineLoopInfo>();
468}
469
470namespace {
471  // SectionCPs - Keep track the alignment, constpool entries per Section.
472  struct SectionCPs {
473    const MCSection *S;
474    unsigned Alignment;
475    SmallVector<unsigned, 4> CPEs;
476    SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
477  };
478}
479
480/// EmitConstantPool - Print to the current output stream assembly
481/// representations of the constants in the constant pool MCP. This is
482/// used to print out constants which have been "spilled to memory" by
483/// the code generator.
484///
485void AsmPrinter::EmitConstantPool() {
486  const MachineConstantPool *MCP = MF->getConstantPool();
487  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
488  if (CP.empty()) return;
489
490  // Calculate sections for constant pool entries. We collect entries to go into
491  // the same section together to reduce amount of section switch statements.
492  SmallVector<SectionCPs, 4> CPSections;
493  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
494    const MachineConstantPoolEntry &CPE = CP[i];
495    unsigned Align = CPE.getAlignment();
496
497    SectionKind Kind;
498    switch (CPE.getRelocationInfo()) {
499    default: llvm_unreachable("Unknown section kind");
500    case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
501    case 1:
502      Kind = SectionKind::getReadOnlyWithRelLocal();
503      break;
504    case 0:
505    switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
506    case 4:  Kind = SectionKind::getMergeableConst4(); break;
507    case 8:  Kind = SectionKind::getMergeableConst8(); break;
508    case 16: Kind = SectionKind::getMergeableConst16();break;
509    default: Kind = SectionKind::getMergeableConst(); break;
510    }
511    }
512
513    const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
514
515    // The number of sections are small, just do a linear search from the
516    // last section to the first.
517    bool Found = false;
518    unsigned SecIdx = CPSections.size();
519    while (SecIdx != 0) {
520      if (CPSections[--SecIdx].S == S) {
521        Found = true;
522        break;
523      }
524    }
525    if (!Found) {
526      SecIdx = CPSections.size();
527      CPSections.push_back(SectionCPs(S, Align));
528    }
529
530    if (Align > CPSections[SecIdx].Alignment)
531      CPSections[SecIdx].Alignment = Align;
532    CPSections[SecIdx].CPEs.push_back(i);
533  }
534
535  // Now print stuff into the calculated sections.
536  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
537    OutStreamer.SwitchSection(CPSections[i].S);
538    EmitAlignment(Log2_32(CPSections[i].Alignment));
539
540    unsigned Offset = 0;
541    for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
542      unsigned CPI = CPSections[i].CPEs[j];
543      MachineConstantPoolEntry CPE = CP[CPI];
544
545      // Emit inter-object padding for alignment.
546      unsigned AlignMask = CPE.getAlignment() - 1;
547      unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
548      OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
549
550      const Type *Ty = CPE.getType();
551      Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
552
553      // Emit the label with a comment on it.
554      if (VerboseAsm) {
555        OutStreamer.GetCommentOS() << "constant pool ";
556        WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
557                          MF->getFunction()->getParent());
558        OutStreamer.GetCommentOS() << '\n';
559      }
560      OutStreamer.EmitLabel(GetCPISymbol(CPI));
561
562      if (CPE.isMachineConstantPoolEntry())
563        EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
564      else
565        EmitGlobalConstant(CPE.Val.ConstVal);
566    }
567  }
568}
569
570/// EmitJumpTableInfo - Print assembly representations of the jump tables used
571/// by the current function to the current output stream.
572///
573void AsmPrinter::EmitJumpTableInfo() {
574  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
575  if (MJTI == 0) return;
576  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
577  if (JT.empty()) return;
578
579  // Pick the directive to use to print the jump table entries, and switch to
580  // the appropriate section.
581  const Function *F = MF->getFunction();
582  bool JTInDiffSection = false;
583  if (// In PIC mode, we need to emit the jump table to the same section as the
584      // function body itself, otherwise the label differences won't make sense.
585      // FIXME: Need a better predicate for this: what about custom entries?
586      MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
587      // We should also do if the section name is NULL or function is declared
588      // in discardable section
589      // FIXME: this isn't the right predicate, should be based on the MCSection
590      // for the function.
591      F->isWeakForLinker()) {
592    OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
593  } else {
594    // Otherwise, drop it in the readonly section.
595    const MCSection *ReadOnlySection =
596      getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
597    OutStreamer.SwitchSection(ReadOnlySection);
598    JTInDiffSection = true;
599  }
600
601  EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
602
603  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
604    const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
605
606    // If this jump table was deleted, ignore it.
607    if (JTBBs.empty()) continue;
608
609    // For the EK_LabelDifference32 entry, if the target supports .set, emit a
610    // .set directive for each unique entry.  This reduces the number of
611    // relocations the assembler will generate for the jump table.
612    if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
613        MAI->hasSetDirective()) {
614      SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
615      const TargetLowering *TLI = TM.getTargetLowering();
616      const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
617      for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
618        const MachineBasicBlock *MBB = JTBBs[ii];
619        if (!EmittedSets.insert(MBB)) continue;
620
621        // .set LJTSet, LBB32-base
622        const MCExpr *LHS =
623          MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
624        OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
625                                MCBinaryExpr::CreateSub(LHS, Base, OutContext));
626      }
627    }
628
629    // On some targets (e.g. Darwin) we want to emit two consequtive labels
630    // before each jump table.  The first label is never referenced, but tells
631    // the assembler and linker the extents of the jump table object.  The
632    // second label is actually referenced by the code.
633    if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
634      // FIXME: This doesn't have to have any specific name, just any randomly
635      // named and numbered 'l' label would work.  Simplify GetJTISymbol.
636      OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
637
638    OutStreamer.EmitLabel(GetJTISymbol(JTI));
639
640    for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
641      EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
642  }
643}
644
645/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
646/// current stream.
647void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
648                                    const MachineBasicBlock *MBB,
649                                    unsigned UID) const {
650  const MCExpr *Value = 0;
651  switch (MJTI->getEntryKind()) {
652  case MachineJumpTableInfo::EK_Custom32:
653    Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
654                                                              OutContext);
655    break;
656  case MachineJumpTableInfo::EK_BlockAddress:
657    // EK_BlockAddress - Each entry is a plain address of block, e.g.:
658    //     .word LBB123
659    Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
660    break;
661  case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
662    // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
663    // with a relocation as gp-relative, e.g.:
664    //     .gprel32 LBB123
665    MCSymbol *MBBSym = MBB->getSymbol(OutContext);
666    OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
667    return;
668  }
669
670  case MachineJumpTableInfo::EK_LabelDifference32: {
671    // EK_LabelDifference32 - Each entry is the address of the block minus
672    // the address of the jump table.  This is used for PIC jump tables where
673    // gprel32 is not supported.  e.g.:
674    //      .word LBB123 - LJTI1_2
675    // If the .set directive is supported, this is emitted as:
676    //      .set L4_5_set_123, LBB123 - LJTI1_2
677    //      .word L4_5_set_123
678
679    // If we have emitted set directives for the jump table entries, print
680    // them rather than the entries themselves.  If we're emitting PIC, then
681    // emit the table entries as differences between two text section labels.
682    if (MAI->hasSetDirective()) {
683      // If we used .set, reference the .set's symbol.
684      Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
685                                      OutContext);
686      break;
687    }
688    // Otherwise, use the difference as the jump table entry.
689    Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
690    const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
691    Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
692    break;
693  }
694  }
695
696  assert(Value && "Unknown entry kind!");
697
698  unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
699  OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
700}
701
702
703/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
704/// special global used by LLVM.  If so, emit it and return true, otherwise
705/// do nothing and return false.
706bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
707  if (GV->getName() == "llvm.used") {
708    if (MAI->hasNoDeadStrip())    // No need to emit this at all.
709      EmitLLVMUsedList(GV->getInitializer());
710    return true;
711  }
712
713  // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
714  if (GV->getSection() == "llvm.metadata" ||
715      GV->hasAvailableExternallyLinkage())
716    return true;
717
718  if (!GV->hasAppendingLinkage()) return false;
719
720  assert(GV->hasInitializer() && "Not a special LLVM global!");
721
722  const TargetData *TD = TM.getTargetData();
723  unsigned Align = Log2_32(TD->getPointerPrefAlignment());
724  if (GV->getName() == "llvm.global_ctors") {
725    OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
726    EmitAlignment(Align, 0);
727    EmitXXStructorList(GV->getInitializer());
728
729    if (TM.getRelocationModel() == Reloc::Static &&
730        MAI->hasStaticCtorDtorReferenceInStaticMode()) {
731      StringRef Sym(".constructors_used");
732      OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
733                                      MCSA_Reference);
734    }
735    return true;
736  }
737
738  if (GV->getName() == "llvm.global_dtors") {
739    OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
740    EmitAlignment(Align, 0);
741    EmitXXStructorList(GV->getInitializer());
742
743    if (TM.getRelocationModel() == Reloc::Static &&
744        MAI->hasStaticCtorDtorReferenceInStaticMode()) {
745      StringRef Sym(".destructors_used");
746      OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
747                                      MCSA_Reference);
748    }
749    return true;
750  }
751
752  return false;
753}
754
755/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
756/// global in the specified llvm.used list for which emitUsedDirectiveFor
757/// is true, as being used with this directive.
758void AsmPrinter::EmitLLVMUsedList(Constant *List) {
759  // Should be an array of 'i8*'.
760  ConstantArray *InitList = dyn_cast<ConstantArray>(List);
761  if (InitList == 0) return;
762
763  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
764    const GlobalValue *GV =
765      dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
766    if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
767      OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
768                                      MCSA_NoDeadStrip);
769  }
770}
771
772/// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the
773/// function pointers, ignoring the init priority.
774void AsmPrinter::EmitXXStructorList(Constant *List) {
775  // Should be an array of '{ int, void ()* }' structs.  The first value is the
776  // init priority, which we ignore.
777  if (!isa<ConstantArray>(List)) return;
778  ConstantArray *InitList = cast<ConstantArray>(List);
779  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
780    if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
781      if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
782
783      if (CS->getOperand(1)->isNullValue())
784        return;  // Found a null terminator, exit printing.
785      // Emit the function pointer.
786      EmitGlobalConstant(CS->getOperand(1));
787    }
788}
789
790//===--------------------------------------------------------------------===//
791// Emission and print routines
792//
793
794/// EmitInt8 - Emit a byte directive and value.
795///
796void AsmPrinter::EmitInt8(int Value) const {
797  OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
798}
799
800/// EmitInt16 - Emit a short directive and value.
801///
802void AsmPrinter::EmitInt16(int Value) const {
803  OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
804}
805
806/// EmitInt32 - Emit a long directive and value.
807///
808void AsmPrinter::EmitInt32(int Value) const {
809  OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
810}
811
812/// EmitInt64 - Emit a long long directive and value.
813///
814void AsmPrinter::EmitInt64(uint64_t Value) const {
815  OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
816}
817
818//===----------------------------------------------------------------------===//
819
820// EmitAlignment - Emit an alignment directive to the specified power of
821// two boundary.  For example, if you pass in 3 here, you will get an 8
822// byte alignment.  If a global value is specified, and if that global has
823// an explicit alignment requested, it will unconditionally override the
824// alignment request.  However, if ForcedAlignBits is specified, this value
825// has final say: the ultimate alignment will be the max of ForcedAlignBits
826// and the alignment computed with NumBits and the global.
827//
828// The algorithm is:
829//     Align = NumBits;
830//     if (GV && GV->hasalignment) Align = GV->getalignment();
831//     Align = std::max(Align, ForcedAlignBits);
832//
833void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
834                               unsigned ForcedAlignBits,
835                               bool UseFillExpr) const {
836  if (GV && GV->getAlignment())
837    NumBits = Log2_32(GV->getAlignment());
838  NumBits = std::max(NumBits, ForcedAlignBits);
839
840  if (NumBits == 0) return;   // No need to emit alignment.
841
842  unsigned FillValue = 0;
843  if (getCurrentSection()->getKind().isText())
844    FillValue = MAI->getTextAlignFillValue();
845
846  OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
847}
848
849/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
850///
851static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
852  MCContext &Ctx = AP.OutContext;
853
854  if (CV->isNullValue() || isa<UndefValue>(CV))
855    return MCConstantExpr::Create(0, Ctx);
856
857  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
858    return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
859
860  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
861    return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
862  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
863    return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
864
865  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
866  if (CE == 0) {
867    llvm_unreachable("Unknown constant value to lower!");
868    return MCConstantExpr::Create(0, Ctx);
869  }
870
871  switch (CE->getOpcode()) {
872  case Instruction::ZExt:
873  case Instruction::SExt:
874  case Instruction::FPTrunc:
875  case Instruction::FPExt:
876  case Instruction::UIToFP:
877  case Instruction::SIToFP:
878  case Instruction::FPToUI:
879  case Instruction::FPToSI:
880  default: llvm_unreachable("FIXME: Don't support this constant cast expr");
881  case Instruction::GetElementPtr: {
882    const TargetData &TD = *AP.TM.getTargetData();
883    // Generate a symbolic expression for the byte address
884    const Constant *PtrVal = CE->getOperand(0);
885    SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
886    int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
887                                         IdxVec.size());
888
889    const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
890    if (Offset == 0)
891      return Base;
892
893    // Truncate/sext the offset to the pointer size.
894    if (TD.getPointerSizeInBits() != 64) {
895      int SExtAmount = 64-TD.getPointerSizeInBits();
896      Offset = (Offset << SExtAmount) >> SExtAmount;
897    }
898
899    return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
900                                   Ctx);
901  }
902
903  case Instruction::Trunc:
904    // We emit the value and depend on the assembler to truncate the generated
905    // expression properly.  This is important for differences between
906    // blockaddress labels.  Since the two labels are in the same function, it
907    // is reasonable to treat their delta as a 32-bit value.
908    // FALL THROUGH.
909  case Instruction::BitCast:
910    return LowerConstant(CE->getOperand(0), AP);
911
912  case Instruction::IntToPtr: {
913    const TargetData &TD = *AP.TM.getTargetData();
914    // Handle casts to pointers by changing them into casts to the appropriate
915    // integer type.  This promotes constant folding and simplifies this code.
916    Constant *Op = CE->getOperand(0);
917    Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
918                                      false/*ZExt*/);
919    return LowerConstant(Op, AP);
920  }
921
922  case Instruction::PtrToInt: {
923    const TargetData &TD = *AP.TM.getTargetData();
924    // Support only foldable casts to/from pointers that can be eliminated by
925    // changing the pointer to the appropriately sized integer type.
926    Constant *Op = CE->getOperand(0);
927    const Type *Ty = CE->getType();
928
929    const MCExpr *OpExpr = LowerConstant(Op, AP);
930
931    // We can emit the pointer value into this slot if the slot is an
932    // integer slot equal to the size of the pointer.
933    if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
934      return OpExpr;
935
936    // Otherwise the pointer is smaller than the resultant integer, mask off
937    // the high bits so we are sure to get a proper truncation if the input is
938    // a constant expr.
939    unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
940    const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
941    return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
942  }
943
944  case Instruction::Add:
945  case Instruction::Sub:
946  case Instruction::And:
947  case Instruction::Or:
948  case Instruction::Xor: {
949    const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
950    const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
951    switch (CE->getOpcode()) {
952    default: llvm_unreachable("Unknown binary operator constant cast expr");
953    case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
954    case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
955    case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
956    case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
957    case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
958    }
959  }
960  }
961}
962
963static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
964                                    AsmPrinter &AP) {
965  if (AddrSpace != 0 || !CA->isString()) {
966    // Not a string.  Print the values in successive locations
967    for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
968      AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
969    return;
970  }
971
972  // Otherwise, it can be emitted as .ascii.
973  SmallVector<char, 128> TmpVec;
974  TmpVec.reserve(CA->getNumOperands());
975  for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
976    TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
977
978  AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
979}
980
981static void EmitGlobalConstantVector(const ConstantVector *CV,
982                                     unsigned AddrSpace, AsmPrinter &AP) {
983  for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
984    AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
985}
986
987static void EmitGlobalConstantStruct(const ConstantStruct *CS,
988                                     unsigned AddrSpace, AsmPrinter &AP) {
989  // Print the fields in successive locations. Pad to align if needed!
990  const TargetData *TD = AP.TM.getTargetData();
991  unsigned Size = TD->getTypeAllocSize(CS->getType());
992  const StructLayout *Layout = TD->getStructLayout(CS->getType());
993  uint64_t SizeSoFar = 0;
994  for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
995    const Constant *Field = CS->getOperand(i);
996
997    // Check if padding is needed and insert one or more 0s.
998    uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
999    uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1000                        - Layout->getElementOffset(i)) - FieldSize;
1001    SizeSoFar += FieldSize + PadSize;
1002
1003    // Now print the actual field value.
1004    AP.EmitGlobalConstant(Field, AddrSpace);
1005
1006    // Insert padding - this may include padding to increase the size of the
1007    // current field up to the ABI size (if the struct is not packed) as well
1008    // as padding to ensure that the next field starts at the right offset.
1009    AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1010  }
1011  assert(SizeSoFar == Layout->getSizeInBytes() &&
1012         "Layout of constant struct may be incorrect!");
1013}
1014
1015static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1016                                 AsmPrinter &AP) {
1017  // FP Constants are printed as integer constants to avoid losing
1018  // precision.
1019  if (CFP->getType()->isDoubleTy()) {
1020    if (AP.VerboseAsm) {
1021      double Val = CFP->getValueAPF().convertToDouble();
1022      AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1023    }
1024
1025    uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1026    AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1027    return;
1028  }
1029
1030  if (CFP->getType()->isFloatTy()) {
1031    if (AP.VerboseAsm) {
1032      float Val = CFP->getValueAPF().convertToFloat();
1033      AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1034    }
1035    uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1036    AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1037    return;
1038  }
1039
1040  if (CFP->getType()->isX86_FP80Ty()) {
1041    // all long double variants are printed as hex
1042    // api needed to prevent premature destruction
1043    APInt API = CFP->getValueAPF().bitcastToAPInt();
1044    const uint64_t *p = API.getRawData();
1045    if (AP.VerboseAsm) {
1046      // Convert to double so we can print the approximate val as a comment.
1047      APFloat DoubleVal = CFP->getValueAPF();
1048      bool ignored;
1049      DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1050                        &ignored);
1051      AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1052        << DoubleVal.convertToDouble() << '\n';
1053    }
1054
1055    if (AP.TM.getTargetData()->isBigEndian()) {
1056      AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1057      AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1058    } else {
1059      AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1060      AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1061    }
1062
1063    // Emit the tail padding for the long double.
1064    const TargetData &TD = *AP.TM.getTargetData();
1065    AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1066                             TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1067    return;
1068  }
1069
1070  assert(CFP->getType()->isPPC_FP128Ty() &&
1071         "Floating point constant type not handled");
1072  // All long double variants are printed as hex api needed to prevent
1073  // premature destruction.
1074  APInt API = CFP->getValueAPF().bitcastToAPInt();
1075  const uint64_t *p = API.getRawData();
1076  if (AP.TM.getTargetData()->isBigEndian()) {
1077    AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1078    AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1079  } else {
1080    AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1081    AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1082  }
1083}
1084
1085static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1086                                       unsigned AddrSpace, AsmPrinter &AP) {
1087  const TargetData *TD = AP.TM.getTargetData();
1088  unsigned BitWidth = CI->getBitWidth();
1089  assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1090
1091  // We don't expect assemblers to support integer data directives
1092  // for more than 64 bits, so we emit the data in at most 64-bit
1093  // quantities at a time.
1094  const uint64_t *RawData = CI->getValue().getRawData();
1095  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1096    uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1097    AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1098  }
1099}
1100
1101/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1102void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1103  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1104    uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1105    return OutStreamer.EmitZeros(Size, AddrSpace);
1106  }
1107
1108  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1109    unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1110    switch (Size) {
1111    case 1:
1112    case 2:
1113    case 4:
1114    case 8:
1115      if (VerboseAsm)
1116        OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1117      OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1118      return;
1119    default:
1120      EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1121      return;
1122    }
1123  }
1124
1125  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1126    return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1127
1128  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1129    return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1130
1131  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1132    return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1133
1134  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1135    return EmitGlobalConstantVector(V, AddrSpace, *this);
1136
1137  if (isa<ConstantPointerNull>(CV)) {
1138    unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1139    OutStreamer.EmitIntValue(0, Size, AddrSpace);
1140    return;
1141  }
1142
1143  // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1144  // thread the streamer with EmitValue.
1145  OutStreamer.EmitValue(LowerConstant(CV, *this),
1146                        TM.getTargetData()->getTypeAllocSize(CV->getType()),
1147                        AddrSpace);
1148}
1149
1150void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1151  // Target doesn't support this yet!
1152  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1153}
1154
1155/// PrintSpecial - Print information related to the specified machine instr
1156/// that is independent of the operand, and may be independent of the instr
1157/// itself.  This can be useful for portably encoding the comment character
1158/// or other bits of target-specific knowledge into the asmstrings.  The
1159/// syntax used is ${:comment}.  Targets can override this to add support
1160/// for their own strange codes.
1161void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1162  if (!strcmp(Code, "private")) {
1163    O << MAI->getPrivateGlobalPrefix();
1164  } else if (!strcmp(Code, "comment")) {
1165    if (VerboseAsm)
1166      O << MAI->getCommentString();
1167  } else if (!strcmp(Code, "uid")) {
1168    // Comparing the address of MI isn't sufficient, because machineinstrs may
1169    // be allocated to the same address across functions.
1170    const Function *ThisF = MI->getParent()->getParent()->getFunction();
1171
1172    // If this is a new LastFn instruction, bump the counter.
1173    if (LastMI != MI || LastFn != ThisF) {
1174      ++Counter;
1175      LastMI = MI;
1176      LastFn = ThisF;
1177    }
1178    O << Counter;
1179  } else {
1180    std::string msg;
1181    raw_string_ostream Msg(msg);
1182    Msg << "Unknown special formatter '" << Code
1183         << "' for machine instr: " << *MI;
1184    llvm_report_error(Msg.str());
1185  }
1186}
1187
1188/// processDebugLoc - Processes the debug information of each machine
1189/// instruction's DebugLoc.
1190void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1191                                 bool BeforePrintingInsn) {
1192  if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1193      || !DW->ShouldEmitDwarfDebug())
1194    return;
1195  DebugLoc DL = MI->getDebugLoc();
1196  if (DL.isUnknown())
1197    return;
1198  DILocation CurDLT = MF->getDILocation(DL);
1199  if (CurDLT.getScope().isNull())
1200    return;
1201
1202  if (!BeforePrintingInsn) {
1203    // After printing instruction
1204    DW->EndScope(MI);
1205  } else if (CurDLT.getNode() != PrevDLT) {
1206    unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1207                                      CurDLT.getColumnNumber(),
1208                                      CurDLT.getScope().getNode());
1209    printLabel(L);
1210    O << '\n';
1211    DW->BeginScope(MI, L);
1212    PrevDLT = CurDLT.getNode();
1213  }
1214}
1215
1216
1217/// printInlineAsm - This method formats and prints the specified machine
1218/// instruction that is an inline asm.
1219void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1220  unsigned NumOperands = MI->getNumOperands();
1221
1222  // Count the number of register definitions.
1223  unsigned NumDefs = 0;
1224  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1225       ++NumDefs)
1226    assert(NumDefs != NumOperands-1 && "No asm string?");
1227
1228  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1229
1230  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1231  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1232
1233  O << '\t';
1234
1235  // If this asmstr is empty, just print the #APP/#NOAPP markers.
1236  // These are useful to see where empty asm's wound up.
1237  if (AsmStr[0] == 0) {
1238    O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1239    O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1240    return;
1241  }
1242
1243  O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1244
1245  // The variant of the current asmprinter.
1246  int AsmPrinterVariant = MAI->getAssemblerDialect();
1247
1248  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1249  const char *LastEmitted = AsmStr; // One past the last character emitted.
1250
1251  while (*LastEmitted) {
1252    switch (*LastEmitted) {
1253    default: {
1254      // Not a special case, emit the string section literally.
1255      const char *LiteralEnd = LastEmitted+1;
1256      while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1257             *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1258        ++LiteralEnd;
1259      if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1260        O.write(LastEmitted, LiteralEnd-LastEmitted);
1261      LastEmitted = LiteralEnd;
1262      break;
1263    }
1264    case '\n':
1265      ++LastEmitted;   // Consume newline character.
1266      O << '\n';       // Indent code with newline.
1267      break;
1268    case '$': {
1269      ++LastEmitted;   // Consume '$' character.
1270      bool Done = true;
1271
1272      // Handle escapes.
1273      switch (*LastEmitted) {
1274      default: Done = false; break;
1275      case '$':     // $$ -> $
1276        if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1277          O << '$';
1278        ++LastEmitted;  // Consume second '$' character.
1279        break;
1280      case '(':             // $( -> same as GCC's { character.
1281        ++LastEmitted;      // Consume '(' character.
1282        if (CurVariant != -1) {
1283          llvm_report_error("Nested variants found in inline asm string: '"
1284                            + std::string(AsmStr) + "'");
1285        }
1286        CurVariant = 0;     // We're in the first variant now.
1287        break;
1288      case '|':
1289        ++LastEmitted;  // consume '|' character.
1290        if (CurVariant == -1)
1291          O << '|';       // this is gcc's behavior for | outside a variant
1292        else
1293          ++CurVariant;   // We're in the next variant.
1294        break;
1295      case ')':         // $) -> same as GCC's } char.
1296        ++LastEmitted;  // consume ')' character.
1297        if (CurVariant == -1)
1298          O << '}';     // this is gcc's behavior for } outside a variant
1299        else
1300          CurVariant = -1;
1301        break;
1302      }
1303      if (Done) break;
1304
1305      bool HasCurlyBraces = false;
1306      if (*LastEmitted == '{') {     // ${variable}
1307        ++LastEmitted;               // Consume '{' character.
1308        HasCurlyBraces = true;
1309      }
1310
1311      // If we have ${:foo}, then this is not a real operand reference, it is a
1312      // "magic" string reference, just like in .td files.  Arrange to call
1313      // PrintSpecial.
1314      if (HasCurlyBraces && *LastEmitted == ':') {
1315        ++LastEmitted;
1316        const char *StrStart = LastEmitted;
1317        const char *StrEnd = strchr(StrStart, '}');
1318        if (StrEnd == 0) {
1319          llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1320                            + std::string(AsmStr) + "'");
1321        }
1322
1323        std::string Val(StrStart, StrEnd);
1324        PrintSpecial(MI, Val.c_str());
1325        LastEmitted = StrEnd+1;
1326        break;
1327      }
1328
1329      const char *IDStart = LastEmitted;
1330      char *IDEnd;
1331      errno = 0;
1332      long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1333      if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1334        llvm_report_error("Bad $ operand number in inline asm string: '"
1335                          + std::string(AsmStr) + "'");
1336      }
1337      LastEmitted = IDEnd;
1338
1339      char Modifier[2] = { 0, 0 };
1340
1341      if (HasCurlyBraces) {
1342        // If we have curly braces, check for a modifier character.  This
1343        // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1344        if (*LastEmitted == ':') {
1345          ++LastEmitted;    // Consume ':' character.
1346          if (*LastEmitted == 0) {
1347            llvm_report_error("Bad ${:} expression in inline asm string: '"
1348                              + std::string(AsmStr) + "'");
1349          }
1350
1351          Modifier[0] = *LastEmitted;
1352          ++LastEmitted;    // Consume modifier character.
1353        }
1354
1355        if (*LastEmitted != '}') {
1356          llvm_report_error("Bad ${} expression in inline asm string: '"
1357                            + std::string(AsmStr) + "'");
1358        }
1359        ++LastEmitted;    // Consume '}' character.
1360      }
1361
1362      if ((unsigned)Val >= NumOperands-1) {
1363        llvm_report_error("Invalid $ operand number in inline asm string: '"
1364                          + std::string(AsmStr) + "'");
1365      }
1366
1367      // Okay, we finally have a value number.  Ask the target to print this
1368      // operand!
1369      if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1370        unsigned OpNo = 1;
1371
1372        bool Error = false;
1373
1374        // Scan to find the machine operand number for the operand.
1375        for (; Val; --Val) {
1376          if (OpNo >= MI->getNumOperands()) break;
1377          unsigned OpFlags = MI->getOperand(OpNo).getImm();
1378          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1379        }
1380
1381        if (OpNo >= MI->getNumOperands()) {
1382          Error = true;
1383        } else {
1384          unsigned OpFlags = MI->getOperand(OpNo).getImm();
1385          ++OpNo;  // Skip over the ID number.
1386
1387          if (Modifier[0] == 'l')  // labels are target independent
1388            O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1389          else {
1390            AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1391            if ((OpFlags & 7) == 4) {
1392              Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1393                                                Modifier[0] ? Modifier : 0);
1394            } else {
1395              Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1396                                          Modifier[0] ? Modifier : 0);
1397            }
1398          }
1399        }
1400        if (Error) {
1401          std::string msg;
1402          raw_string_ostream Msg(msg);
1403          Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1404          MI->print(Msg);
1405          llvm_report_error(Msg.str());
1406        }
1407      }
1408      break;
1409    }
1410    }
1411  }
1412  O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1413}
1414
1415/// printImplicitDef - This method prints the specified machine instruction
1416/// that is an implicit def.
1417void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1418  if (!VerboseAsm) return;
1419  O.PadToColumn(MAI->getCommentColumn());
1420  O << MAI->getCommentString() << " implicit-def: "
1421    << TRI->getName(MI->getOperand(0).getReg());
1422}
1423
1424void AsmPrinter::printKill(const MachineInstr *MI) const {
1425  if (!VerboseAsm) return;
1426  O.PadToColumn(MAI->getCommentColumn());
1427  O << MAI->getCommentString() << " kill:";
1428  for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1429    const MachineOperand &op = MI->getOperand(n);
1430    assert(op.isReg() && "KILL instruction must have only register operands");
1431    O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1432  }
1433}
1434
1435/// printLabel - This method prints a local label used by debug and
1436/// exception handling tables.
1437void AsmPrinter::printLabel(const MachineInstr *MI) const {
1438  printLabel(MI->getOperand(0).getImm());
1439}
1440
1441void AsmPrinter::printLabel(unsigned Id) const {
1442  O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1443}
1444
1445/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1446/// instruction, using the specified assembler variant.  Targets should
1447/// override this to format as appropriate.
1448bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1449                                 unsigned AsmVariant, const char *ExtraCode) {
1450  // Target doesn't support this yet!
1451  return true;
1452}
1453
1454bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1455                                       unsigned AsmVariant,
1456                                       const char *ExtraCode) {
1457  // Target doesn't support this yet!
1458  return true;
1459}
1460
1461MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1462                                            const char *Suffix) const {
1463  return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1464}
1465
1466MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1467                                            const BasicBlock *BB,
1468                                            const char *Suffix) const {
1469  assert(BB->hasName() &&
1470         "Address of anonymous basic block not supported yet!");
1471
1472  // This code must use the function name itself, and not the function number,
1473  // since it must be possible to generate the label name from within other
1474  // functions.
1475  SmallString<60> FnName;
1476  Mang->getNameWithPrefix(FnName, F, false);
1477
1478  // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1479  SmallString<60> NameResult;
1480  Mang->getNameWithPrefix(NameResult,
1481                          StringRef("BA") + Twine((unsigned)FnName.size()) +
1482                          "_" + FnName.str() + "_" + BB->getName() + Suffix,
1483                          Mangler::Private);
1484
1485  return OutContext.GetOrCreateSymbol(NameResult.str());
1486}
1487
1488/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1489MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1490  SmallString<60> Name;
1491  raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1492    << getFunctionNumber() << '_' << CPID;
1493  return OutContext.GetOrCreateSymbol(Name.str());
1494}
1495
1496/// GetJTISymbol - Return the symbol for the specified jump table entry.
1497MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1498  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1499}
1500
1501/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1502/// FIXME: privatize to AsmPrinter.
1503MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1504  SmallString<60> Name;
1505  raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1506    << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1507  return OutContext.GetOrCreateSymbol(Name.str());
1508}
1509
1510/// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1511/// value.
1512MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1513  SmallString<60> NameStr;
1514  Mang->getNameWithPrefix(NameStr, GV, false);
1515  return OutContext.GetOrCreateSymbol(NameStr.str());
1516}
1517
1518/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1519/// global value name as its base, with the specified suffix, and where the
1520/// symbol is forced to have private linkage if ForcePrivate is true.
1521MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1522                                                   StringRef Suffix,
1523                                                   bool ForcePrivate) const {
1524  SmallString<60> NameStr;
1525  Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1526  NameStr.append(Suffix.begin(), Suffix.end());
1527  return OutContext.GetOrCreateSymbol(NameStr.str());
1528}
1529
1530/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1531/// ExternalSymbol.
1532MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1533  SmallString<60> NameStr;
1534  Mang->getNameWithPrefix(NameStr, Sym);
1535  return OutContext.GetOrCreateSymbol(NameStr.str());
1536}
1537
1538
1539
1540/// PrintParentLoopComment - Print comments about parent loops of this one.
1541static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1542                                   unsigned FunctionNumber) {
1543  if (Loop == 0) return;
1544  PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1545  OS.indent(Loop->getLoopDepth()*2)
1546    << "Parent Loop BB" << FunctionNumber << "_"
1547    << Loop->getHeader()->getNumber()
1548    << " Depth=" << Loop->getLoopDepth() << '\n';
1549}
1550
1551
1552/// PrintChildLoopComment - Print comments about child loops within
1553/// the loop for this basic block, with nesting.
1554static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1555                                  unsigned FunctionNumber) {
1556  // Add child loop information
1557  for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1558    OS.indent((*CL)->getLoopDepth()*2)
1559      << "Child Loop BB" << FunctionNumber << "_"
1560      << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1561      << '\n';
1562    PrintChildLoopComment(OS, *CL, FunctionNumber);
1563  }
1564}
1565
1566/// EmitComments - Pretty-print comments for basic blocks.
1567static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1568                                        const MachineLoopInfo *LI,
1569                                        const AsmPrinter &AP) {
1570  // Add loop depth information
1571  const MachineLoop *Loop = LI->getLoopFor(&MBB);
1572  if (Loop == 0) return;
1573
1574  MachineBasicBlock *Header = Loop->getHeader();
1575  assert(Header && "No header for loop");
1576
1577  // If this block is not a loop header, just print out what is the loop header
1578  // and return.
1579  if (Header != &MBB) {
1580    AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1581                              Twine(AP.getFunctionNumber())+"_" +
1582                              Twine(Loop->getHeader()->getNumber())+
1583                              " Depth="+Twine(Loop->getLoopDepth()));
1584    return;
1585  }
1586
1587  // Otherwise, it is a loop header.  Print out information about child and
1588  // parent loops.
1589  raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1590
1591  PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1592
1593  OS << "=>";
1594  OS.indent(Loop->getLoopDepth()*2-2);
1595
1596  OS << "This ";
1597  if (Loop->empty())
1598    OS << "Inner ";
1599  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1600
1601  PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1602}
1603
1604
1605/// EmitBasicBlockStart - This method prints the label for the specified
1606/// MachineBasicBlock, an alignment (if present) and a comment describing
1607/// it if appropriate.
1608void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1609  // Emit an alignment directive for this block, if needed.
1610  if (unsigned Align = MBB->getAlignment())
1611    EmitAlignment(Log2_32(Align));
1612
1613  // If the block has its address taken, emit a special label to satisfy
1614  // references to the block. This is done so that we don't need to
1615  // remember the number of this label, and so that we can make
1616  // forward references to labels without knowing what their numbers
1617  // will be.
1618  if (MBB->hasAddressTaken()) {
1619    const BasicBlock *BB = MBB->getBasicBlock();
1620    if (VerboseAsm)
1621      OutStreamer.AddComment("Address Taken");
1622    OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1623  }
1624
1625  // Print the main label for the block.
1626  if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1627    if (VerboseAsm) {
1628      // NOTE: Want this comment at start of line.
1629      O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1630      if (const BasicBlock *BB = MBB->getBasicBlock())
1631        if (BB->hasName())
1632          OutStreamer.AddComment("%" + BB->getName());
1633
1634      PrintBasicBlockLoopComments(*MBB, LI, *this);
1635      OutStreamer.AddBlankLine();
1636    }
1637  } else {
1638    if (VerboseAsm) {
1639      if (const BasicBlock *BB = MBB->getBasicBlock())
1640        if (BB->hasName())
1641          OutStreamer.AddComment("%" + BB->getName());
1642      PrintBasicBlockLoopComments(*MBB, LI, *this);
1643    }
1644
1645    OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1646  }
1647}
1648
1649void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1650  MCSymbolAttr Attr = MCSA_Invalid;
1651
1652  switch (Visibility) {
1653  default: break;
1654  case GlobalValue::HiddenVisibility:
1655    Attr = MAI->getHiddenVisibilityAttr();
1656    break;
1657  case GlobalValue::ProtectedVisibility:
1658    Attr = MAI->getProtectedVisibilityAttr();
1659    break;
1660  }
1661
1662  if (Attr != MCSA_Invalid)
1663    OutStreamer.EmitSymbolAttribute(Sym, Attr);
1664}
1665
1666void AsmPrinter::printOffset(int64_t Offset) const {
1667  if (Offset > 0)
1668    O << '+' << Offset;
1669  else if (Offset < 0)
1670    O << Offset;
1671}
1672
1673GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1674  if (!S->usesMetadata())
1675    return 0;
1676
1677  gcp_iterator GCPI = GCMetadataPrinters.find(S);
1678  if (GCPI != GCMetadataPrinters.end())
1679    return GCPI->second;
1680
1681  const char *Name = S->getName().c_str();
1682
1683  for (GCMetadataPrinterRegistry::iterator
1684         I = GCMetadataPrinterRegistry::begin(),
1685         E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1686    if (strcmp(Name, I->getName()) == 0) {
1687      GCMetadataPrinter *GMP = I->instantiate();
1688      GMP->S = S;
1689      GCMetadataPrinters.insert(std::make_pair(S, GMP));
1690      return GMP;
1691    }
1692
1693  llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1694  return 0;
1695}
1696
1697/// EmitComments - Pretty-print comments for instructions
1698void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1699  if (!VerboseAsm)
1700    return;
1701
1702  bool Newline = false;
1703
1704  if (!MI.getDebugLoc().isUnknown()) {
1705    DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1706
1707    // Print source line info.
1708    O.PadToColumn(MAI->getCommentColumn());
1709    O << MAI->getCommentString() << ' ';
1710    DIScope Scope = DLT.getScope();
1711    // Omit the directory, because it's likely to be long and uninteresting.
1712    if (!Scope.isNull())
1713      O << Scope.getFilename();
1714    else
1715      O << "<unknown>";
1716    O << ':' << DLT.getLineNumber();
1717    if (DLT.getColumnNumber() != 0)
1718      O << ':' << DLT.getColumnNumber();
1719    Newline = true;
1720  }
1721
1722  // Check for spills and reloads
1723  int FI;
1724
1725  const MachineFrameInfo *FrameInfo =
1726    MI.getParent()->getParent()->getFrameInfo();
1727
1728  // We assume a single instruction only has a spill or reload, not
1729  // both.
1730  const MachineMemOperand *MMO;
1731  if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1732    if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1733      MMO = *MI.memoperands_begin();
1734      if (Newline) O << '\n';
1735      O.PadToColumn(MAI->getCommentColumn());
1736      O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1737      Newline = true;
1738    }
1739  }
1740  else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1741    if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1742      if (Newline) O << '\n';
1743      O.PadToColumn(MAI->getCommentColumn());
1744      O << MAI->getCommentString() << ' '
1745        << MMO->getSize() << "-byte Folded Reload";
1746      Newline = true;
1747    }
1748  }
1749  else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1750    if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1751      MMO = *MI.memoperands_begin();
1752      if (Newline) O << '\n';
1753      O.PadToColumn(MAI->getCommentColumn());
1754      O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1755      Newline = true;
1756    }
1757  }
1758  else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1759    if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1760      if (Newline) O << '\n';
1761      O.PadToColumn(MAI->getCommentColumn());
1762      O << MAI->getCommentString() << ' '
1763        << MMO->getSize() << "-byte Folded Spill";
1764      Newline = true;
1765    }
1766  }
1767
1768  // Check for spill-induced copies
1769  unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1770  if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1771                                      SrcSubIdx, DstSubIdx)) {
1772    if (MI.getAsmPrinterFlag(ReloadReuse)) {
1773      if (Newline) O << '\n';
1774      O.PadToColumn(MAI->getCommentColumn());
1775      O << MAI->getCommentString() << " Reload Reuse";
1776    }
1777  }
1778}
1779
1780