OSDN Git Service

Merge upstream to r134306 at Sat. 2nd July 2011.
[android-x86/external-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
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 #ifndef ANDROID_TARGET_BUILD
17 #   include "DwarfDebug.h"
18 #   include "DwarfException.h"
19 #endif // ANDROID_TARGET_BUILD
20 #include "llvm/Module.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/ConstantFolding.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Target/Mangler.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Assembly/Writer.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/Timer.h"
51 #include <ctype.h>
52 using namespace llvm;
53
54 static const char *DWARFGroupName = "DWARF Emission";
55 static const char *DbgTimerName = "DWARF Debug Writer";
56 static const char *EHTimerName = "DWARF Exception Writer";
57
58 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59
60 char AsmPrinter::ID = 0;
61
62 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
63 static gcp_map_type &getGCMap(void *&P) {
64   if (P == 0)
65     P = new gcp_map_type();
66   return *(gcp_map_type*)P;
67 }
68
69
70 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
71 /// value in log2 form.  This rounds up to the preferred alignment if possible
72 /// and legal.
73 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
74                                    unsigned InBits = 0) {
75   unsigned NumBits = 0;
76   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77     NumBits = TD.getPreferredAlignmentLog(GVar);
78
79   // If InBits is specified, round it to it.
80   if (InBits > NumBits)
81     NumBits = InBits;
82
83   // If the GV has a specified alignment, take it into account.
84   if (GV->getAlignment() == 0)
85     return NumBits;
86
87   unsigned GVAlign = Log2_32(GV->getAlignment());
88
89   // If the GVAlign is larger than NumBits, or if we are required to obey
90   // NumBits because the GV has an assigned section, obey it.
91   if (GVAlign > NumBits || GV->hasSection())
92     NumBits = GVAlign;
93   return NumBits;
94 }
95
96
97
98
99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
100   : MachineFunctionPass(ID),
101     TM(tm), MAI(tm.getMCAsmInfo()),
102     OutContext(Streamer.getContext()),
103     OutStreamer(Streamer),
104     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
105   DD = 0; DE = 0; MMI = 0; LI = 0;
106   GCMetadataPrinters = 0;
107   VerboseAsm = Streamer.isVerboseAsm();
108 }
109
110 AsmPrinter::~AsmPrinter() {
111   assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
112
113   if (GCMetadataPrinters != 0) {
114     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
115
116     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
117       delete I->second;
118     delete &GCMap;
119     GCMetadataPrinters = 0;
120   }
121
122   delete &OutStreamer;
123 }
124
125 /// getFunctionNumber - Return a unique ID for the current function.
126 ///
127 unsigned AsmPrinter::getFunctionNumber() const {
128   return MF->getFunctionNumber();
129 }
130
131 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
132   return TM.getTargetLowering()->getObjFileLowering();
133 }
134
135
136 /// getTargetData - Return information about data layout.
137 const TargetData &AsmPrinter::getTargetData() const {
138   return *TM.getTargetData();
139 }
140
141 /// getCurrentSection() - Return the current section we are emitting to.
142 const MCSection *AsmPrinter::getCurrentSection() const {
143   return OutStreamer.getCurrentSection();
144 }
145
146
147
148 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
149   AU.setPreservesAll();
150   MachineFunctionPass::getAnalysisUsage(AU);
151   AU.addRequired<MachineModuleInfo>();
152   AU.addRequired<GCModuleInfo>();
153   if (isVerbose())
154     AU.addRequired<MachineLoopInfo>();
155 }
156
157 bool AsmPrinter::doInitialization(Module &M) {
158   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
159   MMI->AnalyzeModule(M);
160
161   // Initialize TargetLoweringObjectFile.
162   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
163     .Initialize(OutContext, TM);
164
165   Mang = new Mangler(OutContext, *TM.getTargetData());
166
167   // Allow the target to emit any magic that it wants at the start of the file.
168   EmitStartOfAsmFile(M);
169
170   // Very minimal debug info. It is ignored if we emit actual debug info. If we
171   // don't, this at least helps the user find where a global came from.
172   if (MAI->hasSingleParameterDotFile()) {
173     // .file "foo.c"
174     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
175   }
176
177   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
178   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
179   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
180     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
181       MP->beginAssembly(*this);
182
183   // Emit module-level inline asm if it exists.
184   if (!M.getModuleInlineAsm().empty()) {
185     OutStreamer.AddComment("Start of file scope inline assembly");
186     OutStreamer.AddBlankLine();
187     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
188     OutStreamer.AddComment("End of file scope inline assembly");
189     OutStreamer.AddBlankLine();
190   }
191
192 #ifndef ANDROID_TARGET_BUILD
193   if (MAI->doesSupportDebugInformation())
194     DD = new DwarfDebug(this, &M);
195
196   switch (MAI->getExceptionHandlingType()) {
197   case ExceptionHandling::None:
198     return false;
199   case ExceptionHandling::SjLj:
200   case ExceptionHandling::DwarfCFI:
201     DE = new DwarfCFIException(this);
202     return false;
203   case ExceptionHandling::ARM:
204     DE = new ARMException(this);
205     return false;
206   case ExceptionHandling::Win64:
207     DE = new Win64Exception(this);
208     return false;
209   }
210 #else
211   return false;
212 #endif // ANDROID_TARGET_BUILD
213
214   llvm_unreachable("Unknown exception type.");
215 }
216
217 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
218   switch ((GlobalValue::LinkageTypes)Linkage) {
219   case GlobalValue::CommonLinkage:
220   case GlobalValue::LinkOnceAnyLinkage:
221   case GlobalValue::LinkOnceODRLinkage:
222   case GlobalValue::WeakAnyLinkage:
223   case GlobalValue::WeakODRLinkage:
224   case GlobalValue::LinkerPrivateWeakLinkage:
225   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
226     if (MAI->getWeakDefDirective() != 0) {
227       // .globl _foo
228       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229
230       if ((GlobalValue::LinkageTypes)Linkage !=
231           GlobalValue::LinkerPrivateWeakDefAutoLinkage)
232         // .weak_definition _foo
233         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
234       else
235         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
236     } else if (MAI->getLinkOnceDirective() != 0) {
237       // .globl _foo
238       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
239       //NOTE: linkonce is handled by the section the symbol was assigned to.
240     } else {
241       // .weak _foo
242       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
243     }
244     break;
245   case GlobalValue::DLLExportLinkage:
246   case GlobalValue::AppendingLinkage:
247     // FIXME: appending linkage variables should go into a section of
248     // their name or something.  For now, just emit them as external.
249   case GlobalValue::ExternalLinkage:
250     // If external or appending, declare as a global symbol.
251     // .globl _foo
252     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
253     break;
254   case GlobalValue::PrivateLinkage:
255   case GlobalValue::InternalLinkage:
256   case GlobalValue::LinkerPrivateLinkage:
257     break;
258   default:
259     llvm_unreachable("Unknown linkage type!");
260   }
261 }
262
263
264 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
265 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
266   if (GV->hasInitializer()) {
267     // Check to see if this is a special global used by LLVM, if so, emit it.
268     if (EmitSpecialLLVMGlobal(GV))
269       return;
270
271     if (isVerbose()) {
272       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
273                      /*PrintType=*/false, GV->getParent());
274       OutStreamer.GetCommentOS() << '\n';
275     }
276   }
277
278   MCSymbol *GVSym = Mang->getSymbol(GV);
279   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
280
281   if (!GV->hasInitializer())   // External globals require no extra code.
282     return;
283
284   if (MAI->hasDotTypeDotSizeDirective())
285     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
286
287   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
288
289   const TargetData *TD = TM.getTargetData();
290   uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
291
292   // If the alignment is specified, we *must* obey it.  Overaligning a global
293   // with a specified alignment is a prompt way to break globals emitted to
294   // sections and expected to be contiguous (e.g. ObjC metadata).
295   unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
296
297   // Handle common and BSS local symbols (.lcomm).
298   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
299     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
300
301     // Handle common symbols.
302     if (GVKind.isCommon()) {
303       unsigned Align = 1 << AlignLog;
304       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
305         Align = 0;
306
307       // .comm _foo, 42, 4
308       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
309       return;
310     }
311
312     // Handle local BSS symbols.
313     if (MAI->hasMachoZeroFillDirective()) {
314       const MCSection *TheSection =
315         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
316       // .zerofill __DATA, __bss, _foo, 400, 5
317       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
318       return;
319     }
320
321     if (MAI->hasLCOMMDirective()) {
322       // .lcomm _foo, 42
323       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
324       return;
325     }
326
327     unsigned Align = 1 << AlignLog;
328     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
329       Align = 0;
330
331     // .local _foo
332     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
333     // .comm _foo, 42, 4
334     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
335     return;
336   }
337
338   const MCSection *TheSection =
339     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
340
341   // Handle the zerofill directive on darwin, which is a special form of BSS
342   // emission.
343   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
344     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
345
346     // .globl _foo
347     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
348     // .zerofill __DATA, __common, _foo, 400, 5
349     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
350     return;
351   }
352
353   // Handle thread local data for mach-o which requires us to output an
354   // additional structure of data and mangle the original symbol so that we
355   // can reference it later.
356   //
357   // TODO: This should become an "emit thread local global" method on TLOF.
358   // All of this macho specific stuff should be sunk down into TLOFMachO and
359   // stuff like "TLSExtraDataSection" should no longer be part of the parent
360   // TLOF class.  This will also make it more obvious that stuff like
361   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
362   // specific code.
363   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
364     // Emit the .tbss symbol
365     MCSymbol *MangSym =
366       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
367
368     if (GVKind.isThreadBSS())
369       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
370     else if (GVKind.isThreadData()) {
371       OutStreamer.SwitchSection(TheSection);
372
373       EmitAlignment(AlignLog, GV);
374       OutStreamer.EmitLabel(MangSym);
375
376       EmitGlobalConstant(GV->getInitializer());
377     }
378
379     OutStreamer.AddBlankLine();
380
381     // Emit the variable struct for the runtime.
382     const MCSection *TLVSect
383       = getObjFileLowering().getTLSExtraDataSection();
384
385     OutStreamer.SwitchSection(TLVSect);
386     // Emit the linkage here.
387     EmitLinkage(GV->getLinkage(), GVSym);
388     OutStreamer.EmitLabel(GVSym);
389
390     // Three pointers in size:
391     //   - __tlv_bootstrap - used to make sure support exists
392     //   - spare pointer, used when mapped by the runtime
393     //   - pointer to mangled symbol above with initializer
394     unsigned PtrSize = TD->getPointerSizeInBits()/8;
395     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
396                           PtrSize, 0);
397     OutStreamer.EmitIntValue(0, PtrSize, 0);
398     OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
399
400     OutStreamer.AddBlankLine();
401     return;
402   }
403
404   OutStreamer.SwitchSection(TheSection);
405
406   EmitLinkage(GV->getLinkage(), GVSym);
407   EmitAlignment(AlignLog, GV);
408
409   OutStreamer.EmitLabel(GVSym);
410
411   EmitGlobalConstant(GV->getInitializer());
412
413   if (MAI->hasDotTypeDotSizeDirective())
414     // .size foo, 42
415     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
416
417   OutStreamer.AddBlankLine();
418 }
419
420 /// EmitFunctionHeader - This method emits the header for the current
421 /// function.
422 void AsmPrinter::EmitFunctionHeader() {
423   // Print out constants referenced by the function
424   EmitConstantPool();
425
426   // Print the 'header' of function.
427   const Function *F = MF->getFunction();
428
429   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
430   EmitVisibility(CurrentFnSym, F->getVisibility());
431
432   EmitLinkage(F->getLinkage(), CurrentFnSym);
433   EmitAlignment(MF->getAlignment(), F);
434
435   if (MAI->hasDotTypeDotSizeDirective())
436     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
437
438   if (isVerbose()) {
439     WriteAsOperand(OutStreamer.GetCommentOS(), F,
440                    /*PrintType=*/false, F->getParent());
441     OutStreamer.GetCommentOS() << '\n';
442   }
443
444   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
445   // do their wild and crazy things as required.
446   EmitFunctionEntryLabel();
447
448   // If the function had address-taken blocks that got deleted, then we have
449   // references to the dangling symbols.  Emit them at the start of the function
450   // so that we don't get references to undefined symbols.
451   std::vector<MCSymbol*> DeadBlockSyms;
452   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
453   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
454     OutStreamer.AddComment("Address taken block that was later removed");
455     OutStreamer.EmitLabel(DeadBlockSyms[i]);
456   }
457
458   // Add some workaround for linkonce linkage on Cygwin\MinGW.
459   if (MAI->getLinkOnceDirective() != 0 &&
460       (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
461     // FIXME: What is this?
462     MCSymbol *FakeStub =
463       OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
464                                    CurrentFnSym->getName());
465     OutStreamer.EmitLabel(FakeStub);
466   }
467
468   // Emit pre-function debug and/or EH information.
469 #ifndef ANDROID_TARGET_BUILD
470   if (DE) {
471     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
472     DE->BeginFunction(MF);
473   }
474   if (DD) {
475     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
476     DD->beginFunction(MF);
477   }
478 #endif // ANDROID_TARGET_BUILD
479 }
480
481 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
482 /// function.  This can be overridden by targets as required to do custom stuff.
483 void AsmPrinter::EmitFunctionEntryLabel() {
484   // The function label could have already been emitted if two symbols end up
485   // conflicting due to asm renaming.  Detect this and emit an error.
486   if (CurrentFnSym->isUndefined())
487     return OutStreamer.EmitLabel(CurrentFnSym);
488
489   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
490                      "' label emitted multiple times to assembly file");
491 }
492
493
494 /// EmitComments - Pretty-print comments for instructions.
495 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
496   const MachineFunction *MF = MI.getParent()->getParent();
497   const TargetMachine &TM = MF->getTarget();
498
499   // Check for spills and reloads
500   int FI;
501
502   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
503
504   // We assume a single instruction only has a spill or reload, not
505   // both.
506   const MachineMemOperand *MMO;
507   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
508     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
509       MMO = *MI.memoperands_begin();
510       CommentOS << MMO->getSize() << "-byte Reload\n";
511     }
512   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
513     if (FrameInfo->isSpillSlotObjectIndex(FI))
514       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
515   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
516     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
517       MMO = *MI.memoperands_begin();
518       CommentOS << MMO->getSize() << "-byte Spill\n";
519     }
520   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
521     if (FrameInfo->isSpillSlotObjectIndex(FI))
522       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
523   }
524
525   // Check for spill-induced copies
526   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
527     CommentOS << " Reload Reuse\n";
528 }
529
530 /// EmitImplicitDef - This method emits the specified machine instruction
531 /// that is an implicit def.
532 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
533   unsigned RegNo = MI->getOperand(0).getReg();
534   AP.OutStreamer.AddComment(Twine("implicit-def: ") +
535                             AP.TM.getRegisterInfo()->getName(RegNo));
536   AP.OutStreamer.AddBlankLine();
537 }
538
539 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
540   std::string Str = "kill:";
541   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
542     const MachineOperand &Op = MI->getOperand(i);
543     assert(Op.isReg() && "KILL instruction must have only register operands");
544     Str += ' ';
545     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
546     Str += (Op.isDef() ? "<def>" : "<kill>");
547   }
548   AP.OutStreamer.AddComment(Str);
549   AP.OutStreamer.AddBlankLine();
550 }
551
552 /// EmitDebugValueComment - This method handles the target-independent form
553 /// of DBG_VALUE, returning true if it was able to do so.  A false return
554 /// means the target will need to handle MI in EmitInstruction.
555 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
556   // This code handles only the 3-operand target-independent form.
557   if (MI->getNumOperands() != 3)
558     return false;
559
560   SmallString<128> Str;
561   raw_svector_ostream OS(Str);
562   OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
563
564   // cast away const; DIetc do not take const operands for some reason.
565   DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
566   if (V.getContext().isSubprogram())
567     OS << DISubprogram(V.getContext()).getDisplayName() << ":";
568   OS << V.getName() << " <- ";
569
570   // Register or immediate value. Register 0 means undef.
571   if (MI->getOperand(0).isFPImm()) {
572     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
573     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
574       OS << (double)APF.convertToFloat();
575     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
576       OS << APF.convertToDouble();
577     } else {
578       // There is no good way to print long double.  Convert a copy to
579       // double.  Ah well, it's only a comment.
580       bool ignored;
581       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
582                   &ignored);
583       OS << "(long double) " << APF.convertToDouble();
584     }
585   } else if (MI->getOperand(0).isImm()) {
586     OS << MI->getOperand(0).getImm();
587   } else if (MI->getOperand(0).isCImm()) {
588     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
589   } else {
590     assert(MI->getOperand(0).isReg() && "Unknown operand type");
591     if (MI->getOperand(0).getReg() == 0) {
592       // Suppress offset, it is not meaningful here.
593       OS << "undef";
594       // NOTE: Want this comment at start of line, don't emit with AddComment.
595       AP.OutStreamer.EmitRawText(OS.str());
596       return true;
597     }
598     OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
599   }
600
601   OS << '+' << MI->getOperand(1).getImm();
602   // NOTE: Want this comment at start of line, don't emit with AddComment.
603   AP.OutStreamer.EmitRawText(OS.str());
604   return true;
605 }
606
607 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
608   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
609       MF->getFunction()->needsUnwindTableEntry())
610     return CFI_M_EH;
611
612   if (MMI->hasDebugInfo())
613     return CFI_M_Debug;
614
615   return CFI_M_None;
616 }
617
618 bool AsmPrinter::needsSEHMoves() {
619   return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
620     MF->getFunction()->needsUnwindTableEntry();
621 }
622
623 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
624   MCSymbol *Label = MI.getOperand(0).getMCSymbol();
625
626   if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
627     return;
628
629   if (needsCFIMoves() == CFI_M_None)
630     return;
631
632   MachineModuleInfo &MMI = MF->getMMI();
633   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
634   bool FoundOne = false;
635   (void)FoundOne;
636   for (std::vector<MachineMove>::iterator I = Moves.begin(),
637          E = Moves.end(); I != E; ++I) {
638     if (I->getLabel() == Label) {
639       EmitCFIFrameMove(*I);
640       FoundOne = true;
641     }
642   }
643   assert(FoundOne);
644 }
645
646 /// EmitFunctionBody - This method emits the body and trailer for a
647 /// function.
648 void AsmPrinter::EmitFunctionBody() {
649   // Emit target-specific gunk before the function body.
650   EmitFunctionBodyStart();
651
652   bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
653
654   // Print out code for the function.
655   bool HasAnyRealCode = false;
656   const MachineInstr *LastMI = 0;
657   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
658        I != E; ++I) {
659     // Print a label for the basic block.
660     EmitBasicBlockStart(I);
661     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
662          II != IE; ++II) {
663       LastMI = II;
664
665       // Print the assembly for the instruction.
666       if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
667           !II->isDebugValue()) {
668         HasAnyRealCode = true;
669       
670         ++EmittedInsts;
671       }
672 #ifndef ANDROID_TARGET_BUILD
673       if (ShouldPrintDebugScopes) {
674         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
675         DD->beginInstruction(II);
676       }
677 #endif // ANDROID_TARGET_BUILD
678       
679       if (isVerbose())
680         EmitComments(*II, OutStreamer.GetCommentOS());
681
682       switch (II->getOpcode()) {
683       case TargetOpcode::PROLOG_LABEL:
684         emitPrologLabel(*II);
685         break;
686
687       case TargetOpcode::EH_LABEL:
688       case TargetOpcode::GC_LABEL:
689         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
690         break;
691       case TargetOpcode::INLINEASM:
692         EmitInlineAsm(II);
693         break;
694       case TargetOpcode::DBG_VALUE:
695         if (isVerbose()) {
696           if (!EmitDebugValueComment(II, *this))
697             EmitInstruction(II);
698         }
699         break;
700       case TargetOpcode::IMPLICIT_DEF:
701         if (isVerbose()) EmitImplicitDef(II, *this);
702         break;
703       case TargetOpcode::KILL:
704         if (isVerbose()) EmitKill(II, *this);
705         break;
706       default:
707         if (!TM.hasMCUseLoc())
708           MCLineEntry::Make(&OutStreamer, getCurrentSection());
709
710         EmitInstruction(II);
711         break;
712       }
713       
714 #ifndef ANDROID_TARGET_BUILD
715       if (ShouldPrintDebugScopes) {
716         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
717         DD->endInstruction(II);
718       }
719 #endif // ANDROID_TARGET_BUILD
720     }
721   }
722
723   // If the last instruction was a prolog label, then we have a situation where
724   // we emitted a prolog but no function body. This results in the ending prolog
725   // label equaling the end of function label and an invalid "row" in the
726   // FDE. We need to emit a noop in this situation so that the FDE's rows are
727   // valid.
728   bool RequiresNoop = LastMI && LastMI->isPrologLabel();
729
730   // If the function is empty and the object file uses .subsections_via_symbols,
731   // then we need to emit *something* to the function body to prevent the
732   // labels from collapsing together.  Just emit a noop.
733   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
734     MCInst Noop;
735     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
736     if (Noop.getOpcode()) {
737       OutStreamer.AddComment("avoids zero-length function");
738       OutStreamer.EmitInstruction(Noop);
739     } else  // Target not mc-ized yet.
740       OutStreamer.EmitRawText(StringRef("\tnop\n"));
741   }
742
743   // Emit target-specific gunk after the function body.
744   EmitFunctionBodyEnd();
745
746   // If the target wants a .size directive for the size of the function, emit
747   // it.
748   if (MAI->hasDotTypeDotSizeDirective()) {
749     // Create a symbol for the end of function, so we can get the size as
750     // difference between the function label and the temp label.
751     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
752     OutStreamer.EmitLabel(FnEndLabel);
753
754     const MCExpr *SizeExp =
755       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
756                               MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
757                               OutContext);
758     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
759   }
760
761   // Emit post-function debug information.
762 #ifndef ANDROID_TARGET_BUILD
763   if (DD) {
764     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
765     DD->endFunction(MF);
766   }
767   if (DE) {
768     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
769     DE->EndFunction();
770   }
771 #endif // ANDROID_TARGET_BUILD
772   MMI->EndFunction();
773
774   // Print out jump tables referenced by the function.
775   EmitJumpTableInfo();
776
777   OutStreamer.AddBlankLine();
778 }
779
780 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
781 /// operands.
782 MachineLocation AsmPrinter::
783 getDebugValueLocation(const MachineInstr *MI) const {
784   // Target specific DBG_VALUE instructions are handled by each target.
785   return MachineLocation();
786 }
787
788 /// EmitDwarfRegOp - Emit dwarf register operation.
789 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
790   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
791   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
792
793   for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
794        *SR && Reg < 0; ++SR) {
795     Reg = TRI->getDwarfRegNum(*SR, false);
796     // FIXME: Get the bit range this register uses of the superregister
797     // so that we can produce a DW_OP_bit_piece
798   }
799
800   // FIXME: Handle cases like a super register being encoded as
801   // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
802
803   // FIXME: We have no reasonable way of handling errors in here. The
804   // caller might be in the middle of an dwarf expression. We should
805   // probably assert that Reg >= 0 once debug info generation is more mature.
806
807   if (int Offset =  MLoc.getOffset()) {
808     if (Reg < 32) {
809       OutStreamer.AddComment(
810         dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
811       EmitInt8(dwarf::DW_OP_breg0 + Reg);
812     } else {
813       OutStreamer.AddComment("DW_OP_bregx");
814       EmitInt8(dwarf::DW_OP_bregx);
815       OutStreamer.AddComment(Twine(Reg));
816       EmitULEB128(Reg);
817     }
818     EmitSLEB128(Offset);
819   } else {
820     if (Reg < 32) {
821       OutStreamer.AddComment(
822         dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
823       EmitInt8(dwarf::DW_OP_reg0 + Reg);
824     } else {
825       OutStreamer.AddComment("DW_OP_regx");
826       EmitInt8(dwarf::DW_OP_regx);
827       OutStreamer.AddComment(Twine(Reg));
828       EmitULEB128(Reg);
829     }
830   }
831
832   // FIXME: Produce a DW_OP_bit_piece if we used a superregister
833 }
834
835 bool AsmPrinter::doFinalization(Module &M) {
836   // Emit global variables.
837   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
838        I != E; ++I)
839     EmitGlobalVariable(I);
840
841   // Emit visibility info for declarations
842   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
843     const Function &F = *I;
844     if (!F.isDeclaration())
845       continue;
846     GlobalValue::VisibilityTypes V = F.getVisibility();
847     if (V == GlobalValue::DefaultVisibility)
848       continue;
849
850     MCSymbol *Name = Mang->getSymbol(&F);
851     EmitVisibility(Name, V, false);
852   }
853
854   // Finalize debug and EH information.
855 #ifndef ANDROID_TARGET_BUILD
856   if (DE) {
857     {
858       NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
859       DE->EndModule();
860     }
861     delete DE; DE = 0;
862   }
863   if (DD) {
864     {
865       NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
866       DD->endModule();
867     }
868     delete DD; DD = 0;
869   }
870 #endif // ANDROID_TARGET_BUILD
871   
872   // If the target wants to know about weak references, print them all.
873   if (MAI->getWeakRefDirective()) {
874     // FIXME: This is not lazy, it would be nice to only print weak references
875     // to stuff that is actually used.  Note that doing so would require targets
876     // to notice uses in operands (due to constant exprs etc).  This should
877     // happen with the MC stuff eventually.
878
879     // Print out module-level global variables here.
880     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
881          I != E; ++I) {
882       if (!I->hasExternalWeakLinkage()) continue;
883       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
884     }
885
886     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
887       if (!I->hasExternalWeakLinkage()) continue;
888       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
889     }
890   }
891
892   if (MAI->hasSetDirective()) {
893     OutStreamer.AddBlankLine();
894     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
895          I != E; ++I) {
896       MCSymbol *Name = Mang->getSymbol(I);
897
898       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
899       MCSymbol *Target = Mang->getSymbol(GV);
900
901       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
902         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
903       else if (I->hasWeakLinkage())
904         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
905       else
906         assert(I->hasLocalLinkage() && "Invalid alias linkage");
907
908       EmitVisibility(Name, I->getVisibility());
909
910       // Emit the directives as assignments aka .set:
911       OutStreamer.EmitAssignment(Name,
912                                  MCSymbolRefExpr::Create(Target, OutContext));
913     }
914   }
915
916   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
917   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
918   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
919     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
920       MP->finishAssembly(*this);
921
922   // If we don't have any trampolines, then we don't require stack memory
923   // to be executable. Some targets have a directive to declare this.
924   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
925   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
926     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
927       OutStreamer.SwitchSection(S);
928
929   // Allow the target to emit any magic that it wants at the end of the file,
930   // after everything else has gone out.
931   EmitEndOfAsmFile(M);
932
933   delete Mang; Mang = 0;
934   MMI = 0;
935
936   OutStreamer.Finish();
937   return false;
938 }
939
940 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
941   this->MF = &MF;
942   // Get the function symbol.
943   CurrentFnSym = Mang->getSymbol(MF.getFunction());
944
945   if (isVerbose())
946     LI = &getAnalysis<MachineLoopInfo>();
947 }
948
949 namespace {
950   // SectionCPs - Keep track the alignment, constpool entries per Section.
951   struct SectionCPs {
952     const MCSection *S;
953     unsigned Alignment;
954     SmallVector<unsigned, 4> CPEs;
955     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
956   };
957 }
958
959 /// EmitConstantPool - Print to the current output stream assembly
960 /// representations of the constants in the constant pool MCP. This is
961 /// used to print out constants which have been "spilled to memory" by
962 /// the code generator.
963 ///
964 void AsmPrinter::EmitConstantPool() {
965   const MachineConstantPool *MCP = MF->getConstantPool();
966   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
967   if (CP.empty()) return;
968
969   // Calculate sections for constant pool entries. We collect entries to go into
970   // the same section together to reduce amount of section switch statements.
971   SmallVector<SectionCPs, 4> CPSections;
972   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
973     const MachineConstantPoolEntry &CPE = CP[i];
974     unsigned Align = CPE.getAlignment();
975
976     SectionKind Kind;
977     switch (CPE.getRelocationInfo()) {
978     default: llvm_unreachable("Unknown section kind");
979     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
980     case 1:
981       Kind = SectionKind::getReadOnlyWithRelLocal();
982       break;
983     case 0:
984     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
985     case 4:  Kind = SectionKind::getMergeableConst4(); break;
986     case 8:  Kind = SectionKind::getMergeableConst8(); break;
987     case 16: Kind = SectionKind::getMergeableConst16();break;
988     default: Kind = SectionKind::getMergeableConst(); break;
989     }
990     }
991
992     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
993
994     // The number of sections are small, just do a linear search from the
995     // last section to the first.
996     bool Found = false;
997     unsigned SecIdx = CPSections.size();
998     while (SecIdx != 0) {
999       if (CPSections[--SecIdx].S == S) {
1000         Found = true;
1001         break;
1002       }
1003     }
1004     if (!Found) {
1005       SecIdx = CPSections.size();
1006       CPSections.push_back(SectionCPs(S, Align));
1007     }
1008
1009     if (Align > CPSections[SecIdx].Alignment)
1010       CPSections[SecIdx].Alignment = Align;
1011     CPSections[SecIdx].CPEs.push_back(i);
1012   }
1013
1014   // Now print stuff into the calculated sections.
1015   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1016     OutStreamer.SwitchSection(CPSections[i].S);
1017     EmitAlignment(Log2_32(CPSections[i].Alignment));
1018
1019     unsigned Offset = 0;
1020     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1021       unsigned CPI = CPSections[i].CPEs[j];
1022       MachineConstantPoolEntry CPE = CP[CPI];
1023
1024       // Emit inter-object padding for alignment.
1025       unsigned AlignMask = CPE.getAlignment() - 1;
1026       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1027       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1028
1029       const Type *Ty = CPE.getType();
1030       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
1031       OutStreamer.EmitLabel(GetCPISymbol(CPI));
1032
1033       if (CPE.isMachineConstantPoolEntry())
1034         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1035       else
1036         EmitGlobalConstant(CPE.Val.ConstVal);
1037     }
1038   }
1039 }
1040
1041 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1042 /// by the current function to the current output stream.
1043 ///
1044 void AsmPrinter::EmitJumpTableInfo() {
1045   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1046   if (MJTI == 0) return;
1047   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1048   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1049   if (JT.empty()) return;
1050
1051   // Pick the directive to use to print the jump table entries, and switch to
1052   // the appropriate section.
1053   const Function *F = MF->getFunction();
1054   bool JTInDiffSection = false;
1055   if (// In PIC mode, we need to emit the jump table to the same section as the
1056       // function body itself, otherwise the label differences won't make sense.
1057       // FIXME: Need a better predicate for this: what about custom entries?
1058       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1059       // We should also do if the section name is NULL or function is declared
1060       // in discardable section
1061       // FIXME: this isn't the right predicate, should be based on the MCSection
1062       // for the function.
1063       F->isWeakForLinker()) {
1064     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1065   } else {
1066     // Otherwise, drop it in the readonly section.
1067     const MCSection *ReadOnlySection =
1068       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1069     OutStreamer.SwitchSection(ReadOnlySection);
1070     JTInDiffSection = true;
1071   }
1072
1073   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1074
1075   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1076     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1077
1078     // If this jump table was deleted, ignore it.
1079     if (JTBBs.empty()) continue;
1080
1081     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1082     // .set directive for each unique entry.  This reduces the number of
1083     // relocations the assembler will generate for the jump table.
1084     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1085         MAI->hasSetDirective()) {
1086       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1087       const TargetLowering *TLI = TM.getTargetLowering();
1088       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1089       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1090         const MachineBasicBlock *MBB = JTBBs[ii];
1091         if (!EmittedSets.insert(MBB)) continue;
1092
1093         // .set LJTSet, LBB32-base
1094         const MCExpr *LHS =
1095           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1096         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1097                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1098       }
1099     }
1100
1101     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1102     // before each jump table.  The first label is never referenced, but tells
1103     // the assembler and linker the extents of the jump table object.  The
1104     // second label is actually referenced by the code.
1105     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1106       // FIXME: This doesn't have to have any specific name, just any randomly
1107       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1108       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1109
1110     OutStreamer.EmitLabel(GetJTISymbol(JTI));
1111
1112     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1113       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1114   }
1115 }
1116
1117 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1118 /// current stream.
1119 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1120                                     const MachineBasicBlock *MBB,
1121                                     unsigned UID) const {
1122   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1123   const MCExpr *Value = 0;
1124   switch (MJTI->getEntryKind()) {
1125   case MachineJumpTableInfo::EK_Inline:
1126     llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1127   case MachineJumpTableInfo::EK_Custom32:
1128     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1129                                                               OutContext);
1130     break;
1131   case MachineJumpTableInfo::EK_BlockAddress:
1132     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1133     //     .word LBB123
1134     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1135     break;
1136   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1137     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1138     // with a relocation as gp-relative, e.g.:
1139     //     .gprel32 LBB123
1140     MCSymbol *MBBSym = MBB->getSymbol();
1141     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1142     return;
1143   }
1144
1145   case MachineJumpTableInfo::EK_LabelDifference32: {
1146     // EK_LabelDifference32 - Each entry is the address of the block minus
1147     // the address of the jump table.  This is used for PIC jump tables where
1148     // gprel32 is not supported.  e.g.:
1149     //      .word LBB123 - LJTI1_2
1150     // If the .set directive is supported, this is emitted as:
1151     //      .set L4_5_set_123, LBB123 - LJTI1_2
1152     //      .word L4_5_set_123
1153
1154     // If we have emitted set directives for the jump table entries, print
1155     // them rather than the entries themselves.  If we're emitting PIC, then
1156     // emit the table entries as differences between two text section labels.
1157     if (MAI->hasSetDirective()) {
1158       // If we used .set, reference the .set's symbol.
1159       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1160                                       OutContext);
1161       break;
1162     }
1163     // Otherwise, use the difference as the jump table entry.
1164     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1165     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1166     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1167     break;
1168   }
1169   }
1170
1171   assert(Value && "Unknown entry kind!");
1172
1173   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1174   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1175 }
1176
1177
1178 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1179 /// special global used by LLVM.  If so, emit it and return true, otherwise
1180 /// do nothing and return false.
1181 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1182   if (GV->getName() == "llvm.used") {
1183     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1184       EmitLLVMUsedList(GV->getInitializer());
1185     return true;
1186   }
1187
1188   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1189   if (GV->getSection() == "llvm.metadata" ||
1190       GV->hasAvailableExternallyLinkage())
1191     return true;
1192
1193   if (!GV->hasAppendingLinkage()) return false;
1194
1195   assert(GV->hasInitializer() && "Not a special LLVM global!");
1196
1197   const TargetData *TD = TM.getTargetData();
1198   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1199   if (GV->getName() == "llvm.global_ctors") {
1200     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1201     EmitAlignment(Align);
1202     EmitXXStructorList(GV->getInitializer());
1203
1204     if (TM.getRelocationModel() == Reloc::Static &&
1205         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1206       StringRef Sym(".constructors_used");
1207       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1208                                       MCSA_Reference);
1209     }
1210     return true;
1211   }
1212
1213   if (GV->getName() == "llvm.global_dtors") {
1214     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1215     EmitAlignment(Align);
1216     EmitXXStructorList(GV->getInitializer());
1217
1218     if (TM.getRelocationModel() == Reloc::Static &&
1219         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1220       StringRef Sym(".destructors_used");
1221       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1222                                       MCSA_Reference);
1223     }
1224     return true;
1225   }
1226
1227   return false;
1228 }
1229
1230 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1231 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1232 /// is true, as being used with this directive.
1233 void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
1234   // Should be an array of 'i8*'.
1235   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1236   if (InitList == 0) return;
1237
1238   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1239     const GlobalValue *GV =
1240       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1241     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1242       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1243   }
1244 }
1245
1246 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the
1247 /// function pointers, ignoring the init priority.
1248 void AsmPrinter::EmitXXStructorList(const Constant *List) {
1249   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1250   // init priority, which we ignore.
1251   if (!isa<ConstantArray>(List)) return;
1252   const ConstantArray *InitList = cast<ConstantArray>(List);
1253   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1254     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1255       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
1256
1257       if (CS->getOperand(1)->isNullValue())
1258         return;  // Found a null terminator, exit printing.
1259       // Emit the function pointer.
1260       EmitGlobalConstant(CS->getOperand(1));
1261     }
1262 }
1263
1264 //===--------------------------------------------------------------------===//
1265 // Emission and print routines
1266 //
1267
1268 /// EmitInt8 - Emit a byte directive and value.
1269 ///
1270 void AsmPrinter::EmitInt8(int Value) const {
1271   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1272 }
1273
1274 /// EmitInt16 - Emit a short directive and value.
1275 ///
1276 void AsmPrinter::EmitInt16(int Value) const {
1277   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1278 }
1279
1280 /// EmitInt32 - Emit a long directive and value.
1281 ///
1282 void AsmPrinter::EmitInt32(int Value) const {
1283   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1284 }
1285
1286 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1287 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1288 /// labels.  This implicitly uses .set if it is available.
1289 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1290                                      unsigned Size) const {
1291   // Get the Hi-Lo expression.
1292   const MCExpr *Diff =
1293     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1294                             MCSymbolRefExpr::Create(Lo, OutContext),
1295                             OutContext);
1296
1297   if (!MAI->hasSetDirective()) {
1298     OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1299     return;
1300   }
1301
1302   // Otherwise, emit with .set (aka assignment).
1303   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1304   OutStreamer.EmitAssignment(SetLabel, Diff);
1305   OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1306 }
1307
1308 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1309 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1310 /// specify the labels.  This implicitly uses .set if it is available.
1311 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1312                                            const MCSymbol *Lo, unsigned Size)
1313   const {
1314
1315   // Emit Hi+Offset - Lo
1316   // Get the Hi+Offset expression.
1317   const MCExpr *Plus =
1318     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1319                             MCConstantExpr::Create(Offset, OutContext),
1320                             OutContext);
1321
1322   // Get the Hi+Offset-Lo expression.
1323   const MCExpr *Diff =
1324     MCBinaryExpr::CreateSub(Plus,
1325                             MCSymbolRefExpr::Create(Lo, OutContext),
1326                             OutContext);
1327
1328   if (!MAI->hasSetDirective())
1329     OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1330   else {
1331     // Otherwise, emit with .set (aka assignment).
1332     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1333     OutStreamer.EmitAssignment(SetLabel, Diff);
1334     OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1335   }
1336 }
1337
1338 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1339 /// where the size in bytes of the directive is specified by Size and Label
1340 /// specifies the label.  This implicitly uses .set if it is available.
1341 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1342                                       unsigned Size)
1343   const {
1344
1345   // Emit Label+Offset
1346   const MCExpr *Plus =
1347     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1348                             MCConstantExpr::Create(Offset, OutContext),
1349                             OutContext);
1350
1351   OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1352 }
1353
1354
1355 //===----------------------------------------------------------------------===//
1356
1357 // EmitAlignment - Emit an alignment directive to the specified power of
1358 // two boundary.  For example, if you pass in 3 here, you will get an 8
1359 // byte alignment.  If a global value is specified, and if that global has
1360 // an explicit alignment requested, it will override the alignment request
1361 // if required for correctness.
1362 //
1363 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1364   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1365
1366   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1367
1368   if (getCurrentSection()->getKind().isText())
1369     OutStreamer.EmitCodeAlignment(1 << NumBits);
1370   else
1371     OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1372 }
1373
1374 //===----------------------------------------------------------------------===//
1375 // Constant emission.
1376 //===----------------------------------------------------------------------===//
1377
1378 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1379 ///
1380 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1381   MCContext &Ctx = AP.OutContext;
1382
1383   if (CV->isNullValue() || isa<UndefValue>(CV))
1384     return MCConstantExpr::Create(0, Ctx);
1385
1386   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1387     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1388
1389   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1390     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1391
1392   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1393     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1394
1395   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1396   if (CE == 0) {
1397     llvm_unreachable("Unknown constant value to lower!");
1398     return MCConstantExpr::Create(0, Ctx);
1399   }
1400
1401   switch (CE->getOpcode()) {
1402   default:
1403     // If the code isn't optimized, there may be outstanding folding
1404     // opportunities. Attempt to fold the expression using TargetData as a
1405     // last resort before giving up.
1406     if (Constant *C =
1407           ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1408       if (C != CE)
1409         return LowerConstant(C, AP);
1410
1411     // Otherwise report the problem to the user.
1412     {
1413       std::string S;
1414       raw_string_ostream OS(S);
1415       OS << "Unsupported expression in static initializer: ";
1416       WriteAsOperand(OS, CE, /*PrintType=*/false,
1417                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1418       report_fatal_error(OS.str());
1419     }
1420     return MCConstantExpr::Create(0, Ctx);
1421   case Instruction::GetElementPtr: {
1422     const TargetData &TD = *AP.TM.getTargetData();
1423     // Generate a symbolic expression for the byte address
1424     const Constant *PtrVal = CE->getOperand(0);
1425     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1426     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1427                                          IdxVec.size());
1428
1429     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1430     if (Offset == 0)
1431       return Base;
1432
1433     // Truncate/sext the offset to the pointer size.
1434     if (TD.getPointerSizeInBits() != 64) {
1435       int SExtAmount = 64-TD.getPointerSizeInBits();
1436       Offset = (Offset << SExtAmount) >> SExtAmount;
1437     }
1438
1439     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1440                                    Ctx);
1441   }
1442
1443   case Instruction::Trunc:
1444     // We emit the value and depend on the assembler to truncate the generated
1445     // expression properly.  This is important for differences between
1446     // blockaddress labels.  Since the two labels are in the same function, it
1447     // is reasonable to treat their delta as a 32-bit value.
1448     // FALL THROUGH.
1449   case Instruction::BitCast:
1450     return LowerConstant(CE->getOperand(0), AP);
1451
1452   case Instruction::IntToPtr: {
1453     const TargetData &TD = *AP.TM.getTargetData();
1454     // Handle casts to pointers by changing them into casts to the appropriate
1455     // integer type.  This promotes constant folding and simplifies this code.
1456     Constant *Op = CE->getOperand(0);
1457     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1458                                       false/*ZExt*/);
1459     return LowerConstant(Op, AP);
1460   }
1461
1462   case Instruction::PtrToInt: {
1463     const TargetData &TD = *AP.TM.getTargetData();
1464     // Support only foldable casts to/from pointers that can be eliminated by
1465     // changing the pointer to the appropriately sized integer type.
1466     Constant *Op = CE->getOperand(0);
1467     const Type *Ty = CE->getType();
1468
1469     const MCExpr *OpExpr = LowerConstant(Op, AP);
1470
1471     // We can emit the pointer value into this slot if the slot is an
1472     // integer slot equal to the size of the pointer.
1473     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1474       return OpExpr;
1475
1476     // Otherwise the pointer is smaller than the resultant integer, mask off
1477     // the high bits so we are sure to get a proper truncation if the input is
1478     // a constant expr.
1479     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1480     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1481     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1482   }
1483
1484   // The MC library also has a right-shift operator, but it isn't consistently
1485   // signed or unsigned between different targets.
1486   case Instruction::Add:
1487   case Instruction::Sub:
1488   case Instruction::Mul:
1489   case Instruction::SDiv:
1490   case Instruction::SRem:
1491   case Instruction::Shl:
1492   case Instruction::And:
1493   case Instruction::Or:
1494   case Instruction::Xor: {
1495     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1496     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1497     switch (CE->getOpcode()) {
1498     default: llvm_unreachable("Unknown binary operator constant cast expr");
1499     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1500     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1501     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1502     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1503     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1504     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1505     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1506     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1507     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1508     }
1509   }
1510   }
1511 }
1512
1513 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1514                                    AsmPrinter &AP);
1515
1516 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1517                                     AsmPrinter &AP) {
1518   if (AddrSpace != 0 || !CA->isString()) {
1519     // Not a string.  Print the values in successive locations
1520     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1521       EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1522     return;
1523   }
1524
1525   // Otherwise, it can be emitted as .ascii.
1526   SmallVector<char, 128> TmpVec;
1527   TmpVec.reserve(CA->getNumOperands());
1528   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1529     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1530
1531   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1532 }
1533
1534 static void EmitGlobalConstantVector(const ConstantVector *CV,
1535                                      unsigned AddrSpace, AsmPrinter &AP) {
1536   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1537     EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1538
1539   const TargetData &TD = *AP.TM.getTargetData();
1540   unsigned Size = TD.getTypeAllocSize(CV->getType());
1541   unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
1542                          CV->getType()->getNumElements();
1543   if (unsigned Padding = Size - EmittedSize)
1544     AP.OutStreamer.EmitZeros(Padding, AddrSpace);
1545 }
1546
1547 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1548                                      unsigned AddrSpace, AsmPrinter &AP) {
1549   // Print the fields in successive locations. Pad to align if needed!
1550   const TargetData *TD = AP.TM.getTargetData();
1551   unsigned Size = TD->getTypeAllocSize(CS->getType());
1552   const StructLayout *Layout = TD->getStructLayout(CS->getType());
1553   uint64_t SizeSoFar = 0;
1554   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1555     const Constant *Field = CS->getOperand(i);
1556
1557     // Check if padding is needed and insert one or more 0s.
1558     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1559     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1560                         - Layout->getElementOffset(i)) - FieldSize;
1561     SizeSoFar += FieldSize + PadSize;
1562
1563     // Now print the actual field value.
1564     EmitGlobalConstantImpl(Field, AddrSpace, AP);
1565
1566     // Insert padding - this may include padding to increase the size of the
1567     // current field up to the ABI size (if the struct is not packed) as well
1568     // as padding to ensure that the next field starts at the right offset.
1569     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1570   }
1571   assert(SizeSoFar == Layout->getSizeInBytes() &&
1572          "Layout of constant struct may be incorrect!");
1573 }
1574
1575 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1576                                  AsmPrinter &AP) {
1577   // FP Constants are printed as integer constants to avoid losing
1578   // precision.
1579   if (CFP->getType()->isDoubleTy()) {
1580     if (AP.isVerbose()) {
1581       double Val = CFP->getValueAPF().convertToDouble();
1582       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1583     }
1584
1585     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1586     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1587     return;
1588   }
1589
1590   if (CFP->getType()->isFloatTy()) {
1591     if (AP.isVerbose()) {
1592       float Val = CFP->getValueAPF().convertToFloat();
1593       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1594     }
1595     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1596     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1597     return;
1598   }
1599
1600   if (CFP->getType()->isX86_FP80Ty()) {
1601     // all long double variants are printed as hex
1602     // API needed to prevent premature destruction
1603     APInt API = CFP->getValueAPF().bitcastToAPInt();
1604     const uint64_t *p = API.getRawData();
1605     if (AP.isVerbose()) {
1606       // Convert to double so we can print the approximate val as a comment.
1607       APFloat DoubleVal = CFP->getValueAPF();
1608       bool ignored;
1609       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1610                         &ignored);
1611       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1612         << DoubleVal.convertToDouble() << '\n';
1613     }
1614
1615     if (AP.TM.getTargetData()->isBigEndian()) {
1616       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1617       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1618     } else {
1619       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1620       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1621     }
1622
1623     // Emit the tail padding for the long double.
1624     const TargetData &TD = *AP.TM.getTargetData();
1625     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1626                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1627     return;
1628   }
1629
1630   assert(CFP->getType()->isPPC_FP128Ty() &&
1631          "Floating point constant type not handled");
1632   // All long double variants are printed as hex
1633   // API needed to prevent premature destruction.
1634   APInt API = CFP->getValueAPF().bitcastToAPInt();
1635   const uint64_t *p = API.getRawData();
1636   if (AP.TM.getTargetData()->isBigEndian()) {
1637     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1638     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1639   } else {
1640     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1641     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1642   }
1643 }
1644
1645 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1646                                        unsigned AddrSpace, AsmPrinter &AP) {
1647   const TargetData *TD = AP.TM.getTargetData();
1648   unsigned BitWidth = CI->getBitWidth();
1649   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1650
1651   // We don't expect assemblers to support integer data directives
1652   // for more than 64 bits, so we emit the data in at most 64-bit
1653   // quantities at a time.
1654   const uint64_t *RawData = CI->getValue().getRawData();
1655   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1656     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1657     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1658   }
1659 }
1660
1661 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1662                                    AsmPrinter &AP) {
1663   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1664     uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1665     return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1666   }
1667
1668   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1669     unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1670     switch (Size) {
1671     case 1:
1672     case 2:
1673     case 4:
1674     case 8:
1675       if (AP.isVerbose())
1676         AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1677       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1678       return;
1679     default:
1680       EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1681       return;
1682     }
1683   }
1684
1685   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1686     return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1687
1688   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1689     return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1690
1691   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1692     return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1693
1694   if (isa<ConstantPointerNull>(CV)) {
1695     unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1696     AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1697     return;
1698   }
1699
1700   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1701     return EmitGlobalConstantVector(V, AddrSpace, AP);
1702
1703   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1704   // thread the streamer with EmitValue.
1705   AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1706                          AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1707                            AddrSpace);
1708 }
1709
1710 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1711 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1712   uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1713   if (Size)
1714     EmitGlobalConstantImpl(CV, AddrSpace, *this);
1715   else if (MAI->hasSubsectionsViaSymbols()) {
1716     // If the global has zero size, emit a single byte so that two labels don't
1717     // look like they are at the same location.
1718     OutStreamer.EmitIntValue(0, 1, AddrSpace);
1719   }
1720 }
1721
1722 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1723   // Target doesn't support this yet!
1724   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1725 }
1726
1727 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1728   if (Offset > 0)
1729     OS << '+' << Offset;
1730   else if (Offset < 0)
1731     OS << Offset;
1732 }
1733
1734 //===----------------------------------------------------------------------===//
1735 // Symbol Lowering Routines.
1736 //===----------------------------------------------------------------------===//
1737
1738 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1739 /// temporary label with the specified stem and unique ID.
1740 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1741   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1742                                       Name + Twine(ID));
1743 }
1744
1745 /// GetTempSymbol - Return an assembler temporary label with the specified
1746 /// stem.
1747 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1748   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1749                                       Name);
1750 }
1751
1752
1753 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1754   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1755 }
1756
1757 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1758   return MMI->getAddrLabelSymbol(BB);
1759 }
1760
1761 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1762 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1763   return OutContext.GetOrCreateSymbol
1764     (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1765      + "_" + Twine(CPID));
1766 }
1767
1768 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1769 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1770   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1771 }
1772
1773 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1774 /// FIXME: privatize to AsmPrinter.
1775 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1776   return OutContext.GetOrCreateSymbol
1777   (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1778    Twine(UID) + "_set_" + Twine(MBBID));
1779 }
1780
1781 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1782 /// global value name as its base, with the specified suffix, and where the
1783 /// symbol is forced to have private linkage if ForcePrivate is true.
1784 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1785                                                    StringRef Suffix,
1786                                                    bool ForcePrivate) const {
1787   SmallString<60> NameStr;
1788   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1789   NameStr.append(Suffix.begin(), Suffix.end());
1790   return OutContext.GetOrCreateSymbol(NameStr.str());
1791 }
1792
1793 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1794 /// ExternalSymbol.
1795 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1796   SmallString<60> NameStr;
1797   Mang->getNameWithPrefix(NameStr, Sym);
1798   return OutContext.GetOrCreateSymbol(NameStr.str());
1799 }
1800
1801
1802
1803 /// PrintParentLoopComment - Print comments about parent loops of this one.
1804 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1805                                    unsigned FunctionNumber) {
1806   if (Loop == 0) return;
1807   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1808   OS.indent(Loop->getLoopDepth()*2)
1809     << "Parent Loop BB" << FunctionNumber << "_"
1810     << Loop->getHeader()->getNumber()
1811     << " Depth=" << Loop->getLoopDepth() << '\n';
1812 }
1813
1814
1815 /// PrintChildLoopComment - Print comments about child loops within
1816 /// the loop for this basic block, with nesting.
1817 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1818                                   unsigned FunctionNumber) {
1819   // Add child loop information
1820   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1821     OS.indent((*CL)->getLoopDepth()*2)
1822       << "Child Loop BB" << FunctionNumber << "_"
1823       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1824       << '\n';
1825     PrintChildLoopComment(OS, *CL, FunctionNumber);
1826   }
1827 }
1828
1829 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1830 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1831                                        const MachineLoopInfo *LI,
1832                                        const AsmPrinter &AP) {
1833   // Add loop depth information
1834   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1835   if (Loop == 0) return;
1836
1837   MachineBasicBlock *Header = Loop->getHeader();
1838   assert(Header && "No header for loop");
1839
1840   // If this block is not a loop header, just print out what is the loop header
1841   // and return.
1842   if (Header != &MBB) {
1843     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1844                               Twine(AP.getFunctionNumber())+"_" +
1845                               Twine(Loop->getHeader()->getNumber())+
1846                               " Depth="+Twine(Loop->getLoopDepth()));
1847     return;
1848   }
1849
1850   // Otherwise, it is a loop header.  Print out information about child and
1851   // parent loops.
1852   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1853
1854   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1855
1856   OS << "=>";
1857   OS.indent(Loop->getLoopDepth()*2-2);
1858
1859   OS << "This ";
1860   if (Loop->empty())
1861     OS << "Inner ";
1862   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1863
1864   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1865 }
1866
1867
1868 /// EmitBasicBlockStart - This method prints the label for the specified
1869 /// MachineBasicBlock, an alignment (if present) and a comment describing
1870 /// it if appropriate.
1871 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1872   // Emit an alignment directive for this block, if needed.
1873   if (unsigned Align = MBB->getAlignment())
1874     EmitAlignment(Log2_32(Align));
1875
1876   // If the block has its address taken, emit any labels that were used to
1877   // reference the block.  It is possible that there is more than one label
1878   // here, because multiple LLVM BB's may have been RAUW'd to this block after
1879   // the references were generated.
1880   if (MBB->hasAddressTaken()) {
1881     const BasicBlock *BB = MBB->getBasicBlock();
1882     if (isVerbose())
1883       OutStreamer.AddComment("Block address taken");
1884
1885     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1886
1887     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1888       OutStreamer.EmitLabel(Syms[i]);
1889   }
1890
1891   // Print the main label for the block.
1892   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1893     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1894       if (const BasicBlock *BB = MBB->getBasicBlock())
1895         if (BB->hasName())
1896           OutStreamer.AddComment("%" + BB->getName());
1897
1898       EmitBasicBlockLoopComments(*MBB, LI, *this);
1899
1900       // NOTE: Want this comment at start of line, don't emit with AddComment.
1901       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1902                               Twine(MBB->getNumber()) + ":");
1903     }
1904   } else {
1905     if (isVerbose()) {
1906       if (const BasicBlock *BB = MBB->getBasicBlock())
1907         if (BB->hasName())
1908           OutStreamer.AddComment("%" + BB->getName());
1909       EmitBasicBlockLoopComments(*MBB, LI, *this);
1910     }
1911
1912     OutStreamer.EmitLabel(MBB->getSymbol());
1913   }
1914 }
1915
1916 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
1917                                 bool IsDefinition) const {
1918   MCSymbolAttr Attr = MCSA_Invalid;
1919
1920   switch (Visibility) {
1921   default: break;
1922   case GlobalValue::HiddenVisibility:
1923     if (IsDefinition)
1924       Attr = MAI->getHiddenVisibilityAttr();
1925     else
1926       Attr = MAI->getHiddenDeclarationVisibilityAttr();
1927     break;
1928   case GlobalValue::ProtectedVisibility:
1929     Attr = MAI->getProtectedVisibilityAttr();
1930     break;
1931   }
1932
1933   if (Attr != MCSA_Invalid)
1934     OutStreamer.EmitSymbolAttribute(Sym, Attr);
1935 }
1936
1937 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1938 /// exactly one predecessor and the control transfer mechanism between
1939 /// the predecessor and this block is a fall-through.
1940 bool AsmPrinter::
1941 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1942   // If this is a landing pad, it isn't a fall through.  If it has no preds,
1943   // then nothing falls through to it.
1944   if (MBB->isLandingPad() || MBB->pred_empty())
1945     return false;
1946
1947   // If there isn't exactly one predecessor, it can't be a fall through.
1948   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1949   ++PI2;
1950   if (PI2 != MBB->pred_end())
1951     return false;
1952
1953   // The predecessor has to be immediately before this block.
1954   MachineBasicBlock *Pred = *PI;
1955
1956   if (!Pred->isLayoutSuccessor(MBB))
1957     return false;
1958
1959   // If the block is completely empty, then it definitely does fall through.
1960   if (Pred->empty())
1961     return true;
1962
1963   // Check the terminators in the previous blocks
1964   for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
1965          IE = Pred->end(); II != IE; ++II) {
1966     MachineInstr &MI = *II;
1967
1968     // If it is not a simple branch, we are in a table somewhere.
1969     if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
1970       return false;
1971
1972     // If we are the operands of one of the branches, this is not
1973     // a fall through.
1974     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
1975            OE = MI.operands_end(); OI != OE; ++OI) {
1976       const MachineOperand& OP = *OI;
1977       if (OP.isJTI())
1978         return false;
1979       if (OP.isMBB() && OP.getMBB() == MBB)
1980         return false;
1981     }
1982   }
1983
1984   return true;
1985 }
1986
1987
1988
1989 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1990   if (!S->usesMetadata())
1991     return 0;
1992
1993   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1994   gcp_map_type::iterator GCPI = GCMap.find(S);
1995   if (GCPI != GCMap.end())
1996     return GCPI->second;
1997
1998   const char *Name = S->getName().c_str();
1999
2000   for (GCMetadataPrinterRegistry::iterator
2001          I = GCMetadataPrinterRegistry::begin(),
2002          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2003     if (strcmp(Name, I->getName()) == 0) {
2004       GCMetadataPrinter *GMP = I->instantiate();
2005       GMP->S = S;
2006       GCMap.insert(std::make_pair(S, GMP));
2007       return GMP;
2008     }
2009
2010   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2011   return 0;
2012 }
2013